Skip to content

feat(crud): add AKSMachineClient non-batch scale path - #1181

Merged
Karen Chen (karenychen) merged 3 commits into
mainfrom
pr/crud-machine-scale-nonbatch
May 19, 2026
Merged

Karen Chen (karenychen) merged 3 commits into
mainfrom
pr/crud-machine-scale-nonbatch

Conversation

@karenychen

Copy link
Copy Markdown
Contributor

Summary

Adds the non-batch scale path to AKSMachineClient, building on the scaffolding from #1179. The batch path (use_batch_api=True) is intentionally still stubbed with NotImplementedError and lands in a follow-up PR so this diff stays focused and reviewable.

What's in this PR

Fully implemented in this PR:

  • scale_machine (non-batch branch): snapshots baseline ready node count, submits per-machine PUTs via _scale_machine_individually, waits once on the agentpool-level provisioningState, then waits for P50/P70/P90/P99/P100 node readiness. Raises RuntimeError on partial landing, agentpool timeout, or P100 readiness failure.
  • _wait_for_machine_node_readiness: polls nodes labeled agentpool=<pool> and computes percentile envelopes against baseline_count + expected_count so only NEW nodes count toward thresholds. Never raises; returns an empty-state envelope on exhaustion.
  • _get_machine_name_prefix: scale<N>k for multiples of 1000 ≥ 1000, scale<N> otherwise. Stable scheme for cross-repo Kusto dashboards.
  • _scale_machine_individually: ThreadPoolExecutor dispatch with max(1, machine_workers) clamp.
  • _create_single_machine: single Machine PUT, returns True on any 2xx, never raises. Per-machine ARM polling intentionally omitted (AKS RP reports Succeeded essentially as soon as the agentpool admits the request).

Stubbed in this PR (lands in a follow-up PR):

  • scale_machine batch branch (use_batch_api=True)
  • _scale_machine_batch, _create_batch_machines, _make_batch_request, _array_split, and the _BATCH_429_* retry constants

Other notes

  • scale_machine return type changed from -> bool to -> None for consistency with create_machine_agentpool (only exceptions signal failure; the return value was always dead).
  • Adds _MACHINE_API_VERSION = '2025-06-02-preview' constant.
  • Preserves every fix from feat(crud): add AKSMachineClient scaffolding for AKS Machine API #1179: self._session for connection pooling, _PER_REQUEST_TIMEOUT_CAP=60 timeout split, immediate 4xx raise in _wait_for_agentpool_provisioning, immediate-Failed on missing provisioningState, tempfile.TemporaryDirectory() in test setUp/tearDown.

Tests

  • 12 unit tests pass (up from 5 on main).
  • New tests cover:
    • Non-batch scale success (metadata enrichment, all required keys present)
    • Partial-landing raises RuntimeError
    • baseline_count snapshot propagation to _wait_for_machine_node_readiness
    • _get_machine_name_prefix value tests for small / multiple-of-1000 / non-multiple-of-1000 counts
    • _create_single_machine accepts 200/201/202 and returns False (no raise) on 500
    • Regression test asserting the batch path still raises NotImplementedError
  • pylint rating: 10.00/10 on both files.

Follow-up PR

A subsequent PR will:

  • Replace the NotImplementedError in the use_batch_api=True branch with batch dispatch.
  • Add _scale_machine_batch, _create_batch_machines, _make_batch_request, _array_split, and the _BATCH_429_* constants.
  • Add a batch success-path test.

