Skip to content

feat: reuse same cluster across a stage and slow delete at the end - #1039

Merged
Johnson Isaac Joseph (j-isaac-joseph) merged 47 commits into
feature/swiftv2GA/swiftv2scalefrom
users/isaac/feat-nodescale
Feb 9, 2026
Merged

Johnson Isaac Joseph (j-isaac-joseph) merged 47 commits into
feature/swiftv2GA/swiftv2scalefrom
users/isaac/feat-nodescale

Conversation

@j-isaac-joseph

@j-isaac-joseph Johnson Isaac Joseph (j-isaac-joseph) commented Jan 29, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR refactors the SwiftV2 pipeline architecture to support per-stage resource management, job isolation, improved cleanup procedures, and optimized prepull operations.


Key Changes

1. Pipeline Architecture Restructuring

  • Moved run ID generation from a global stage to per-stage jobs using the new generate-run-id.yml template
  • Each stage now owns a generate_run_id job with a stage-specific prefix:
    • sg, dg, sb, db
  • Added per-stage cleanup jobs using the new cleanup.yml template
  • Replaced CLEANUP_RESOURCES with the new unified CLEANUP variable

2. Job Isolation with CL2_JOB_INDEX

  • Introduced CL2_JOB_INDEX (derived from System.JobId) to isolate resources across parallel and sequential jobs
  • Namespace isolation:
    • slo-job{{$jobIndex}}
  • Resource naming now includes job index to prevent collisions:
    • pod-network-instance-job{{$jobIndex}}-{{$j}}
    • deployment-churn-job{{$jobIndex}}-{{$j}}
    • group={{$groupName}}-job{{$jobIndex}}-{{$j}}

3. Auto-Detection of Existing Pods

  • Added Query Existing Pod Count step in execute.yml
  • Queries the cluster for existing deployment-churn pods
  • Passes EXISTING_PODS into CL2 config
  • CL2 configs now dynamically calculate:
    • deltaPods
    • actualPodsPerStep
      based on existing cluster state

4. New Shell Script Libraries

  • common.sh
    • Cancellation handling
    • Retry logic
    • Nodepool / cluster wait helpers
  • nodepool.sh
    • Nodepool creation and verification
    • Idempotent provisioning helpers

5. New Cleanup Scripts

  • cleanup-azure-resources.sh
    • Deletes AKS clusters
    • Removes NAT gateways, NSGs, and public IPs
  • cleanup-swiftv2-workloads.sh
    • Deletes deployments and pods by label
    • Sequentially removes user nodepools
  • ensure-nodepools.sh
    • Idempotent nodepool provisioning with sharding support

6. Simplified Cleanup Process

  • Removed terraform destroy steps from cleanup
  • Cleanup now uses Azure CLI directly via AzureCLI@2 tasks for proper authentication
  • Resources are identified using RESOURCE_GROUP_NAME instead of RUN_ID

7. Prepull Optimization

  • Tracks prepulled nodes using labels:
    • image-prepull-{hash}=true
  • Skips prepull on nodes that already contain required images from previous runs
  • Added mark_nodes_prepulled() with retry logic for robustness

8. Improved Cancellation Handling

  • Added handle_cancellation and check_cancellation across scripts
  • Scale operations, VM repairs, and node labeling now properly handle SIGTERM / SIGINT
  • Ensures graceful exit on pipeline cancellation with clear logging

9. Node Labeling Improvements

  • Added utility helpers:
    • label_nodes_with_retry()
    • batch_label_nodes()
  • Labels only previously unlabeled nodes (accounts for reuse across runs)
  • Added retry mechanism with exponential backoff for resiliency
    ``

… pipeline

Refactor Azure DevOps pipeline to support efficient cluster reuse across
matrix jobs while maintaining result isolation through a dual-ID system.

BREAKING CHANGE: Removed global CLEANUP_RESOURCES variable in favor of
matrix-level skip_cleanup and reuse_cluster flags for better control.

