From 20bda05e2bc781afd7bdfd22bb1bb913441480ce Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 13:56:10 -0700 Subject: [PATCH 1/6] feat(crud): add AKSMachineClient scaffolding for AKS Machine API Add the AKSMachineClient subclass with the agentpool half of the AKS Machine API workflow fully implemented: - create_machine_agentpool (PUT manualScale=0 agentpool, 200/201/202) - _wait_for_agentpool_provisioning (poll until Succeeded) - _get_machine_name_prefix (deterministic 12-char prefix so cross-repo Kusto dashboards key on a stable machine name) scale_machine and the per-machine readiness poll are stubbed to raise NotImplementedError; the scale/batch/readiness helpers land in a follow-up PR so this change stays small enough to review. This is the first of a planned multi-PR series; it supersedes PR #1178 which grew too large for a single review. Tests: 6 unit tests covering the implemented surface plus a guard that scale_machine raises NotImplementedError so the MachineCRUD wire-up can detect the unimplemented path cleanly. --- modules/python/clients/aks_machine_client.py | 256 ++++++++++++++++++ .../python/tests/test_aks_machine_client.py | 156 +++++++++++ 2 files changed, 412 insertions(+) create mode 100644 modules/python/clients/aks_machine_client.py create mode 100644 modules/python/tests/test_aks_machine_client.py diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py new file mode 100644 index 0000000000..92b544667a --- /dev/null +++ b/modules/python/clients/aks_machine_client.py @@ -0,0 +1,256 @@ +"""AKS Machine API client. + +Subclasses ``AKSClient`` to inherit auth, ContainerServiceClient, +KubernetesClient, ``get_cluster_name``, ``get_cluster_data``, and the existing +node-pool CRUD methods. Adds raw REST methods for the Machine API which is not +yet exposed in the Azure SDK. + +Public methods (``create_machine_agentpool``, ``scale_machine``) wrap their work +in ``OperationContext``: the context is opened inside the client method, +metadata is enriched with ``op.add_metadata`` along the way, success returns +True, failures are logged and re-raised so ``OperationContext`` records them. +``MachineCRUD`` therefore stays a thin try/except wrapper. + +This is the scaffolding revision: ``create_machine_agentpool`` and the +agentpool provisioning poll are fully implemented; ``scale_machine`` and its +private helpers raise ``NotImplementedError`` and will land in a follow-up PR. +""" +import logging +import threading +import time +from typing import Any, Dict, Optional + +import requests + +from clients.aks_client import AKSClient +from utils.logger_config import get_logger, setup_logging + +# Configure logging. +setup_logging() +logger = get_logger(__name__) +# Suppress noisy Azure SDK logs. +get_logger("azure.core.pipeline.policies.http_logging_policy").setLevel(logging.ERROR) +get_logger("azure.identity").setLevel(logging.ERROR) +get_logger("azure.core.pipeline").setLevel(logging.ERROR) +get_logger("msal").setLevel(logging.ERROR) + +_ARM_BASE = "https://management.azure.com" +_ARM_SCOPE = "https://management.azure.com/.default" +_AGENTPOOL_API_VERSION = "2024-06-02-preview" +_POLL_INTERVAL_SECONDS = 10 +_PROVISIONING_NONE_STATE_LIMIT = 5 + + +class AKSMachineClient(AKSClient): + """Extends ``AKSClient`` with Machine-API REST plumbing. + + Inherits ``credential``, ``subscription_id``, ``resource_group``, + ``k8s_client``, ``get_cluster_name``, ``get_cluster_data``, and the + existing ``create_node_pool`` / ``scale_node_pool`` / ``delete_node_pool`` + methods. Tests that require a baseline node pool can therefore call the + inherited methods directly without a separate client. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._token_cache_value: Optional[str] = None + self._token_cache_expiry: float = 0.0 # unix epoch seconds + self._token_lock = threading.Lock() + + # ---- auth + REST plumbing ---- + def _get_access_token(self) -> str: + """Cached token fetch. Re-uses token across worker threads with a 60s safety margin + before expiry. Avoids forking `az account get-access-token` per worker.""" + with self._token_lock: + if self._token_cache_value and time.time() < self._token_cache_expiry - 60: + return self._token_cache_value + tok = self.credential.get_token(_ARM_SCOPE) + self._token_cache_value = tok.token + self._token_cache_expiry = float(tok.expires_on) + return self._token_cache_value + + def make_request( + self, + method: str, + url: str, + data: Optional[Dict[str, Any]] = None, + timeout: int = 30, + ) -> requests.Response: + """Send an authenticated ARM REST request and return the raw Response. + + Callers are responsible for checking ``response.status_code`` (or + calling ``raise_for_status()``) — this method does NOT raise on HTTP + errors. Long-running Machine API operations return 200/202 with a + Location header that callers must follow. + """ + headers = { + "Authorization": f"Bearer {self._get_access_token()}", + "Content-Type": "application/json", + } + return requests.request(method, url, headers=headers, json=data, timeout=timeout) + + # ---- Machine API: agent pool provisioning ---- + def create_machine_agentpool( + self, + agentpool_name: str, + vm_size: str, + cluster_name: Optional[str] = None, + timeout: int = 300, + ) -> bool: + """Convert an existing agentpool to Machines mode via PUT. + + Opens an ``OperationContext`` here, enriches metadata, returns True on + success, re-raises on failure (so the context records ``success=False`` + with traceback before the exception propagates to ``MachineCRUD``). + + Args: + agentpool_name: Target agentpool name. + vm_size: VM SKU recorded in operation metadata. The PUT body itself + only sets ``mode: Machines``; the SKU is informational here so + downstream Kusto rows can attribute the agentpool to a SKU. + cluster_name: Parent AKS cluster name. Defaults to + ``self.get_cluster_name()`` (matches ``create_node_pool``). + timeout: Total budget (seconds) used as both the PUT HTTP timeout + AND the polling deadline for ``_wait_for_agentpool_provisioning``. + + Returns: + True iff the agentpool reaches provisioningState='Succeeded'. + + Raises: + RuntimeError: PUT non-2xx, ARM-reported Failed state, or timeout. + """ + cluster_name = cluster_name or self.get_cluster_name() + metadata = { + "cluster_name": cluster_name, + "agentpool_name": agentpool_name, + "vm_size": vm_size, + } + with self._get_operation_context()( + "create_machine_agentpool", "azure", metadata, result_dir=self.result_dir + ) as op: + try: + sub = self.subscription_id + url = ( + f"{_ARM_BASE}/subscriptions/{sub}/resourceGroups/{self.resource_group}" + f"/providers/Microsoft.ContainerService/managedClusters/{cluster_name}" + f"/agentPools/{agentpool_name}?api-version={_AGENTPOOL_API_VERSION}" + ) + body = {"properties": {"mode": "Machines"}} + resp = self.make_request("PUT", url, data=body, timeout=timeout) + # ARM async PUT acceptance returns 200/201/202; the agentpool + # provisioning poll below is the real completion gate. + if resp.status_code not in (200, 201, 202): + raise RuntimeError( + f"create_machine_agentpool PUT failed: " + f"{resp.status_code} {resp.text[:500]}" + ) + if not self._wait_for_agentpool_provisioning(url, timeout): + raise RuntimeError( + f"agentpool {agentpool_name} did not reach Succeeded within {timeout}s" + ) + op.add_metadata("agentpool_info", self.get_node_pool( + agentpool_name, cluster_name).as_dict()) + op.add_metadata("cluster_info", self.get_cluster_data(cluster_name)) + return True + except Exception as e: + logger.error(f"Failed to create machine agentpool {agentpool_name}: {e}") + raise + + def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: + """Poll the agentpool URL until provisioningState is terminal. + + Polls every ``_POLL_INTERVAL_SECONDS`` (10s) using a 30s per-request HTTP + timeout. Returns True on 'Succeeded'. Returns False on 'Failed' or when + ``timeout`` seconds have elapsed since invocation. Transient non-200 GETs + are logged and retried until the deadline. Also handles missing + provisioningState (treats absence for ``_PROVISIONING_NONE_STATE_LIMIT`` + consecutive polls as Failed). + """ + deadline = time.time() + timeout + none_count = 0 + while time.time() < deadline: + r = self.make_request("GET", url, timeout=30) + if r.status_code != 200: + logger.warning(f"agentpool GET {url} -> {r.status_code}") + time.sleep(_POLL_INTERVAL_SECONDS) + continue + try: + body = r.json() + except (ValueError, TypeError) as exc: + logger.warning(f"agentpool poll JSON parse failed: {exc}") + time.sleep(_POLL_INTERVAL_SECONDS) + continue + state = body.get("properties", {}).get("provisioningState") + if state == "Succeeded": + return True + if state == "Failed": + logger.error(f"agentpool provisioning failed: {body}") + return False + if state is None: + none_count += 1 + if none_count >= _PROVISIONING_NONE_STATE_LIMIT: + logger.warning( + f"agentpool provisioningState absent for {none_count} consecutive polls; " + f"treating as Failed." + ) + return False + else: + none_count = 0 + time.sleep(_POLL_INTERVAL_SECONDS) + logger.error(f"agentpool provisioning timed out after {timeout}s") + return False + + # ---- scale path: stubbed on this scaffolding PR ---- + # The methods below preserve the public/private signatures so that + # ``MachineCRUD`` can be wired up against them in a follow-up PR; each + # raises ``NotImplementedError`` until the implementation lands. + + def _wait_for_machine_node_readiness( + self, + agentpool_name: str, + expected_count: int, + timeout: int, + baseline_count: int = 0, + ) -> Dict[str, Dict[str, Any]]: + """Wait for ``expected_count`` NEW Ready nodes; return percentile dict. + + Stubbed in this PR; implementation lands in a follow-up. + """ + raise NotImplementedError( + "_wait_for_machine_node_readiness lands in a follow-up PR" + ) + + def scale_machine( + self, + agentpool_name: str, + vm_size: str, + scale_machine_count: int, + cluster_name: Optional[str] = None, + use_batch_api: bool = False, + machine_workers: int = 1, + timeout: int = 600, + readiness_wait_timeout: int = 1200, + tags: Optional[Dict[str, str]] = None, # pylint: disable=unused-argument + ) -> bool: + """Scale a Machine-mode agentpool by creating ``scale_machine_count`` machines. + + Stubbed in this PR; implementation lands in a follow-up. + """ + raise NotImplementedError( + "scale_machine lands in a follow-up PR" + ) + + @staticmethod + def _get_machine_name_prefix(scale_machine_count: int) -> str: + """Generate the machine-name prefix for a given scale count. + + The prefix is part of the machine ARM resource name; cross-repo Kusto + dashboards key on machine name, so this scheme is kept stable. + + - ``scale1000`` -> ``scale1k`` (any multiple of 1000 >= 1000 collapses) + - ``scale500`` -> ``scale500`` + - ``scale1`` -> ``scale1`` + """ + if scale_machine_count >= 1000 and scale_machine_count % 1000 == 0: + return f"scale{scale_machine_count // 1000}k" + return f"scale{scale_machine_count}" diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py new file mode 100644 index 0000000000..d90e600072 --- /dev/null +++ b/modules/python/tests/test_aks_machine_client.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Unit tests for AKSMachineClient (subclass of AKSClient). + +All public methods open an ``OperationContext`` (patched here) and write the +result file via ``Operation.save_to_file`` on context exit. Tests verify: +- success path returns True and enriches ``op.add_metadata`` with the right keys +- failure path raises (so the OperationContext records ``success=False``) + +Only ``create_machine_agentpool`` and the ``_get_machine_name_prefix`` static +helper have full implementations on this scaffolding PR; ``scale_machine`` and +its private helpers raise ``NotImplementedError`` and will be tested in a +follow-up PR. +""" +# pylint: disable=protected-access +# Several tests intentionally exercise the static helper ``_get_machine_name_prefix`` +# directly; the leading underscore is conventional rather than semantic privacy. +import tempfile +import unittest +from unittest import mock + +from clients.aks_machine_client import AKSMachineClient + + +class TestAKSMachineClient(unittest.TestCase): + """Tests for the AKSMachineClient class.""" + + def setUp(self): + """Patch all upstream Azure SDK and OperationContext seams.""" + self.cs_client_patcher = mock.patch( + "clients.aks_client.ContainerServiceClient" + ) + self.mi_cred_patcher = mock.patch( + "clients.aks_client.ManagedIdentityCredential" + ) + self.k8s_client_patcher = mock.patch("clients.aks_client.KubernetesClient") + self.operation_context_patcher = mock.patch( + "crud.operation.OperationContext" + ) + + self.cs_client_patcher.start() + self.mi_cred_patcher.start() + mock_k8s_class = self.k8s_client_patcher.start() + self.mock_operation_context = self.operation_context_patcher.start() + + self.mock_k8s = mock_k8s_class.return_value + self.mock_operation = mock.MagicMock() + self.mock_operation_context.return_value.__enter__.return_value = ( + self.mock_operation + ) + self.mock_operation_context.return_value.__exit__.return_value = None + + # Hermetic per-test temp dir avoids cross-platform /tmp assumptions + # and parallel-run collisions. + self._tmp_dir = tempfile.TemporaryDirectory() + self.test_result_dir = self._tmp_dir.name + + self.client = AKSMachineClient( + subscription_id="fake-sub", + resource_group="fake-rg", + cluster_name="fake-cluster", + use_managed_identity=True, + result_dir=self.test_result_dir, + ) + + # Stub inherited helpers that the Machine methods enrich metadata with. + self.client.get_cluster_name = mock.MagicMock(return_value="fake-cluster") + self.client.get_cluster_data = mock.MagicMock( + return_value={"name": "fake-cluster"} + ) + fake_pool = mock.MagicMock() + fake_pool.as_dict.return_value = {"name": "fake-pool"} + self.client.get_node_pool = mock.MagicMock(return_value=fake_pool) + + def tearDown(self): + mock.patch.stopall() + self._tmp_dir.cleanup() + + # ---- create_machine_agentpool ---- + + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=True) + @mock.patch.object(AKSMachineClient, "make_request") + def test_create_machine_agentpool_success(self, mock_make_request, _mock_wait): + """PUT 200 + Succeeded poll \u2192 return True; metadata enriched.""" + mock_resp = mock.MagicMock() + mock_resp.status_code = 200 + mock_make_request.return_value = mock_resp + + result = self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + self.assertTrue(result) + mock_make_request.assert_called_once() + call_args = mock_make_request.call_args + self.assertEqual(call_args.args[0], "PUT") + self.assertEqual(call_args.kwargs["data"], {"properties": {"mode": "Machines"}}) + metadata_keys = { + call.args[0] for call in self.mock_operation.add_metadata.call_args_list + } + self.assertIn("agentpool_info", metadata_keys) + self.assertIn("cluster_info", metadata_keys) + + @mock.patch.object(AKSMachineClient, "make_request") + def test_create_machine_agentpool_put_failure_raises(self, mock_make_request): + """PUT non-2xx \u2192 RuntimeError propagates out of with-block.""" + mock_resp = mock.MagicMock() + mock_resp.status_code = 500 + mock_resp.text = "boom" + mock_make_request.return_value = mock_resp + + with self.assertRaises(RuntimeError): + self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=False) + @mock.patch.object(AKSMachineClient, "make_request") + def test_create_machine_agentpool_provisioning_timeout_raises( + self, mock_make_request, _mock_wait + ): + """PUT OK but provisioning never reaches Succeeded \u2192 RuntimeError.""" + mock_resp = mock.MagicMock() + mock_resp.status_code = 200 + mock_make_request.return_value = mock_resp + + with self.assertRaises(RuntimeError): + self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + # ---- scale_machine: stubbed on this PR ---- + + def test_scale_machine_raises_not_implemented(self): + """scale_machine is a stub on this PR; subsequent PR will implement it.""" + with self.assertRaises(NotImplementedError): + self.client.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=2, + ) + + # ---- _get_machine_name_prefix static helper ---- + + def test_machine_name_prefix_collapses_thousands(self): + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1000), "scale1k") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(3000), "scale3k") + + def test_machine_name_prefix_keeps_non_thousand_values(self): + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1), "scale1") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(500), "scale500") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1500), "scale1500") + + +if __name__ == "__main__": + unittest.main() From 05810a3b5f3ef8546f472a6d5d53f718b58c66cc Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 14:22:29 -0700 Subject: [PATCH 2/6] address PR #1179 review comments + stub _get_machine_name_prefix - Stub _get_machine_name_prefix to raise NotImplementedError; implementation lands in PR-2 alongside the scale path that consumes it. - Reuse a per-instance requests.Session in make_request so TCP/TLS handshakes pool across polls and the planned parallel scale path. - Split the timeout budget in create_machine_agentpool: cap the PUT HTTP timeout at _PER_REQUEST_TIMEOUT_CAP (60s) and reserve the remainder for _wait_for_agentpool_provisioning's polling deadline. - Gate the transient-absent provisioningState 'treat as Failed' branch by wall-clock: only after _PROVISIONING_NONE_STATE_LIMIT consecutive polls AND at least half of timeout have elapsed. Avoids false negatives on slower control planes. - pylint setUp tempfile.TemporaryDirectory: disable consider-using-with inline since 'with' doesn't fit the unittest setUp/tearDown lifecycle. - Tests + module docstrings updated to reflect that _get_machine_name_prefix is stubbed; 5 unit tests, all passing. --- modules/python/clients/aks_machine_client.py | 70 +++++++++++++------ .../python/tests/test_aks_machine_client.py | 30 ++++---- 2 files changed, 61 insertions(+), 39 deletions(-) diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index 92b544667a..e26214bf36 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -12,8 +12,9 @@ ``MachineCRUD`` therefore stays a thin try/except wrapper. This is the scaffolding revision: ``create_machine_agentpool`` and the -agentpool provisioning poll are fully implemented; ``scale_machine`` and its -private helpers raise ``NotImplementedError`` and will land in a follow-up PR. +agentpool provisioning poll are fully implemented; ``scale_machine``, its +private helpers, and the ``_get_machine_name_prefix`` naming helper raise +``NotImplementedError`` and will land in a follow-up PR. """ import logging import threading @@ -39,6 +40,10 @@ _AGENTPOOL_API_VERSION = "2024-06-02-preview" _POLL_INTERVAL_SECONDS = 10 _PROVISIONING_NONE_STATE_LIMIT = 5 +# Per-request HTTP timeout is capped so that a single slow PUT/GET cannot +# consume the caller's whole ``timeout`` budget before the polling loop starts. +# The remaining budget is reserved for ``_wait_for_agentpool_provisioning``. +_PER_REQUEST_TIMEOUT_CAP = 60 class AKSMachineClient(AKSClient): @@ -56,6 +61,11 @@ def __init__(self, *args, **kwargs): self._token_cache_value: Optional[str] = None self._token_cache_expiry: float = 0.0 # unix epoch seconds self._token_lock = threading.Lock() + # Pool TCP/TLS across calls. ``requests.Session`` is thread-safe for + # sending requests (each request creates its own urllib3 connection + # from the shared pool), so this is safe for the planned parallel + # scale path landing in PR-2. + self._session = requests.Session() # ---- auth + REST plumbing ---- def _get_access_token(self) -> str: @@ -82,12 +92,17 @@ def make_request( calling ``raise_for_status()``) — this method does NOT raise on HTTP errors. Long-running Machine API operations return 200/202 with a Location header that callers must follow. + + Uses ``self._session`` for connection pooling so TCP/TLS handshakes + are reused across polls and the planned parallel scale path. """ headers = { "Authorization": f"Bearer {self._get_access_token()}", "Content-Type": "application/json", } - return requests.request(method, url, headers=headers, json=data, timeout=timeout) + return self._session.request( + method, url, headers=headers, json=data, timeout=timeout + ) # ---- Machine API: agent pool provisioning ---- def create_machine_agentpool( @@ -110,8 +125,11 @@ def create_machine_agentpool( downstream Kusto rows can attribute the agentpool to a SKU. cluster_name: Parent AKS cluster name. Defaults to ``self.get_cluster_name()`` (matches ``create_node_pool``). - timeout: Total budget (seconds) used as both the PUT HTTP timeout - AND the polling deadline for ``_wait_for_agentpool_provisioning``. + timeout: Total wall-clock budget (seconds) for this operation. + Used as the polling deadline for ``_wait_for_agentpool_provisioning``. + The per-request HTTP timeout is capped at + ``_PER_REQUEST_TIMEOUT_CAP`` so a single slow PUT cannot consume + the whole budget before polling starts. Returns: True iff the agentpool reaches provisioningState='Succeeded'. @@ -136,7 +154,10 @@ def create_machine_agentpool( f"/agentPools/{agentpool_name}?api-version={_AGENTPOOL_API_VERSION}" ) body = {"properties": {"mode": "Machines"}} - resp = self.make_request("PUT", url, data=body, timeout=timeout) + # Cap the PUT timeout so the bulk of ``timeout`` is preserved + # for the polling loop below. + put_timeout = min(timeout, _PER_REQUEST_TIMEOUT_CAP) + resp = self.make_request("PUT", url, data=body, timeout=put_timeout) # ARM async PUT acceptance returns 200/201/202; the agentpool # provisioning poll below is the real completion gate. if resp.status_code not in (200, 201, 202): @@ -162,11 +183,15 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: Polls every ``_POLL_INTERVAL_SECONDS`` (10s) using a 30s per-request HTTP timeout. Returns True on 'Succeeded'. Returns False on 'Failed' or when ``timeout`` seconds have elapsed since invocation. Transient non-200 GETs - are logged and retried until the deadline. Also handles missing - provisioningState (treats absence for ``_PROVISIONING_NONE_STATE_LIMIT`` - consecutive polls as Failed). + are logged and retried until the deadline. Missing ``provisioningState`` + (which ARM can transiently omit right after PUT acceptance) is tolerated + until BOTH ``_PROVISIONING_NONE_STATE_LIMIT`` consecutive polls AND at + least half of ``timeout`` have elapsed; only then is it treated as + Failed. This avoids false negatives on slower control planes. """ - deadline = time.time() + timeout + start = time.time() + deadline = start + timeout + none_grace_deadline = start + timeout / 2 none_count = 0 while time.time() < deadline: r = self.make_request("GET", url, timeout=30) @@ -188,10 +213,15 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: return False if state is None: none_count += 1 - if none_count >= _PROVISIONING_NONE_STATE_LIMIT: + # Only treat missing state as Failed once we're past the grace + # window AND have seen it for several consecutive polls. + if ( + none_count >= _PROVISIONING_NONE_STATE_LIMIT + and time.time() >= none_grace_deadline + ): logger.warning( - f"agentpool provisioningState absent for {none_count} consecutive polls; " - f"treating as Failed." + f"agentpool provisioningState absent for {none_count} consecutive polls " + f"after {time.time() - start:.0f}s; treating as Failed." ) return False else: @@ -244,13 +274,9 @@ def scale_machine( def _get_machine_name_prefix(scale_machine_count: int) -> str: """Generate the machine-name prefix for a given scale count. - The prefix is part of the machine ARM resource name; cross-repo Kusto - dashboards key on machine name, so this scheme is kept stable. - - - ``scale1000`` -> ``scale1k`` (any multiple of 1000 >= 1000 collapses) - - ``scale500`` -> ``scale500`` - - ``scale1`` -> ``scale1`` + Stubbed in this PR; implementation lands in a follow-up alongside the + scale path that consumes it. """ - if scale_machine_count >= 1000 and scale_machine_count % 1000 == 0: - return f"scale{scale_machine_count // 1000}k" - return f"scale{scale_machine_count}" + raise NotImplementedError( + "_get_machine_name_prefix lands in a follow-up PR" + ) diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index d90e600072..6d24e39233 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -6,14 +6,13 @@ - success path returns True and enriches ``op.add_metadata`` with the right keys - failure path raises (so the OperationContext records ``success=False``) -Only ``create_machine_agentpool`` and the ``_get_machine_name_prefix`` static -helper have full implementations on this scaffolding PR; ``scale_machine`` and -its private helpers raise ``NotImplementedError`` and will be tested in a -follow-up PR. +Only ``create_machine_agentpool`` has a full implementation on this scaffolding +PR; ``scale_machine`` and the ``_get_machine_name_prefix`` naming helper raise +``NotImplementedError`` and will be tested in a follow-up PR. """ # pylint: disable=protected-access -# Several tests intentionally exercise the static helper ``_get_machine_name_prefix`` -# directly; the leading underscore is conventional rather than semantic privacy. +# Tests intentionally exercise private helpers directly; the leading underscore +# is conventional rather than semantic privacy. import tempfile import unittest from unittest import mock @@ -50,8 +49,9 @@ def setUp(self): self.mock_operation_context.return_value.__exit__.return_value = None # Hermetic per-test temp dir avoids cross-platform /tmp assumptions - # and parallel-run collisions. - self._tmp_dir = tempfile.TemporaryDirectory() + # and parallel-run collisions. ``with`` doesn't fit the setUp/tearDown + # lifecycle, so we explicitly cleanup() in tearDown. + self._tmp_dir = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with self.test_result_dir = self._tmp_dir.name self.client = AKSMachineClient( @@ -140,16 +140,12 @@ def test_scale_machine_raises_not_implemented(self): scale_machine_count=2, ) - # ---- _get_machine_name_prefix static helper ---- + # ---- _get_machine_name_prefix: stubbed on this PR ---- - def test_machine_name_prefix_collapses_thousands(self): - self.assertEqual(AKSMachineClient._get_machine_name_prefix(1000), "scale1k") - self.assertEqual(AKSMachineClient._get_machine_name_prefix(3000), "scale3k") - - def test_machine_name_prefix_keeps_non_thousand_values(self): - self.assertEqual(AKSMachineClient._get_machine_name_prefix(1), "scale1") - self.assertEqual(AKSMachineClient._get_machine_name_prefix(500), "scale500") - self.assertEqual(AKSMachineClient._get_machine_name_prefix(1500), "scale1500") + def test_get_machine_name_prefix_raises_not_implemented(self): + """_get_machine_name_prefix is a stub on this PR; lands with the scale path.""" + with self.assertRaises(NotImplementedError): + AKSMachineClient._get_machine_name_prefix(1000) if __name__ == "__main__": From 0cd1bdea6ff145293eaa624f39f66ec2dd507bb5 Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 15:37:11 -0700 Subject: [PATCH 3/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- modules/python/tests/test_aks_machine_client.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index 6d24e39233..a3fe54a8eb 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -32,14 +32,16 @@ def setUp(self): "clients.aks_client.ManagedIdentityCredential" ) self.k8s_client_patcher = mock.patch("clients.aks_client.KubernetesClient") - self.operation_context_patcher = mock.patch( - "crud.operation.OperationContext" + self.operation_context_getter_patcher = mock.patch( + "clients.aks_machine_client.AKSMachineClient._get_operation_context" ) self.cs_client_patcher.start() self.mi_cred_patcher.start() mock_k8s_class = self.k8s_client_patcher.start() - self.mock_operation_context = self.operation_context_patcher.start() + mock_get_operation_context = self.operation_context_getter_patcher.start() + self.mock_operation_context = mock.MagicMock() + mock_get_operation_context.return_value = self.mock_operation_context self.mock_k8s = mock_k8s_class.return_value self.mock_operation = mock.MagicMock() From 1f382eeb0a9b649785d4b70f5cf30b778945f34f Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 18:29:50 -0700 Subject: [PATCH 4/6] address PR #1179 round-2 review comments - _wait_for_agentpool_provisioning: raise on 4xx GET (404/401/403 won't recover by polling); only 5xx and other transient failures retry until the deadline. (per @liyu-ma) - _wait_for_agentpool_provisioning: simplify the absent-provisioningState branch to a single half-budget wall-clock gate; drop none_count and _PROVISIONING_NONE_STATE_LIMIT. (per @liyu-ma) - create_machine_agentpool: return type -> None (only ever returns or raises; the dead True return was misleading). Test updated to drop the assertTrue on the discarded return value. (per @liyu-ma) --- modules/python/clients/aks_machine_client.py | 49 ++++++++----------- .../python/tests/test_aks_machine_client.py | 8 +-- 2 files changed, 24 insertions(+), 33 deletions(-) diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index e26214bf36..3f0865f4aa 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -39,7 +39,6 @@ _ARM_SCOPE = "https://management.azure.com/.default" _AGENTPOOL_API_VERSION = "2024-06-02-preview" _POLL_INTERVAL_SECONDS = 10 -_PROVISIONING_NONE_STATE_LIMIT = 5 # Per-request HTTP timeout is capped so that a single slow PUT/GET cannot # consume the caller's whole ``timeout`` budget before the polling loop starts. # The remaining budget is reserved for ``_wait_for_agentpool_provisioning``. @@ -111,10 +110,10 @@ def create_machine_agentpool( vm_size: str, cluster_name: Optional[str] = None, timeout: int = 300, - ) -> bool: + ) -> None: """Convert an existing agentpool to Machines mode via PUT. - Opens an ``OperationContext`` here, enriches metadata, returns True on + Opens an ``OperationContext`` here, enriches metadata, returns on success, re-raises on failure (so the context records ``success=False`` with traceback before the exception propagates to ``MachineCRUD``). @@ -131,9 +130,6 @@ def create_machine_agentpool( ``_PER_REQUEST_TIMEOUT_CAP`` so a single slow PUT cannot consume the whole budget before polling starts. - Returns: - True iff the agentpool reaches provisioningState='Succeeded'. - Raises: RuntimeError: PUT non-2xx, ARM-reported Failed state, or timeout. """ @@ -172,7 +168,6 @@ def create_machine_agentpool( op.add_metadata("agentpool_info", self.get_node_pool( agentpool_name, cluster_name).as_dict()) op.add_metadata("cluster_info", self.get_cluster_data(cluster_name)) - return True except Exception as e: logger.error(f"Failed to create machine agentpool {agentpool_name}: {e}") raise @@ -182,20 +177,24 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: Polls every ``_POLL_INTERVAL_SECONDS`` (10s) using a 30s per-request HTTP timeout. Returns True on 'Succeeded'. Returns False on 'Failed' or when - ``timeout`` seconds have elapsed since invocation. Transient non-200 GETs - are logged and retried until the deadline. Missing ``provisioningState`` - (which ARM can transiently omit right after PUT acceptance) is tolerated - until BOTH ``_PROVISIONING_NONE_STATE_LIMIT`` consecutive polls AND at - least half of ``timeout`` have elapsed; only then is it treated as - Failed. This avoids false negatives on slower control planes. + ``timeout`` seconds have elapsed since invocation. 4xx GETs are raised + immediately (e.g. 404 'agentpool not found', 401/403) since retrying + won't change the outcome; 5xx and other transient failures are logged + and retried until the deadline. Missing ``provisioningState`` (which + ARM can transiently omit right after PUT acceptance) is tolerated for + the first half of ``timeout`` and then treated as Failed; this avoids + false negatives on slower control planes without infinite patience. """ start = time.time() deadline = start + timeout none_grace_deadline = start + timeout / 2 - none_count = 0 while time.time() < deadline: r = self.make_request("GET", url, timeout=30) if r.status_code != 200: + if 400 <= r.status_code < 500: + raise RuntimeError( + f"agentpool GET {url} -> {r.status_code} {r.text[:500]}" + ) logger.warning(f"agentpool GET {url} -> {r.status_code}") time.sleep(_POLL_INTERVAL_SECONDS) continue @@ -211,21 +210,13 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: if state == "Failed": logger.error(f"agentpool provisioning failed: {body}") return False - if state is None: - none_count += 1 - # Only treat missing state as Failed once we're past the grace - # window AND have seen it for several consecutive polls. - if ( - none_count >= _PROVISIONING_NONE_STATE_LIMIT - and time.time() >= none_grace_deadline - ): - logger.warning( - f"agentpool provisioningState absent for {none_count} consecutive polls " - f"after {time.time() - start:.0f}s; treating as Failed." - ) - return False - else: - none_count = 0 + if state is None and time.time() >= none_grace_deadline: + logger.warning( + f"agentpool provisioningState absent after " + f"{time.time() - start:.0f}s (past half-budget grace); " + f"treating as Failed." + ) + return False time.sleep(_POLL_INTERVAL_SECONDS) logger.error(f"agentpool provisioning timed out after {timeout}s") return False diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index a3fe54a8eb..a29a37a79f 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -3,7 +3,8 @@ All public methods open an ``OperationContext`` (patched here) and write the result file via ``Operation.save_to_file`` on context exit. Tests verify: -- success path returns True and enriches ``op.add_metadata`` with the right keys +- success path completes without raising and enriches ``op.add_metadata`` with + the right keys - failure path raises (so the OperationContext records ``success=False``) Only ``create_machine_agentpool`` has a full implementation on this scaffolding @@ -83,16 +84,15 @@ def tearDown(self): return_value=True) @mock.patch.object(AKSMachineClient, "make_request") def test_create_machine_agentpool_success(self, mock_make_request, _mock_wait): - """PUT 200 + Succeeded poll \u2192 return True; metadata enriched.""" + """PUT 200 + Succeeded poll → returns; metadata enriched.""" mock_resp = mock.MagicMock() mock_resp.status_code = 200 mock_make_request.return_value = mock_resp - result = self.client.create_machine_agentpool( + self.client.create_machine_agentpool( agentpool_name="apool", vm_size="Standard_D2_v3" ) - self.assertTrue(result) mock_make_request.assert_called_once() call_args = mock_make_request.call_args self.assertEqual(call_args.args[0], "PUT") From 75ffefb68a30cfccceaa3a221eb42fc10ff6934c Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 18:57:49 -0700 Subject: [PATCH 5/6] fix(crud): treat missing provisioningState on 200 GET as immediate Failed By AKS contract, a 200 GET on an agentpool always includes properties.provisioningState. The previous half-budget grace window existed to absorb a presumed transient None right after PUT acceptance, but that case does not actually occur for a successful (200) GET. If we do see a 200 response without provisioningState, that is a Failed signal and we should stop polling immediately rather than waiting out half of the timeout budget. --- modules/python/clients/aks_machine_client.py | 21 +++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index 3f0865f4aa..2325bd9e7d 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -180,14 +180,12 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: ``timeout`` seconds have elapsed since invocation. 4xx GETs are raised immediately (e.g. 404 'agentpool not found', 401/403) since retrying won't change the outcome; 5xx and other transient failures are logged - and retried until the deadline. Missing ``provisioningState`` (which - ARM can transiently omit right after PUT acceptance) is tolerated for - the first half of ``timeout`` and then treated as Failed; this avoids - false negatives on slower control planes without infinite patience. + and retried until the deadline. By AKS contract a 200 GET on the + agentpool always includes ``properties.provisioningState``; if it is + absent on a 200 response, that is a Failed signal and we stop + immediately rather than waiting out the timeout. """ - start = time.time() - deadline = start + timeout - none_grace_deadline = start + timeout / 2 + deadline = time.time() + timeout while time.time() < deadline: r = self.make_request("GET", url, timeout=30) if r.status_code != 200: @@ -210,11 +208,10 @@ def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: if state == "Failed": logger.error(f"agentpool provisioning failed: {body}") return False - if state is None and time.time() >= none_grace_deadline: - logger.warning( - f"agentpool provisioningState absent after " - f"{time.time() - start:.0f}s (past half-budget grace); " - f"treating as Failed." + if state is None: + logger.error( + f"agentpool 200 GET returned without provisioningState; " + f"treating as Failed. body={body}" ) return False time.sleep(_POLL_INTERVAL_SECONDS) From 713d1ee9edae0e2f01c5030f67de01c6a815e7ee Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 19:03:19 -0700 Subject: [PATCH 6/6] style(crud): replace unicode arrow with ASCII in test docstring --- modules/python/tests/test_aks_machine_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index a29a37a79f..eca4505937 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -84,7 +84,7 @@ def tearDown(self): return_value=True) @mock.patch.object(AKSMachineClient, "make_request") def test_create_machine_agentpool_success(self, mock_make_request, _mock_wait): - """PUT 200 + Succeeded poll → returns; metadata enriched.""" + """PUT 200 + Succeeded poll -> returns; metadata enriched.""" mock_resp = mock.MagicMock() mock_resp.status_code = 200 mock_make_request.return_value = mock_resp