Unstubs the non-batch ``scale_machine`` dispatch on AKSMachineClient,
following the scaffolding PR (#1179). The batch path
(``use_batch_api=True``) remains a ``NotImplementedError`` stub and
lands in a follow-up PR; this keeps the diff focused.

Newly implemented:
- ``scale_machine`` (non-batch branch): snapshots baseline ready node
  count, submits per-machine PUTs via ``_scale_machine_individually``,
  waits ONCE on the agentpool-level provisioningState, then waits for
  P50/P70/P90/P99/P100 node readiness. Raises RuntimeError on partial
  landing, agentpool timeout, or P100 failure.
- ``_wait_for_machine_node_readiness``: polls nodes labeled
  ``agentpool=<pool>`` and computes percentile envelopes against
  ``baseline_count + expected_count`` so only NEW nodes count toward
  thresholds. Never raises; returns the empty-state envelope on
  exhaustion.
- ``_get_machine_name_prefix``: ``scale<N>k`` for multiples of 1000 >=
  1000, ``scale<N>`` otherwise. Stable for cross-repo Kusto dashboards.
- ``_scale_machine_individually``: ThreadPoolExecutor dispatch with
  ``max(1, machine_workers)`` clamp.
- ``_create_single_machine``: single Machine PUT; returns True on any
  2xx, never raises. Per-machine ARM polling intentionally omitted
  (AKS RP reports Succeeded too early).

Still stubbed (lands in a follow-up PR):
- ``scale_machine`` batch branch (``use_batch_api=True``)
- ``_scale_machine_batch``, ``_create_batch_machines``,
  ``_make_batch_request``, ``_array_split``, and the ``_BATCH_429_*``
  constants

Other notes:
- ``scale_machine`` return type changed from ``-> bool`` to ``-> None``
  for consistency with ``create_machine_agentpool`` (only exceptions
  signal failure; the return value was always dead).
- Adds ``_MACHINE_API_VERSION = '2025-06-02-preview'`` constant.
- Preserves all PR-1179 fixes (``self._session``, timeout split,
  4xx-raises, immediate-Failed on missing provisioningState,
  ``tempfile.TemporaryDirectory`` in tests).

Tests:
- 12 unit tests pass (was 5). New tests cover non-batch success,
  partial-landing-raises, baseline_count propagation,
  ``_get_machine_name_prefix`` value tests for small/multiple-of-1000/
  non-multiple-of-1000 counts, ``_create_single_machine`` for
  200/201/202 vs 500, and a regression test for the batch path
  still raising ``NotImplementedError``.
- pylint 10.00/10.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds the non-batch (per-machine PUT) scale path to AKSMachineClient, including Kubernetes node-readiness percentile tracking and expanded unit test coverage, while keeping the batch path explicitly stubbed for a follow-up PR.

Changes:

  • Implemented scale_machine non-batch flow, including concurrent machine PUTs, a single agentpool provisioning poll, and node readiness percentile reporting.
  • Implemented _wait_for_machine_node_readiness, _get_machine_name_prefix, _scale_machine_individually, and _create_single_machine.
  • Expanded test_aks_machine_client.py to cover the non-batch success/failure paths and new helpers, and to assert the batch branch still raises NotImplementedError.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
modules/python/clients/aks_machine_client.py Implements non-batch machine scaling, readiness percentile polling, naming scheme, and single-machine PUT behavior.
modules/python/tests/test_aks_machine_client.py Adds unit tests for non-batch scaling, prefix generation, single-machine PUT handling, and batch-path stub assertion.

@karenychen

Copy link
Copy Markdown
Contributor Author

Code review

Found 2 issues:

  1. On partial-landing failure, scale_machine records misleading "P100 success" metadata before raising. _wait_for_machine_node_readiness is called with expected_count=len(successful) (the reduced count) at line 458 and its result is unconditionally written to OperationContext via op.add_metadata("percentile_node_readiness_times", ...) and op.add_metadata("node_readiness_time", ...) at lines 462–466, before the partial-landing check raises RuntimeError at lines 469–472. When PUTs partially fail, the readiness watcher can legitimately satisfy P100 against the reduced count, so the row that lands in Kusto carries P100 success for an operation that ultimately failed. As a side effect the function also blocks for up to readiness_wait_timeout (default 1200s) plus the _wait_for_agentpool_provisioning budget (default 600s) before reporting the failure. Move the len(successful) != scale_machine_count check above the readiness wait, or short-circuit when fewer than requested machines were PUT.

percentile_envelope = self._wait_for_machine_node_readiness(
agentpool_name=agentpool_name,
expected_count=len(successful),
timeout=readiness_wait_timeout,
baseline_count=baseline_count,
)
op.add_metadata("percentile_node_readiness_times", percentile_envelope)
p100 = percentile_envelope.get("P100", {})
op.add_metadata(
"node_readiness_time", p100.get("elapsed_time_seconds") or 0.0
)
op.add_metadata("cluster_info", self.get_cluster_data(cluster_name))
if len(successful) != scale_machine_count:
raise RuntimeError(
f"scale_machine landed {len(successful)}/{scale_machine_count} machines"
)
if not agentpool_ok:

  1. _wait_for_machine_node_readiness logs "All target nodes became ready in {max_elapsed:.2f} seconds" whenever elapsed is non-empty, even when some percentiles timed out. The per-percentile block at lines 331–335 correctly reports TIMEOUT for missing percentiles, but the summary line at 336–340 then computes max_elapsed = max(elapsed.values()) over the percentiles that did hit and unconditionally claims all targets are ready. Guard the summary on len(elapsed) == len(targets) or reword it.

logger.info(f"Node Readiness Percentile Summary for agentpool {agentpool_name}:")
for p in (50, 70, 90, 99, 100):
if p in elapsed:
logger.info(f" P{p} (target={targets[p]} nodes): {elapsed[p]:.2f} seconds")
else:
logger.info(f" P{p} (target={targets[p]} nodes): TIMEOUT")
max_elapsed = max(elapsed.values())
logger.info(
f"All target nodes became ready in {max_elapsed:.2f} seconds "
f"in agent pool {agentpool_name}"
)
logger.info(f"Percentile node readiness data: {json.dumps(result, indent=2)}")
return result

…e path

- Use math.ceil for percentile targets so P50/P70/P90 don't floor down to
  unreachable counts (e.g., target_total=3 now requires P50>=2, not 1);
  P100 still equals target_total and baseline_count+1 clamp is preserved.
- Stop logging "All target nodes became ready" when only some percentiles
  met within timeout; emit a partial-readiness warning listing the missed
  percentiles instead.
- In scale_machine, fail fast on partial machine landing BEFORE waiting on
  the agentpool or readiness against a reduced count, so the recorded
  percentile envelope, node_readiness_time, and cluster_info metadata are
  not written with a target smaller than the caller requested.
- Add focused tests for _wait_for_machine_node_readiness covering ceil
  rounding, baseline clamping, partial-timeout envelopes, expected_count=0,
  and k8s_client=None short-circuits; tighten partial-landing test to
  assert agentpool/readiness waits are skipped on fail-fast.
Pylint flagged the two local 'import itertools' inside test bodies as
C0415 (import-outside-toplevel) in CI. Move it to the file-level imports
to satisfy python-validation.
@karenychen
Karen Chen (karenychen) merged commit b1e6200 into main May 19, 2026
3 checks passed
@karenychen
Karen Chen (karenychen) deleted the pr/crud-machine-scale-nonbatch branch May 19, 2026 18:35
Karen Chen (karenychen) added a commit that referenced this pull request May 19, 2026
Adds the use_batch_api=True branch of scale_machine and the four batch
helpers it dispatches to: _array_split, _scale_machine_batch,
_create_batch_machines, _make_batch_request. Replaces the NotImplementedError
stub landed in #1181.

The batch path uses the AKS Machine API's BatchPutMachine HEADER pattern (NOT
the non-existent ARM /$batch envelope): a single PUT to the first machine
name in the chunk carrying a BatchPutMachine header whose JSON value contains
vmSkus (wrapped in {value: [...]}) and batchMachines for the *additional*
machines in the chunk. The batchMachines entries use the key 'machineName'
(NOT 'name') — using the wrong key causes the API to silently ignore the
entries and create only the URL-pointed machine.