Features:
- Add reuse_cluster and skip_cleanup flags to all matrix files
- Implement dual-ID system: RUN_ID (unique) and SHARED_RUN_ID (shared)
- Add SHARED_RUN_ID to telescope metadata for job correlation
- Derive CL2_JOB_INDEX automatically from System.JobId
- Add job_index to pod labels for measurement isolation

Fixes:
- Fix cluster discovery to use SHARED_RUN_ID when reusing clusters
- Fix createclusterforping.sh to only run when reuse_cluster=false
- Add SHARED_RUN_ID env var to scale-cluster and prepull-images steps
- Update aks-utils.sh and update-kubeconfig.yml cluster queries

Performance:
- Enable sequential cluster reuse pattern (create once, scale multiple times)
- Remove redundant 'Scale Existing AKS Cluster' step from provision-resources
- Consolidate all nodepool scaling logic in scale-cluster.sh

Documentation:
- Add comprehensive cluster reuse documentation to running-swiftv2-pipeline.md
- Document dual-ID system and how cluster discovery works
- Explain result storage and why overwrites don't occur

Files changed:
- Matrix configs: Add reuse_cluster/skip_cleanup to 28 test entries (4 files)
- Pipeline: Remove CLEANUP_RESOURCES, add cleanup parameter passing
- Steps: Add reuse_cluster/skip_cleanup parameters and conditions
- Scripts: Update cluster discovery to use SHARED_RUN_ID
- CL2 configs: Add job_index to pod labels and PNI names
- Metadata: Include shared_run_id in telescope metadata

This enables running 7 tests on one cluster instead of creating/destroying
7 separate clusters, reducing test time from ~40 hours to ~25 hours.
… string

Azure DevOps cannot evaluate runtime variables like $(reuse_cluster) as
boolean parameters, causing pipeline parsing errors.

Changes:
- Change reuse_cluster parameter from 'type: boolean' to 'type: string'
  with default: 'false' in provision-resources.yml
- Change skip_cleanup parameter from 'type: boolean' to 'type: string'
  with default: 'false' in cleanup-resources.yml

Impact:
- Allows matrix variables to be passed as runtime values
- All existing conditions already use string comparisons (eq()), so no
  functional changes required
- Fixes ADO parsing errors:
  * "The 'reuse_cluster' parameter value '$(reuse_cluster)' is not a valid Boolean"
  * "Key not found 'reuse_cluster'" in multiple template conditions

This maintains backward compatibility while enabling runtime variable
evaluation from matrix configurations.
… variables

- Change conditions from compile-time parameters to runtime variables
- Fix reuse_cluster checks in provision-resources.yml
- Fix skip_cleanup checks in cleanup-resources.yml
- Remove compile-time conditional for terraform destroy step
- Simplify conditions to check only lowercase values per matrix definitions
- Set SKIP_RESOURCE_MANAGEMENT variable instead of adding condition to template
- Template already checks this variable internally for skip logic
…ry env declarations

When SHARED_RUN_ID/shared_run_id variables are not set, ADO passes literal
unexpanded strings like $(SHARED_RUN_ID) instead of empty values. This caused:
- Bash command substitution errors (exit code 127)
- Azure CLI queries failing with literal strings in tag filters

Changes:
- setup-tests.yml: Add pattern check to detect unexpanded $(shared_run_id)
- provision-resources.yml: Validate shared_run_id parameter isn't unexpanded
- scale-cluster.yml: Remove redundant RUN_ID/SHARED_RUN_ID (inherited from setup-tests.yml)
- prepull-images.yml: Remove unused REGION/ROLE/RUN_ID/SHARED_RUN_ID env vars
- collect-telescope-metadata.yml: Remove unnecessary sanitization (no explicit env var)
- aks-utils.sh: Remove redundant check (variables validated upstream)
- update-kubeconfig.yml: Revert changes (variables inherited and working)

Validation now happens at entry points (setup-tests.yml, provision-resources.yml)
with subsequent steps relying on inherited pipeline variables. This fixes the
first matrix entry (reuse_cluster: false) where SHARED_RUN_ID is not set.
…echanism

