diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index b760fe3ddd..8f3faf67d3 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -18,6 +18,7 @@ from requests.adapters import HTTPAdapter from clients.aks_client import AKSClient +from utils.common import compute_throttle_delay from utils.logger_config import get_logger, setup_logging # Configure logging. @@ -505,6 +506,8 @@ def scale_machine( machine_workers=machine_workers, timeout=timeout, batch_command_execution_times={}, + chunk_throttle=[], + throttle_lock=threading.Lock(), ) with self._get_operation_context()( "scale_machine", "azure", metadata, result_dir=self.result_dir @@ -536,7 +539,13 @@ def scale_machine( successful = self._scale_machine_batch(request, names) else: successful = self._scale_machine_individually(request, names) - op.add_metadata("command_execution_time", time.time() - command_t0) + command_end = time.time() + throttle_wait = compute_throttle_delay(request.chunk_throttle) + op.add_metadata( + "command_execution_time", + max(0.0, command_end - command_t0 - throttle_wait), + ) + op.add_metadata("throttle_wait_seconds", throttle_wait) if use_batch_api: op.add_metadata( "batch_command_execution_times", @@ -889,10 +898,7 @@ def _create_batch_machines( "vmSkus": {"value": [vm_sku]}, "batchMachines": batch_machines, }) - logger.info( - f"chunk {chunk_idx}: submitting BatchPutMachine PUT for {len(chunk)} machines " - f"(target={first_machine_name})" - ) + logger.info(f"chunk {chunk_idx}: submitting BatchPutMachine PUT for {len(chunk)} machines (target={first_machine_name})") # Cap the timeout value passed to this batch PUT attempt. This limits # the per-attempt request timeout given to ``_make_batch_request``, # but it does not bound total wall time for the chunk because retry @@ -904,6 +910,7 @@ def _create_batch_machines( batch_header_value=batch_header_value, chunk_idx=chunk_idx, first_machine_name=first_machine_name, + request=request, ) end_time = datetime.now(timezone.utc) execution_time_seconds = (end_time - start_time).total_seconds() @@ -913,11 +920,7 @@ def _create_batch_machines( "execution_time_seconds": execution_time_seconds, "total_machines_in_batch": len(chunk), } - logger.info( - f"chunk {chunk_idx}: BatchPutMachine PUT completed for {len(chunk)} " - f"machines in {execution_time_seconds:.3f} seconds " - f"(target={first_machine_name})" - ) + logger.info(f"chunk {chunk_idx}: BatchPutMachine PUT completed for {len(chunk)} machines in {execution_time_seconds:.3f} seconds (target={first_machine_name})") return list(chunk) def _make_batch_request( @@ -929,7 +932,8 @@ def _make_batch_request( batch_header_value: str, chunk_idx: Optional[int] = None, first_machine_name: Optional[str] = None, - ) -> None: + request: Optional[SimpleNamespace] = None, + ) -> float: """Send a ``BatchPutMachine``-headered request with bounded 429 backoff. Sends the request directly (NOT via ``make_request``) so we can attach @@ -943,42 +947,38 @@ def _make_batch_request( # Compact prefix so every error/log line is self-identifying in Kusto # (chunk_idx + first machine name pinpoint the failing slice without # cross-referencing the per-worker log). - ctx = ( - f"chunk={chunk_idx} target={first_machine_name} {method} {url}" - ) + ctx = f"chunk={chunk_idx} target={first_machine_name} {method} {url}" backoff = _BATCH_429_INITIAL_BACKOFF_SECONDS + total_backoff = 0.0 last_resp: Optional[requests.Response] = None - for attempt in range(_BATCH_429_MAX_RETRIES): - headers = { - "Authorization": f"Bearer {self._get_access_token()}", - "Content-Type": "application/json", - "BatchPutMachine": batch_header_value, - } - # Use the client's shared Session so this batch path reuses the - # same pooled TCP/TLS connections (and adapters/proxies) as the - # individual ``make_request`` path; avoids per-PUT handshakes - # during large scales. - resp = self._session.request( - method, url, headers=headers, json=data, timeout=timeout, - ) - last_resp = resp - if resp.status_code in (200, 201, 202, 204): - return - if resp.status_code != 429: - raise RuntimeError( - f"batch request failed [{ctx}]: " - f"{resp.status_code} {resp.text[:500]}" + try: + for attempt in range(_BATCH_429_MAX_RETRIES): + headers = { + "Authorization": f"Bearer {self._get_access_token()}", + "Content-Type": "application/json", + "BatchPutMachine": batch_header_value, + } + # Use the client's shared Session so this batch path reuses the + # same pooled TCP/TLS connections (and adapters/proxies) as the + # individual ``make_request`` path; avoids per-PUT handshakes + # during large scales. + resp = self._session.request( + method, url, headers=headers, json=data, timeout=timeout, ) - if attempt == _BATCH_429_MAX_RETRIES - 1: - break - logger.warning( - f"batch request 429 [{ctx}]; retrying in {backoff:.1f}s " - f"(attempt {attempt + 1}/{_BATCH_429_MAX_RETRIES})" - ) - time.sleep(backoff) - backoff *= 2 - text = last_resp.text[:500] if last_resp is not None else "" - raise RuntimeError( - f"batch request exceeded {_BATCH_429_MAX_RETRIES} attempts " - f"after HTTP 429 responses [{ctx}]; last text={text}" - ) + last_resp = resp + if resp.status_code in (200, 201, 202, 204): + return total_backoff + if resp.status_code != 429: + raise RuntimeError(f"batch request failed [{ctx}]: {resp.status_code} {resp.text[:500]}") + if attempt == _BATCH_429_MAX_RETRIES - 1: + break + logger.warning(f"batch request 429 [{ctx}]; retrying in {backoff:.1f}s (attempt {attempt + 1}/{_BATCH_429_MAX_RETRIES})") + time.sleep(backoff) + total_backoff += backoff + backoff *= 2 + text = last_resp.text[:500] if last_resp is not None else "" + raise RuntimeError(f"batch request exceeded {_BATCH_429_MAX_RETRIES} attempts after HTTP 429 [{ctx}]; last text={text}") + finally: + if request is not None: + with request.throttle_lock: + request.chunk_throttle.append((time.time(), total_backoff)) diff --git a/modules/python/crud/operation.py b/modules/python/crud/operation.py index b2b465f1e3..a6ef4fa7ae 100644 --- a/modules/python/crud/operation.py +++ b/modules/python/crud/operation.py @@ -9,7 +9,7 @@ import json import os import traceback -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Dict, Any, Optional from utils.logger_config import get_logger, setup_logging @@ -39,6 +39,7 @@ def __init__(self, name: str, cloud: str, metadata: Optional[Dict[str, Any]] = N self.start_timestamp = None self.end_timestamp = None self.duration = None + self.excluded_seconds = 0.0 self.unit = "seconds" self.success = True self.error_message = None @@ -51,6 +52,12 @@ def start(self) -> None: """ self.start_timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + def exclude_time(self, seconds: float) -> None: + """Accumulate wall-clock ``seconds`` to drop from the duration (e.g. ARM + admission/queue-wait). Positive values accumulate; others are ignored.""" + if seconds is not None and seconds > 0: + self.excluded_seconds += seconds + def end(self, success: bool = True, error: Optional[Exception] = None) -> None: """ End the operation by recording the end time and calculating the duration. @@ -70,6 +77,13 @@ def end(self, success: bool = True, error: Optional[Exception] = None) -> None: end_dt = datetime.fromisoformat( self.end_timestamp.replace("Z", "+00:00") ) + if self.excluded_seconds > 0: + excluded = min( + self.excluded_seconds, (end_dt - start_dt).total_seconds() + ) + start_dt = start_dt + timedelta(seconds=excluded) + self.start_timestamp = start_dt.strftime("%Y-%m-%dT%H:%M:%SZ") + self.metadata["in_progress_wait_seconds"] = excluded self.duration = (end_dt - start_dt).total_seconds() except Exception: # If there's any issue parsing timestamps, don't set duration diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index e0ff39a3db..1f111441fa 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -176,11 +176,16 @@ def test_create_node_pool_success(self, _mock_time, mock_instr_time): vm_size = "Standard_DS2_v2" node_count = 2 - # Define timestamps for clarity + # Define timestamps for clarity. accepted_at == start_time: ARM accepted the + # PUT on the first attempt (no in-progress wait), so timings measured from the + # accept match those measured from start. NOTE: the shared side_effect assumes + # ARM-thread-first scheduling of the concurrent ARM/K8s executor (arm_done + # consumed before ready); instant mocks make this hold in practice. start_time = 100 + accepted_at = 100 arm_done_time = 150 nodes_ready_time = 130 - mock_instr_time.time.side_effect = [start_time, arm_done_time, nodes_ready_time] + mock_instr_time.time.side_effect = [start_time, accepted_at, arm_done_time, nodes_ready_time] mock_instr_time.sleep = mock.MagicMock() mock_operation = mock.MagicMock() @@ -242,10 +247,20 @@ def test_create_node_pool_retry_occurred_metadata(self, _mock_time, mock_instr_t vm_size = "Standard_DS2_v2" node_count = 2 + # The first PUT is rejected (OperationNotAllowed) and the retry is accepted + # ~30s later. Each attempt stamps its own start; timings are measured from + # the accepted attempt's start (130), so 30s of in-progress wait is excluded. + # Order: instrument start, failed-attempt start, accepted-attempt start, + # ARM done, nodes ready. start_time = 100 + failed_attempt_start = 105 + accepted_attempt_start = 130 arm_done_time = 180 nodes_ready_time = 160 - mock_instr_time.time.side_effect = [start_time, arm_done_time, nodes_ready_time] + mock_instr_time.time.side_effect = [ + start_time, failed_attempt_start, accepted_attempt_start, + arm_done_time, nodes_ready_time, + ] mock_instr_time.sleep = mock.MagicMock() # First call raises OperationNotAllowed, second succeeds @@ -396,11 +411,13 @@ def test_scale_node_pool_up(self, mock_time, mock_instr_time): node_pool_name = "test-pool" node_count = 3 - # Define timestamps for clarity + # Define timestamps for clarity. accepted_at == start_time: first-attempt + # accept (no in-progress wait), so accept-based timings match start-based. start_time = 100 + accepted_at = 100 arm_done_time = 150 nodes_ready_time = 130 - mock_instr_time.time.side_effect = [start_time, arm_done_time, nodes_ready_time] + mock_instr_time.time.side_effect = [start_time, accepted_at, arm_done_time, nodes_ready_time] mock_instr_time.sleep = mock.MagicMock() mock_time.sleep = mock.MagicMock() diff --git a/modules/python/tests/crud/test_operation.py b/modules/python/tests/crud/test_operation.py index 873e1dfe30..1b22734d70 100644 --- a/modules/python/tests/crud/test_operation.py +++ b/modules/python/tests/crud/test_operation.py @@ -108,6 +108,90 @@ def test_operation_end_with_error(self, mock_datetime): self.assertEqual(self.test_operation.error_message, "Test error") self.assertIsNotNone(self.test_operation.error_traceback) + @mock.patch("crud.operation.datetime") + def test_operation_end_excludes_in_progress_wait(self, mock_datetime): + """Duration excludes time spent waiting for a pre-existing in-progress op.""" + # 10 minutes of wall-clock, 3 of which were queue-wait. + mock_now = mock.MagicMock() + mock_now.strftime.side_effect = [ + "2023-01-01T12:00:00Z", # start + "2023-01-01T12:10:00Z", # end + ] + mock_datetime.now.return_value = mock_now + mock_datetime.fromisoformat.side_effect = [ + datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc), + datetime(2023, 1, 1, 12, 10, 0, tzinfo=timezone.utc), + ] + + self.test_operation.start() + self.test_operation.exclude_time(180) + self.test_operation.end(success=True) + + # 600s wall-clock minus 180s queue-wait == 420s effective. + self.assertEqual(self.test_operation.duration, 420.0) + self.assertEqual( + self.test_operation.metadata["in_progress_wait_seconds"], 180 + ) + # Effective start shifted forward so start/end/duration stay consistent. + self.assertEqual( + self.test_operation.start_timestamp, "2023-01-01T12:03:00Z" + ) + self.assertEqual(self.test_operation.end_timestamp, "2023-01-01T12:10:00Z") + + def test_exclude_time_accumulates_and_ignores_nonpositive(self): + """exclude_time sums positive waits and ignores zero/negative values.""" + self.test_operation.exclude_time(30) + self.test_operation.exclude_time(60) + self.test_operation.exclude_time(0) + self.test_operation.exclude_time(-5) + self.assertEqual(self.test_operation.excluded_seconds, 90) + + @mock.patch("crud.operation.datetime") + def test_operation_end_clamps_excluded_to_wall_clock(self, mock_datetime): + """Excluded wait exceeding wall-clock clamps duration to 0 and metadata matches.""" + mock_now = mock.MagicMock() + mock_now.strftime.side_effect = [ + "2023-01-01T12:00:00Z", # start + "2023-01-01T12:01:00Z", # end (60s wall-clock) + ] + mock_datetime.now.return_value = mock_now + mock_datetime.fromisoformat.side_effect = [ + datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc), + datetime(2023, 1, 1, 12, 1, 0, tzinfo=timezone.utc), + ] + + self.test_operation.start() + self.test_operation.exclude_time(600) # more than the 60s wall-clock + self.test_operation.end(success=True) + + # Duration floors at 0 and the recorded wait is the clamped (real) value. + self.assertEqual(self.test_operation.duration, 0.0) + self.assertEqual( + self.test_operation.metadata["in_progress_wait_seconds"], 60.0 + ) + self.assertEqual(self.test_operation.start_timestamp, "2023-01-01T12:01:00Z") + + @mock.patch("crud.operation.datetime") + def test_operation_end_no_wait_leaves_duration_unchanged(self, mock_datetime): + """With no excluded time, duration and start_timestamp are untouched.""" + mock_now = mock.MagicMock() + mock_now.strftime.side_effect = [ + "2023-01-01T12:00:00Z", + "2023-01-01T12:01:30Z", + ] + mock_datetime.now.return_value = mock_now + mock_datetime.fromisoformat.side_effect = [ + datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc), + datetime(2023, 1, 1, 12, 1, 30, tzinfo=timezone.utc), + ] + + self.test_operation.start() + self.test_operation.end(success=True) + + self.assertEqual(self.test_operation.duration, 90.0) + self.assertEqual(self.test_operation.start_timestamp, "2023-01-01T12:00:00Z") + self.assertNotIn("in_progress_wait_seconds", self.test_operation.metadata) + @mock.patch("crud.operation.datetime") def test_operation_end_duration_calculation_error(self, mock_datetime): """Test operation end when duration calculation fails""" diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index fb3f34e5e2..ca9494c5ba 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -855,10 +855,10 @@ def test_create_batch_machines_header_shape(self): vm_size="Standard_D2_v3", timeout=60, batch_command_execution_times={}, + chunk_throttle=[], + throttle_lock=mock.MagicMock(), ) - with mock.patch.object( - AKSMachineClient, "_make_batch_request" - ) as mock_make_batch: + with mock.patch.object(AKSMachineClient, "_make_batch_request", return_value=0.0) as mock_make_batch: result = self.client._create_batch_machines( request, ["m-1", "m-2", "m-3"], chunk_idx=0 ) diff --git a/modules/python/tests/test_aks_machine_throttle.py b/modules/python/tests/test_aks_machine_throttle.py new file mode 100644 index 0000000000..edc75c0554 --- /dev/null +++ b/modules/python/tests/test_aks_machine_throttle.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Unit tests for Machine-API 429 throttle-wait exclusion. + +Covers the ``compute_throttle_delay`` critical-path attribution, per-chunk +backoff returned by ``_make_batch_request``, and the ``scale_machine`` exclusion +of throttle-wait from the operation duration / command time. +""" +# pylint: disable=protected-access +import tempfile +import unittest +from types import SimpleNamespace +from unittest import mock + +from clients.aks_machine_client import AKSMachineClient +from utils.common import compute_throttle_delay + + +class TestComputeThrottleDelay(unittest.TestCase): + """Tests for the compute_throttle_delay critical-path helper.""" + + def test_empty_is_zero(self): + """No chunks -> 0 delay.""" + self.assertEqual(compute_throttle_delay([]), 0.0) + + def test_single_chunk_backoff_counts(self): + """A lone chunk's backoff fully delayed its own completion.""" + # finish=1005, backoff=5 -> throttle-free finish 1000 -> delay 5. + self.assertEqual(compute_throttle_delay([(1005.0, 5.0)]), 5.0) + + def test_off_critical_path_backoff_excluded(self): + """Backoff on a worker that is NOT last-to-finish does not delay command.""" + # Chunk A finishes last at 1005 with no backoff (critical path); chunk B + # slept 5s but finished earlier at 1003. Removing B's throttle would not + # move the makespan, so the throttle delay is 0 (Karen's concurrency case). + self.assertEqual( + compute_throttle_delay([(1005.0, 0.0), (1003.0, 5.0)]), 0.0 + ) + + def test_critical_path_capped_by_runner_up(self): + """Delay is capped by the next-latest throttle-free finish.""" + # Critical chunk finishes 1010 with 8s backoff (throttle-free 1002); + # runner-up finishes 1005 with no backoff. Counterfactual makespan = + # max(1002, 1005) = 1005, so delay = 1010 - 1005 = 5 (not the full 8). + self.assertEqual( + compute_throttle_delay([(1010.0, 8.0), (1005.0, 0.0)]), 5.0 + ) + + def test_tie_finish_uses_least_throttled(self): + """When two chunks finish together, the least-throttled bounds the delay.""" + # Both finish at 1000; throttle-free finishes are 990 and 997. Without + # throttle the command still finishes at max(990, 997) = 997 -> delay 3. + self.assertEqual( + compute_throttle_delay([(1000.0, 10.0), (1000.0, 3.0)]), 3.0 + ) + + def test_exact_tie(self): + """Identical (finish, backoff) chunks -> delay equals the shared backoff.""" + self.assertEqual( + compute_throttle_delay([(1000.0, 4.0), (1000.0, 4.0)]), 4.0 + ) + + +class TestMachineThrottleExclusion(unittest.TestCase): + """Tests that throttle backoff is recorded and excluded from timings.""" + + def setUp(self): + """Build the client WITHOUT running __init__ and stub only the attrs these + tests touch (no mock.patch of clients.aks_client at all). Other tests in the + suite mutate that module's SDK symbols / AKSClient.__init__, so constructing + or patching through it is order-dependent; this avoids the dependency.""" + self._tmp_dir = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with + self.mock_operation = mock.MagicMock() + op_context = mock.MagicMock() + op_context.return_value.__enter__.return_value = self.mock_operation + op_context.return_value.__exit__.return_value = None + self.mock_k8s = mock.MagicMock() + + self.client = AKSMachineClient.__new__(AKSMachineClient) + self.client._session = mock.MagicMock() + self.client.subscription_id = "fake-sub" + self.client.resource_group = "fake-rg" + self.client.result_dir = self._tmp_dir.name + self.client.k8s_client = self.mock_k8s + self.client._get_access_token = mock.MagicMock(return_value="token") + self.client._get_operation_context = mock.MagicMock(return_value=op_context) + self.client.get_cluster_name = mock.MagicMock(return_value="fake-cluster") + self.client.get_cluster_data = mock.MagicMock(return_value={"name": "fake-cluster"}) + + def tearDown(self): + self._tmp_dir.cleanup() + + def test_make_batch_request_returns_backoff(self): + """A 429-then-2xx returns the accumulated backoff seconds.""" + responses = [ + mock.MagicMock(status_code=429), + mock.MagicMock(status_code=201), + ] + with mock.patch.object( + self.client._session, "request", side_effect=responses, + ), mock.patch("clients.aks_machine_client.time.sleep"): + backoff = self.client._make_batch_request( + "PUT", "https://fake/url", {}, timeout=30, batch_header_value="{}", + ) + # One retry at the initial 1.0s backoff. + self.assertEqual(backoff, 1.0) + + def test_make_batch_request_no_retry_returns_zero(self): + """A first-attempt 2xx returns 0 backoff.""" + with mock.patch.object( + self.client._session, "request", + return_value=mock.MagicMock(status_code=201), + ), mock.patch("clients.aks_machine_client.time.sleep"): + backoff = self.client._make_batch_request( + "PUT", "https://fake/url", {}, timeout=30, batch_header_value="{}", + ) + self.assertEqual(backoff, 0.0) + + def test_make_batch_request_records_backoff_on_failure(self): + """A chunk that exhausts its 429 retries still records its backoff (finally).""" + request = SimpleNamespace(chunk_throttle=[], throttle_lock=mock.MagicMock()) + with mock.patch.object( + self.client._session, "request", + return_value=mock.MagicMock(status_code=429), + ), mock.patch("clients.aks_machine_client.time.sleep"): + with self.assertRaises(RuntimeError): + self.client._make_batch_request( + "PUT", "https://fake/url", {}, timeout=30, + batch_header_value="{}", request=request, + ) + # Recorded despite failure; backoff = 1+2+4+8 = 15s across the retry budget. + self.assertEqual(len(request.chunk_throttle), 1) + self.assertEqual(request.chunk_throttle[0][1], 15.0) + + def test_scale_machine_scopes_throttle_to_command_time(self): + """Throttle adjusts command_execution_time only, NOT the operation duration.""" + def fake_batch(request, names): + # Critical chunk finishes last (1005) with 5s backoff; an earlier chunk + # (1003) also slept 5s but is off the critical path. Only the critical + # chunk's backoff delayed the PUT makespan -> 5s throttle, not 10s. + request.chunk_throttle.append((1005.0, 5.0)) + request.chunk_throttle.append((1003.0, 5.0)) + return names + + with mock.patch.object( + AKSMachineClient, "_scale_machine_batch", side_effect=fake_batch, + ), mock.patch.object( + AKSMachineClient, "_wait_for_agentpool_provisioning", return_value=True + ), mock.patch.object( + AKSMachineClient, + "_wait_for_machine_node_readiness", + return_value={ + f"P{p}": { + "target_nodes": 2, + "elapsed_time_seconds": 12.0, + "percentage": p, + "success": True, + } + for p in (50, 70, 90, 99, 100) + }, + ): + self.mock_k8s.get_ready_nodes.return_value = [] + self.client.scale_machine( + agent_pool_name="apool", + vm_size="Standard_D2_v3", + scale_machine_count=2, + use_batch_api=True, + machine_workers=2, + ) + + # Only the critical-path chunk's 5s backoff delayed the PUT makespan (not 10s). + # It is removed from command_execution_time (fan-out ~instant -> wall - 5s + # floors to 0) and recorded as throttle_wait_seconds, but the operation + # duration is NOT adjusted (op.exclude_time is not called): the PUT-phase + # critical path may not determine end-to-end completion. + self.mock_operation.add_metadata.assert_any_call("command_execution_time", 0.0) + self.mock_operation.add_metadata.assert_any_call("throttle_wait_seconds", 5.0) + self.mock_operation.exclude_time.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/modules/python/tests/utils/test_provisioning_instrumentation.py b/modules/python/tests/utils/test_provisioning_instrumentation.py index 8b5e681e0f..1853aaaaaf 100644 --- a/modules/python/tests/utils/test_provisioning_instrumentation.py +++ b/modules/python/tests/utils/test_provisioning_instrumentation.py @@ -9,21 +9,32 @@ from azure.core.exceptions import HttpResponseError from utils.provisioning_instrumentation import ( + RETRY_WAIT_SECONDS, begin_create_or_update_with_retry, instrument_nodepool_provisioning, ) class TestInstrumentNodepoolProvisioning(unittest.TestCase): - """Tests for instrument_nodepool_provisioning""" + """Tests for instrument_nodepool_provisioning. + + These drive the concurrent ARM/K8s ThreadPoolExecutor with a shared mocked + ``time.time()`` side_effect list, and rely on ARM-thread-first scheduling: the + ARM thread must consume its post-callable ``time.time()`` before the K8s thread + (values ordered arm_done then ready). This is not guaranteed by the runtime -- + the mocked callables are instant so the ARM thread usually finishes within one + GIL slice, but if these ever flake, replace the positional side_effect with a + caller-keyed ``time.time`` stub instead of a shared list. + """ @mock.patch("utils.provisioning_instrumentation.time") def test_records_timing_metadata(self, mock_time): - """Both node_readiness_time and command_execution_time are stored""" + """Timings are measured from the ARM accept; no wait when accepted immediately.""" + # start=100, arm done=140, nodes ready=130; ARM accepted at 100 (no retry). mock_time.time.side_effect = [100, 140, 130] op = mock.MagicMock() - arm_callable = mock.MagicMock(return_value=False) + arm_callable = mock.MagicMock(return_value=(100, False)) # (command_start, retry_occurred) ready_nodes = [mock.MagicMock()] k8s_callable = mock.MagicMock(return_value=ready_nodes) @@ -34,18 +45,22 @@ def test_records_timing_metadata(self, mock_time): k8s_wait_callable=k8s_callable, ) + # command_execution_time = 140 - 100 = 40; node_readiness = 130 - 100 = 30 self.assertEqual(result, ready_nodes) op.add_metadata.assert_any_call("node_readiness_time", 30) op.add_metadata.assert_any_call("command_execution_time", 40) op.add_metadata.assert_any_call("retry_occurred", False) + # Operation.end() (not instrument) owns in_progress_wait_seconds. + op.exclude_time.assert_called_once_with(0) @mock.patch("utils.provisioning_instrumentation.time") - def test_retry_occurred_true(self, mock_time): - """retry_occurred=True is stored when arm_callable returns True""" + def test_in_progress_wait_excluded_from_timings(self, mock_time): + """Pre-accept queue-wait is excluded from the op duration and both timings.""" + # start=100, accepted attempt starts at 130 (30s queue-wait), arm done=160, ready=150. mock_time.time.side_effect = [100, 160, 150] op = mock.MagicMock() - arm_callable = mock.MagicMock(return_value=True) + arm_callable = mock.MagicMock(return_value=(130, True)) # (command_start, retry_occurred) k8s_callable = mock.MagicMock(return_value=[mock.MagicMock()]) instrument_nodepool_provisioning( @@ -55,7 +70,12 @@ def test_retry_occurred_true(self, mock_time): k8s_wait_callable=k8s_callable, ) + # measured from accepted-attempt start (130): command = 160-130 = 30; readiness = 150-130 = 20 + op.add_metadata.assert_any_call("command_execution_time", 30) + op.add_metadata.assert_any_call("node_readiness_time", 20) op.add_metadata.assert_any_call("retry_occurred", True) + # 30s of pre-accept wait is fed to the op; Operation.end() records it. + op.exclude_time.assert_called_once_with(30) @mock.patch("utils.provisioning_instrumentation.time") def test_arm_failure_raises(self, mock_time): @@ -76,12 +96,13 @@ def test_arm_failure_raises(self, mock_time): self.assertIn("ARM failed", str(ctx.exception)) @mock.patch("utils.provisioning_instrumentation.time") - def test_k8s_failure_raises(self, mock_time): - """K8s failure is raised when ARM succeeds""" - mock_time.time.side_effect = [100, 110, 110] + def test_k8s_failure_raises_still_excludes_queue_wait(self, mock_time): + """K8s failure re-raises, but the pre-accept queue-wait is still excluded.""" + # start=100, ARM accepted at 130 (30s queue-wait) then succeeds; K8s fails. + mock_time.time.side_effect = [100, 160, 150] op = mock.MagicMock() - arm_callable = mock.MagicMock(return_value=False) + arm_callable = mock.MagicMock(return_value=(130, True)) k8s_callable = mock.MagicMock(side_effect=RuntimeError("K8s timeout")) with self.assertRaises(RuntimeError) as ctx: @@ -92,6 +113,30 @@ def test_k8s_failure_raises(self, mock_time): k8s_wait_callable=k8s_callable, ) self.assertIn("K8s timeout", str(ctx.exception)) + # 30s of queue-wait (command_start 130 - start 100) excluded before re-raise. + op.exclude_time.assert_called_once_with(30) + + @mock.patch("utils.provisioning_instrumentation.time") + def test_arm_accept_then_fail_excludes_attached_queue_wait(self, mock_time): + """ARM accepted-then-failed: the attached accept time is excluded on failure.""" + mock_time.time.side_effect = [100, 160, 150] + + op = mock.MagicMock() + # arm_callable raises, but carries the accepted attempt's start (130). + arm_err = RuntimeError("provisioning failed") + arm_err.request_started_at = 130 + arm_callable = mock.MagicMock(side_effect=arm_err) + k8s_callable = mock.MagicMock(return_value=[mock.MagicMock()]) + + with self.assertRaises(RuntimeError) as ctx: + instrument_nodepool_provisioning( + node_pool_name="pool1", + op=op, + arm_callable=arm_callable, + k8s_wait_callable=k8s_callable, + ) + self.assertIn("provisioning failed", str(ctx.exception)) + op.exclude_time.assert_called_once_with(30) class TestBeginCreateOrUpdateWithRetry(unittest.TestCase): @@ -99,8 +144,9 @@ class TestBeginCreateOrUpdateWithRetry(unittest.TestCase): @mock.patch("utils.provisioning_instrumentation.time") def test_succeeds_first_attempt(self, mock_time): - """Returns False (no retry) on first-attempt success""" + """Returns (request_started_at, False) on first-attempt success""" mock_time.sleep = mock.MagicMock() + mock_time.time.return_value = 500 # accepted attempt start mock_poller = mock.MagicMock() mock_poller.done.return_value = True @@ -115,13 +161,14 @@ def test_succeeds_first_attempt(self, mock_time): parameters={}, ) - self.assertFalse(result) + self.assertEqual(result, (500, False)) sdk_client.agent_pools.begin_create_or_update.assert_called_once() @mock.patch("utils.provisioning_instrumentation.time") def test_retries_on_operation_not_allowed(self, mock_time): - """Returns True (retry occurred) after transient OperationNotAllowed""" + """Returns (request_started_at, True) after a transient OperationNotAllowed""" mock_time.sleep = mock.MagicMock() + mock_time.time.return_value = 500 # accepted attempt start (the retry) error = HttpResponseError(message="OperationNotAllowed") error.error = mock.MagicMock() @@ -142,10 +189,11 @@ def test_retries_on_operation_not_allowed(self, mock_time): cluster_name="cluster1", node_pool_name="pool1", parameters={}, - retry_wait=0, ) - self.assertTrue(result) + # Accepted on the 2nd attempt; retry_occurred flagged True. + self.assertEqual(result, (500, True)) + mock_time.sleep.assert_called_once_with(RETRY_WAIT_SECONDS) self.assertEqual(sdk_client.agent_pools.begin_create_or_update.call_count, 2) @mock.patch("utils.provisioning_instrumentation.time") @@ -160,7 +208,7 @@ def test_raises_non_retryable_error(self, mock_time): sdk_client = mock.MagicMock() sdk_client.agent_pools.begin_create_or_update.side_effect = error - with self.assertRaises(HttpResponseError): + with self.assertRaises(HttpResponseError) as ctx: begin_create_or_update_with_retry( aks_sdk_client=sdk_client, resource_group="rg", @@ -169,10 +217,14 @@ def test_raises_non_retryable_error(self, mock_time): parameters={}, ) sdk_client.agent_pools.begin_create_or_update.assert_called_once() + # Non-retryable failure is real ARM latency, not queue-wait: no timing + # anchor is attached, so the caller excludes nothing. + self.assertIsNone(getattr(ctx.exception, "request_started_at", None)) + @mock.patch("utils.provisioning_instrumentation.TIMEOUT_SECONDS", 0) @mock.patch("utils.provisioning_instrumentation.time") def test_timeout_raises(self, mock_time): - """TimeoutError raised when poller exceeds timeout""" + """TimeoutError raised when poller exceeds TIMEOUT_SECONDS""" mock_time.sleep = mock.MagicMock() mock_poller = mock.MagicMock() @@ -189,9 +241,95 @@ def test_timeout_raises(self, mock_time): cluster_name="cluster1", node_pool_name="pool1", parameters={}, - timeout=0, ) + @mock.patch("utils.provisioning_instrumentation.time") + def test_post_accept_failure_attaches_request_started_at(self, mock_time): + """An accepted op that then fails carries the accept time on the exception.""" + mock_time.time.return_value = 500 + mock_time.sleep = mock.MagicMock() + + poller = mock.MagicMock() + poller.done.return_value = True + poller.result.side_effect = RuntimeError("provisioning failed") + sdk_client = mock.MagicMock() + sdk_client.agent_pools.begin_create_or_update.return_value = poller + + with self.assertRaises(RuntimeError) as ctx: + begin_create_or_update_with_retry( + aks_sdk_client=sdk_client, + resource_group="rg", + cluster_name="cluster1", + node_pool_name="pool1", + parameters={}, + ) + # The accepted attempt's start is attached so the caller can exclude it. + self.assertEqual(getattr(ctx.exception, "request_started_at", None), 500) + + @mock.patch("utils.provisioning_instrumentation.MAX_RETRIES", 3) + @mock.patch("utils.provisioning_instrumentation.time") + def test_exhausted_budget_reraises_last_error(self, mock_time): + """Every attempt OperationNotAllowed -> the last attempt re-raises it.""" + mock_time.sleep = mock.MagicMock() + + error = HttpResponseError(message="OperationNotAllowed") + error.error = mock.MagicMock() + error.error.code = "OperationNotAllowed" + + sdk_client = mock.MagicMock() + sdk_client.agent_pools.begin_create_or_update.side_effect = error + + with self.assertRaises(HttpResponseError): + begin_create_or_update_with_retry( + aks_sdk_client=sdk_client, + resource_group="rg", + cluster_name="cluster1", + node_pool_name="pool1", + parameters={}, + ) + # All 3 attempts made; the last one (no retry left) re-raises. + self.assertEqual(sdk_client.agent_pools.begin_create_or_update.call_count, 3) + + @mock.patch("utils.provisioning_instrumentation.MAX_RETRIES", 3) + @mock.patch("utils.provisioning_instrumentation.time") + def test_terminal_rejection_attaches_timing_anchor(self, mock_time): + """A never-admitted op anchors the exclusion at the give-up time.""" + mock_time.sleep = mock.MagicMock() + mock_time.time.return_value = 900 # give-up timestamp + + error = HttpResponseError(message="OperationNotAllowed") + error.error = mock.MagicMock() + error.error.code = "OperationNotAllowed" + + sdk_client = mock.MagicMock() + sdk_client.agent_pools.begin_create_or_update.side_effect = error + + with self.assertRaises(HttpResponseError) as ctx: + begin_create_or_update_with_retry( + aks_sdk_client=sdk_client, + resource_group="rg", + cluster_name="cluster1", + node_pool_name="pool1", + parameters={}, + ) + # Timing anchor attached so the caller excludes the rejected-attempt wait. + self.assertEqual(getattr(ctx.exception, "request_started_at", None), 900) + + @mock.patch("utils.provisioning_instrumentation.MAX_RETRIES", 0) + def test_zero_max_retries_raises_runtime_error(self): + """MAX_RETRIES=0 makes no attempt and raises RuntimeError (guards None return).""" + sdk_client = mock.MagicMock() + with self.assertRaises(RuntimeError) as ctx: + begin_create_or_update_with_retry( + aks_sdk_client=sdk_client, + resource_group="rg", + cluster_name="cluster1", + node_pool_name="pool1", + parameters={}, + ) + self.assertIn("exhausted", str(ctx.exception)) + sdk_client.agent_pools.begin_create_or_update.assert_not_called() + if __name__ == "__main__": unittest.main() diff --git a/modules/python/utils/common.py b/modules/python/utils/common.py index 9aaace09e5..e358a3b7d3 100644 --- a/modules/python/utils/common.py +++ b/modules/python/utils/common.py @@ -2,6 +2,7 @@ import os import json import argparse +from typing import List, Tuple from utils.logger_config import get_logger, setup_logging # Configure logging @@ -71,3 +72,20 @@ def str2bool(val): if val.lower() in ("false", "no", "0"): return False raise argparse.ArgumentTypeError("Boolean value expected.") + + +def compute_throttle_delay(chunks: List[Tuple[float, float]]) -> float: + """Throttle delay to a concurrent command's completion. + + ``chunks`` is per-worker ``(finish_time, backoff_seconds)``. Backoff is pure + delay on a worker's own timeline, so its throttle-free finish is + ``finish - backoff`` and the delay is ``max(finish) - max(finish - backoff)``. + Only backoff on the critical path counts -- off-path backoff hides behind + other workers. Assumes workers start concurrently (each Machine chunk gets its + own pool slot); queued workers would make this under-count. + """ + if not chunks: + return 0.0 + actual_finish = max(finish for finish, _ in chunks) + finish_without_backoff = max(finish - backoff for finish, backoff in chunks) + return max(0.0, actual_finish - finish_without_backoff) diff --git a/modules/python/utils/provisioning_instrumentation.py b/modules/python/utils/provisioning_instrumentation.py index f8e38a5e13..f84ce017ea 100644 --- a/modules/python/utils/provisioning_instrumentation.py +++ b/modules/python/utils/provisioning_instrumentation.py @@ -14,6 +14,29 @@ logger = get_logger(__name__) +IN_PROGRESS_CODES = ("OperationNotAllowed", "EtagMismatch") +MAX_RETRIES = 10 # in-progress (409) submit attempts +RETRY_WAIT_SECONDS = 30 # sleep between rejected submit attempts +POLL_INTERVAL_SECONDS = 30 # poller.done() polling cadence +TIMEOUT_SECONDS = 1800 # LRO poll timeout (slow A100 MIG provisioning) + + +def _record_excluded_time(op, command_start, start_time): + """Exclude pre-accept queue-wait from the op duration; return the seconds excluded.""" + if command_start is None: + return 0.0 + excluded = max(0, command_start - start_time) + op.exclude_time(excluded) + return excluded + + +def _log_provisioning_success(node_pool_name, label, command_time, readiness_time, queue_wait): + logger.info( + "[%s] %sARM %.2fs, K8s ready %.2fs | Delta %.2fs | queue-wait excluded %.2fs", + node_pool_name, label, command_time, readiness_time, + abs(command_time - readiness_time), queue_wait, + ) + def instrument_nodepool_provisioning( node_pool_name, @@ -61,24 +84,23 @@ def instrument_nodepool_provisioning( "Concurrent operation failed after %.2fs - ARM: %s, K8s readiness: %s", elapsed, arm_status, k8s_status ) - if arm_exc: - raise arm_exc - raise k8s_exc - - arm_result, arm_timestamp = arm_future.result() + if not arm_exc: + (command_start, _), _ = arm_future.result() + else: + command_start = getattr(arm_exc, "request_started_at", None) + _record_excluded_time(op, command_start, start_time) + raise arm_exc or k8s_exc + + (command_start, retry_occurred), arm_timestamp = arm_future.result() ready_nodes, ready_timestamp = k8s_future.result() + command_execution_time = max(0, arm_timestamp - command_start) + node_readiness_time = max(0, ready_timestamp - command_start) - node_readiness_time = ready_timestamp - start_time - command_execution_time = arm_timestamp - start_time - + queue_wait = _record_excluded_time(op, command_start, start_time) op.add_metadata("node_readiness_time", node_readiness_time) op.add_metadata("command_execution_time", command_execution_time) - op.add_metadata("retry_occurred", bool(arm_result)) - logger.info( - "[%s] %sARM completed in %.2fs, K8s nodes ready in %.2fs | Delta: %.2fs", - node_pool_name, label, command_execution_time, node_readiness_time, - abs(command_execution_time - node_readiness_time) - ) + op.add_metadata("retry_occurred", retry_occurred) + _log_provisioning_success(node_pool_name, label, command_execution_time, node_readiness_time, queue_wait) return ready_nodes @@ -90,21 +112,21 @@ def begin_create_or_update_with_retry( node_pool_name, parameters, label="", - retries=10, - retry_wait=30, - poll_interval=30, - timeout=1800, ): """ - Call begin_create_or_update with retry on OperationNotAllowed/EtagMismatch, - polling every poll_interval seconds and raising TimeoutError after timeout seconds. - timeout defaults to 1800s (30 min) for slow GPU node provisioning (A100 MIG). - - Returns: - bool: True if a retry occurred, False if the operation succeeded on the first attempt. + Call begin_create_or_update, retrying IN_PROGRESS_CODES (a *previous* op still + in progress) up to MAX_RETRIES; poll until done, TimeoutError after + TIMEOUT_SECONDS. + + Returns (request_started_at, retry_occurred): request_started_at is when the + accepted (2xx) attempt's PUT was issued, so callers count the accepted + request's frontend time and exclude the failed prior attempts as queue-wait. + On failure it attaches request_started_at to the exception (see below) so the + caller can still exclude the queue-wait. """ retry_occurred = False - for attempt in range(retries): + for attempt in range(MAX_RETRIES): + request_started_at = time.time() try: poller = aks_sdk_client.agent_pools.begin_create_or_update( resource_group_name=resource_group, @@ -112,29 +134,38 @@ def begin_create_or_update_with_retry( agent_pool_name=node_pool_name, parameters=parameters, ) + except HttpResponseError as e: + in_progress = any(code in str(e) for code in IN_PROGRESS_CODES) + if in_progress and attempt < MAX_RETRIES - 1: + retry_occurred = True + error_code = e.error.code if e.error else str(e) + logger.warning( + f"Cluster has an in-progress operation, retrying in {RETRY_WAIT_SECONDS}s " + f"(attempt {attempt + 1}/{MAX_RETRIES}): {error_code}" + ) + time.sleep(RETRY_WAIT_SECONDS) + continue + if in_progress: + e.request_started_at = time.time() + raise + try: elapsed = 0 while not poller.done(): - time.sleep(poll_interval) - elapsed += poll_interval - if elapsed >= timeout: + time.sleep(POLL_INTERVAL_SECONDS) + elapsed += POLL_INTERVAL_SECONDS + if elapsed >= TIMEOUT_SECONDS: raise TimeoutError( - f"Node pool {node_pool_name} {label}timed out after {timeout}s" + f"Node pool {node_pool_name} {label}timed out after {TIMEOUT_SECONDS}s" ) logger.info( f"Waiting for node pool {node_pool_name} {label}to complete " f"({elapsed}s elapsed)..." ) poller.result() - return retry_occurred - except HttpResponseError as e: - if any(code in str(e) for code in ("OperationNotAllowed", "EtagMismatch")) and attempt < retries - 1: - retry_occurred = True - error_code = e.error.code if e.error else str(e) - logger.warning( - f"Cluster has an in-progress operation, retrying in {retry_wait}s " - f"(attempt {attempt + 1}/{retries}): {error_code}" - ) - time.sleep(retry_wait) - else: - raise - return retry_occurred + except Exception as e: + e.request_started_at = request_started_at + raise + return request_started_at, retry_occurred + raise RuntimeError( + f"Node pool {node_pool_name} {label}exhausted {MAX_RETRIES} create/update retries" + )