Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 47 additions & 47 deletions modules/python/clients/aks_machine_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand All @@ -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(
Expand All @@ -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
Expand All @@ -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))
16 changes: 15 additions & 1 deletion modules/python/crud/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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
Expand Down
27 changes: 22 additions & 5 deletions modules/python/tests/clients/test_aks_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down
84 changes: 84 additions & 0 deletions modules/python/tests/crud/test_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down
6 changes: 3 additions & 3 deletions modules/python/tests/test_aks_machine_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
Loading
Loading