- Skip image prepull on nodes already labeled from previous jobs
  - Calculate hash of image set to track prepull state
  - Filter nodes by prepull label to identify already-processed nodes
  - Only prepull on new/unlabeled nodes when reusing clusters
  - Reduces prepull time by ~50% in cluster reuse scenarios

- Add common node labeling utility with retry mechanism
  - Create label_nodes_with_retry() in aks-utils.sh
  - 3 retry attempts with 30s delays between failures
  - Per-node tracking only retries failed nodes
  - Handles transient kubectl API failures gracefully

- Refactor duplicate labeling code across scripts
  - Replace inline retry logic in scale-cluster.sh with common function
  - Replace simple xargs labeling in prepull-images.sh with retry function
  - Eliminate ~100 lines of duplicate code
  - Single source of truth for retry parameters

Improves reliability for large-scale operations (1000+ nodes) where API
throttling and transient failures are common.

Resolves cluster reuse optimization for swiftv2 pipeline pattern.
Use single quotes when assigning shared_run_id parameter to prevent bash
from interpreting $(shared_run_id) as command substitution when the ADO
runtime variable is unexpanded. This fixes 'command not found' errors in
cluster reuse scenarios.
…plate parameter

The script was attempting to use template parameter syntax which was receiving
the literal string '' at compile time. Changed to directly
reference the runtime variable  which properly expands during
pipeline execution.

Fixes error: 'reuse_cluster is true but shared_run_id is not provided or unexpanded'
…template parameter

Remove shared_run_id from provision-resources.yml template parameters as it's
set as a pipeline variable in setup-tests.yml. Access it directly via env
section using runtime variable syntax .

This fixes the issue where template parameters can't access runtime variables
set during pipeline execution, causing the variable to appear unexpanded.
…directly

BREAKING CHANGE: Remove SHARED_RUN_ID pipeline variable

Simplify cluster reuse logic by using BASE_RUN_ID directly instead of
creating an intermediate SHARED_RUN_ID variable that was just a copy.

Changes:
- Remove SHARED_RUN_ID variable setting from setup-tests.yml
- Update provision-resources.yml to use BASE_RUN_ID for shared resource groups
- Update update-kubeconfig.yml and aks-utils.sh to explicitly check
  reuse_cluster before choosing BASE_RUN_ID vs RUN_ID
- Update metadata collection to use base_run_id field
- Remove redundant resource group validation step in provision-resources.yml
- Consolidate resource group creation logic into single step

Resource group naming now works correctly:
- First job (reuse_cluster=false): Creates RG named BASE_RUN_ID
- Subsequent jobs (reuse_cluster=true): Find RG named BASE_RUN_ID
- All jobs use unique RUN_ID for test result isolation
Update documentation to reflect code changes that eliminated SHARED_RUN_ID:
- Replace references to shared_run_id with BASE_RUN_ID
- Update metadata field name from shared_run_id to base_run_id
- Clarify cluster discovery logic with explicit reuse_cluster check
- Update RUN_ID generation description (BASE_RUN_ID + job suffix)

The documentation now accurately describes how BASE_RUN_ID is used directly
for cluster discovery and resource group naming in reuse scenarios.
- Remove terraform parameters from competitive-test.yml job template
- Remove terraform setup and command templates from provision-resources.yml
- Remove terraform destroy steps from cleanup-resources.yml
- Set deletion_due_time to 1 week instead of reading from terraform input
- Set owner to Build.RequestedFor (ADO pipeline runner)
…tern

Align RG variable assignment with provision-resources.yml pattern:
- When reuse_cluster=false and BASE_RUN_ID is set, use BASE_RUN_ID
  so subsequent matrix jobs can find the cluster
- Otherwise use RUN_ID for standalone jobs

This ensures createclusterforping.sh creates the cluster in the
same resource group that provision-resources.yml expects.
- Remove job index suffix from PodGroup label selector in swiftv2
  deployment configs to aggregate metrics across all jobs