429 responses are retried with bounded exponential backoff
(_BATCH_429_MAX_RETRIES=3, 1s/2s/4s). Non-2xx non-429 responses raise
immediately. Per-chunk wall time is captured in
op.add_metadata('batch_command_execution_times', {chunk_<idx>: seconds}).

Verification:
- pylint repo-root on touched files: 10.00/10.
- pytest modules/python/tests/test_aks_machine_client.py: 31 passed (13 new tests
  for the batch helpers + dispatch).
- pytest --cov=. --cov-fail-under=80: 724 passed, 83.45% coverage.
Pablo Trivino (PabloTriv) pushed a commit that referenced this pull request Jun 12, 2026
## Summary

Adds the non-batch scale path to `AKSMachineClient`, building on the
scaffolding from #1179. The batch path (`use_batch_api=True`) is
intentionally still stubbed with `NotImplementedError` and lands in a
follow-up PR so this diff stays focused and reviewable.

## What's in this PR

**Fully implemented in this PR:**
- `scale_machine` (non-batch branch): snapshots baseline ready node
count, submits per-machine PUTs via `_scale_machine_individually`, waits
once on the agentpool-level `provisioningState`, then waits for
P50/P70/P90/P99/P100 node readiness. Raises `RuntimeError` on partial
landing, agentpool timeout, or P100 readiness failure.
- `_wait_for_machine_node_readiness`: polls nodes labeled
`agentpool=<pool>` and computes percentile envelopes against
`baseline_count + expected_count` so only NEW nodes count toward
thresholds. Never raises; returns an empty-state envelope on exhaustion.
- `_get_machine_name_prefix`: `scale<N>k` for multiples of 1000 ≥ 1000,
`scale<N>` otherwise. Stable scheme for cross-repo Kusto dashboards.
- `_scale_machine_individually`: `ThreadPoolExecutor` dispatch with
`max(1, machine_workers)` clamp.
- `_create_single_machine`: single Machine PUT, returns `True` on any
2xx, never raises. Per-machine ARM polling intentionally omitted (AKS RP
reports `Succeeded` essentially as soon as the agentpool admits the
request).