- Fix bash array handling for space-separated nodepool labels by
  splitting them into individual elements for az cli command
Simplify resource group naming logic to always use BASE_RUN_ID since
it is always generated by the pipeline. This fixes cluster discovery
failures in the first matrix job where reuse_cluster=false but the
cluster was created with BASE_RUN_ID.

Previously, find_aks_cluster used RUN_ID when reuse_cluster=false,
but createclusterforping.sh created the cluster with BASE_RUN_ID,
causing ensure-nodepools.sh to fail finding the cluster.

- Remove reuse_cluster-based conditional logic
- Always use BASE_RUN_ID when present (normal case)
- Keep RUN_ID as defensive fallback with warning
…sioning

- Add steps/generate-run-id.yml for reusable run ID generation per stage
- Each stage now generates its own BASE_RUN_ID with stage-specific prefix
- Make resource group and AKS cluster creation idempotent (check exists first)
- Add jobs/cleanup.yml as dedicated cleanup job template
- Add CLEANUP variable to toggle resource cleanup on/off
- Remove reuse_cluster and skip_cleanup flags from all matrix files
- Centralize RESOURCE_GROUP_NAME as single source of truth
- Remove unused steps/terraform/run-command.yml

BREAKING CHANGE: Stages now operate independently with separate resource groups
Jobs within a stage were not waiting for generate_run_id job and could
not access BASE_RUN_ID output variable. Stage-level variables using
dependencies.X syntax only work for cross-stage references, not for
jobs within the same stage.

Changes:
- Add dependsOn parameter to competitive-test.yml and cleanup.yml jobs
- Add dependsOn parameter to all swiftv2 matrix templates
- Update new-pipeline-test.yml to pass job dependencies explicitly
- Use job-level dependency syntax for BASE_RUN_ID references

This ensures proper execution order:
generate_run_id -> test job (azure) -> cleanup
… steps

The provision-resources.yml step was failing with 'BASE_RUN_ID not set'
because the variable was only passed as a parameter to setup-tests.yml
but not exported as a pipeline variable for other steps in the same job.

This change exports BASE_RUN_ID via ##vso[task.setvariable] so that all
subsequent steps (provision-resources, collect-telescope-metadata, etc.)
can access it directly without requiring explicit parameter passing.
ADO runtime expressions ($[ ... ]) cannot be passed through template
parameters as they get treated as literal strings at compile time.

Changes:
- Define BASE_RUN_ID as job-level variable in competitive-test.yml and
  cleanup.yml using runtime expression directly
- Remove base_run_id parameter from templates since it's now a job variable
- Add generate_run_id to cleanup job dependencies to access output

This fixes resource group creation failing with literal expression string
instead of the resolved run ID value.
Cluster discovery was incorrectly using RUN_ID (which includes job suffix)
instead of RESOURCE_GROUP_NAME/BASE_RUN_ID (which matches the run_id tag
set during cluster creation).

Fixed in:
- steps/cloud/azure/update-kubeconfig.yml
- steps/engine/clusterloader2/cilium/scale-cluster.yml

RESOURCE_GROUP_NAME is the single source of truth set by provision-resources.yml
and matches the run_id tag on clusters.
…abeling

The label_swiftv2slo_nodes function was failing when nodes were already
labeled from a previous run. It would find only N unlabeled nodes but
compare against the total required count, causing spurious failures.

Changes:
- Count nodes already labeled with swiftv2slo=true before labeling
- Calculate additional nodes needed (total - already_labeled)
- Short-circuit if sufficient nodes are already labeled
- Only label the delta of unlabeled nodes
- Verify final total (already_labeled + newly_labeled) meets requirement
- Convert cleanup-resources.yml script steps to AzureCLI@2 tasks
- Add azureSubscription parameter for proper Azure authentication
- Fix 'Please run az login' errors in ADO pipeline cleanup phase
- Add swiftv2 workload cleanup step calling cleanup-swiftv2-workloads.sh
- Add Azure resource cleanup step calling cleanup-azure-resources.sh

New files:
- swiftv2kubeobjects/lib/common.sh: shared library with cancellation
  handling, retry logic, and wait functions
- swiftv2kubeobjects/cleanup-swiftv2-workloads.sh: cleanup deployments/
  pods and user nodepools one at a time
- swiftv2kubeobjects/cleanup-azure-resources.sh: force cleanup AKS
  clusters, NAT gateways, NSGs, public IPs before RG deletion

Updated files:
- swiftv2kubeobjects/lib/nodepool.sh: source common.sh
- swiftv2kubeobjects/createclusterforping.sh: source common.sh
- steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh: source common.sh
- steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh: add
  cancellation handling with trap and check_cancellation calls
Support reusing the same AKS cluster across multiple matrix jobs within
a pipeline stage by making namespace prefixes unique per job.

Problem: When reusing clusters, CL2 fails with 'pre-existing automanaged
namespaces found' because all jobs use the same 'slo' namespace prefix.

Solution:
- Change namespace prefix from 'slo' to 'slo-job{{jobIndex}}'
- Namespaces are now: slo-job0-1, slo-job1-1, slo-job2-1, etc.

Updated files:
- swiftv2_deployment_staticres_scale_config.yaml: prefix with jobIndex
- swiftv2_deployment_dynamicres_scale_config.yaml: prefix with jobIndex
- pni_readiness_checker_unified_template.yaml: use {{.Namespace}} instead
  of hardcoded slo-1
- cleanup-swiftv2-workloads.sh: match slo-job* namespace pattern
- datapath-observer deployment.yaml: remove --namespace flag, rely on
  label selector to watch pods across all namespaces
- collect-datapath-observer.yml: use labelSelector instead of namespace
- README.md: document multi-job namespace behavior
The azureSubscription input for AzureCLI@2 tasks requires the service
connection variable name, not the subscription ID variable.
…selector filtering

DatapathResult CRDs were storing pod labels only in spec.Labels, but
Kubernetes label selectors only work with metadata.labels. This caused
the labelSelector query parameter in the API to return empty results.

- Copy pod labels to ObjectMeta.Labels in addition to Spec.Labels
- Bump controller image to 2026.01.29.01
- Remove default value for CL2_JOB_INDEX in staticres and dynamicres configs
- Add CL2_JOB_INDEX to override file in slo.py
- Fixes namespace collision when running back-to-back tests on same cluster

Previously CL2_JOB_INDEX defaulted to 0, causing pre-existing namespace
errors when running parallel jobs. Now the pipeline must explicitly
provide a unique job index.
- Add AZURE_SUBSCRIPTION_ID validation to cleanup-swiftv2-workloads.sh
- Add AZURE_SUBSCRIPTION_ID validation to cleanup-azure-resources.sh
- Pass AZURE_SUBSCRIPTION_ID from cleanup-resources.yml to both scripts
- Remove fallback defaults to ensure correct subscription is always used
- Add CL2_EXISTING_PODS parameter to calculate delta pods to deploy
- Update CL2 config templates to compute actualPodsPerStep from delta
- Update slo.py to pass existing_pods parameter through CLI
- Update execute.yml to pass EXISTING_PODS env variable
- Simplify matrix files to 500-2000 nodes in 500 increments (7 pods/node)

This enables reusing clusters across test cases by only deploying the
incremental difference in pods rather than the full target count.
… replicas

The actualPodsPerStep variable was incorrectly calculated as (total_pods - existingPods),
which represents the total delta pods, not the per-step count. This caused each step
to create all delta pods instead of the configured pods_per_step amount.

For example, with pods_per_step=35 and total_pods=70, each step was creating 70 pods
instead of 35, causing pod scheduling failures due to insufficient node capacity.
The steps calculation was using total pod capacity (node_count * pods_per_node)
instead of accounting for existing_pods. This caused gradual scale tests to
create more steps than needed when existing_pods > 0.