**Stubbed in this PR (lands in a follow-up PR):**
- `scale_machine` batch branch (`use_batch_api=True`)
- `_scale_machine_batch`, `_create_batch_machines`,
`_make_batch_request`, `_array_split`, and the `_BATCH_429_*` retry
constants

## Other notes

- `scale_machine` return type changed from `-> bool` to `-> None` for
consistency with `create_machine_agentpool` (only exceptions signal
failure; the return value was always dead).
- Adds `_MACHINE_API_VERSION = '2025-06-02-preview'` constant.
- Preserves every fix from #1179: `self._session` for connection
pooling, `_PER_REQUEST_TIMEOUT_CAP=60` timeout split, immediate 4xx
raise in `_wait_for_agentpool_provisioning`, immediate-Failed on missing
`provisioningState`, `tempfile.TemporaryDirectory()` in test
setUp/tearDown.

## Tests

- 12 unit tests pass (up from 5 on main).
- New tests cover:
- Non-batch scale success (metadata enrichment, all required keys
present)
  - Partial-landing raises `RuntimeError`
- `baseline_count` snapshot propagation to
`_wait_for_machine_node_readiness`
- `_get_machine_name_prefix` value tests for small / multiple-of-1000 /
non-multiple-of-1000 counts
- `_create_single_machine` accepts 200/201/202 and returns `False` (no
raise) on 500
- Regression test asserting the batch path still raises
`NotImplementedError`
- `pylint` rating: 10.00/10 on both files.

## Follow-up PR

A subsequent PR will:
- Replace the `NotImplementedError` in the `use_batch_api=True` branch
with batch dispatch.
- Add `_scale_machine_batch`, `_create_batch_machines`,
`_make_batch_request`, `_array_split`, and the `_BATCH_429_*` constants.
- Add a batch success-path test.
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.

3 participants