For example, with node_count=20, pods_per_node=7, pods_per_step=35, existing_pods=70:
- Before: steps = 20 * 7 // 35 = 4 (creating 140 new pods)
- After:  steps = (140 - 70) // 35 = 2 (creating 70 new pods)
Add pipeline step to query existing deployment-churn pods by summing
deployment replica counts. This eliminates manual existing_pods config
in matrix files.

Changes:
- Add 'Query Existing Pod Count' step in execute.yml that queries
  deployments with label podgroup=deployment-churn and sums replicas
- Remove existing_pods parameter from all swiftv2 matrix files

Benefits:
- No manual calculation required for matrix entries
- Handles job retries/reruns correctly (always gets current state)
- Uses deployment replicas (not pod count) to avoid counting
  pending/failed pods
- Graceful fallback to 0 if no deployments or kubectl errors
…rement

- Add podgroup-job label to swiftv2_deployment_template.yaml
- Add podgroup-job label to swiftv2_deployment_single_pod_template.yaml
- Update PodStartupLatency labelSelector to use podgroup-job in staticres config
- Update PodStartupLatency labelSelector to use podgroup-job in dynamicres config
- Add PodGroupJob parameter to templateFillMap in both configs

The existing podgroup label is preserved for datapath-observer/controller
which needs to query all pods across jobs.
The variable name was misleading since podsPerStep already exists
and refers to the number of deployments per step. The renamed variable
represents the total pods for the entire job, clamped to 0.
The numPNIs variable was calculated based on actualPodsThisJob (total pods)
but used inside the step loop, causing 3500 PNIs to be created per step
instead of 50. This exhausted network capacity and caused pod timeouts.

Changed to numPNIsPerStep = podsPerStep / podsPerPNI to create only the
PNIs needed for each step.
…ing pod detection

The kubectl query to detect existing pods was searching for
deployments with label podgroup=deployment-churn, but this label
was only present on the Pod template, not on the Deployment object
itself. This caused existing_pods to always return 0, resulting in
over-provisioning pods across gradual scale jobs.
- Replace 'set -euo pipefail' with 'set +e' to continue on errors
- Remove SIGTERM/SIGINT trap handlers - scripts run to completion
- Add 'exit 0' to ensure subsequent pipeline steps always run
- Add batched deletion for deployments/PNIs (~500 items per batch)
- Use retry_command from common.sh for kubectl delete operations
- Add CLEANUP_BATCH_SIZE env var (default: 500) for configurable batching

This ensures cleanup scripts don't block the pipeline even if they
encounter errors, since subsequent scripts will cleanup the AKS
cluster and resource group anyway.
- Add verify_node_labels() function to aks-utils.sh for reusable label
  verification across scripts
- Verify batch nodes have both swiftv2slo=true AND batch label before
  creating prepull DaemonSet to prevent scheduling failures
- Add warning when DaemonSet desired count doesn't match verified count
- Skip batch if no nodes have both required labels

This fixes a race condition where nodes could be labeled with the batch
label but not yet have swiftv2slo=true visible to the scheduler, causing
pods to fail with NodeAffinity errors.
- Add SLOW_DELETE variable to pipeline (default: false)
- Add condition in cleanup-resources.yml to skip workload cleanup when SLOW_DELETE is not true
- When disabled, relies on cluster/RG deletion for cleanup
- Enables graceful cleanup of deployments, pods, and PNIs when set to true
…nuxagent

The azuresecuritylinuxagent DaemonSet runs on all nodes, consuming 1 pod
slot per node. Updated max_pods from 12 to 13 to accommodate:
- 5 kube-system DaemonSet pods
- 1 azuresecuritylinuxagent pod
- 7 deployment churn workload pods
@j-isaac-joseph
Johnson Isaac Joseph (j-isaac-joseph) merged commit 2655274 into feature/swiftv2GA/swiftv2scale Feb 9, 2026
1 of 3 checks passed
@j-isaac-joseph
Johnson Isaac Joseph (j-isaac-joseph) deleted the users/isaac/feat-nodescale branch February 9, 2026 20:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant