From c41efadfa6d566dabe8b0f4b1d9ca286daa06668 Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Tue, 12 May 2026 15:09:39 -0700 Subject: [PATCH] feat(crud-machine): add machine data classes and result handler First slice of the k8s-cluster-crud-machine perf-test port from ado-telescope. Introduces a new `machine/` python package with the data records and result-persistence decorator that subsequent slices will build on. Differences from ado-telescope's reference k8s package: - OperationNames is a str Enum (was a frozen @dataclass). - MachineOperationResponse.percentile_node_readiness_times is a nested envelope (Dict[str, Dict[str, Any]]) so each percentile carries its target_nodes / elapsed_time_seconds / percentage / success metadata. - save_test_result writes a nested {config, response} payload instead of a flat **-spread that could overwrite overlapping keys. - Persistence failures are swallowed and logged rather than propagated, so test orchestration stays insulated from disk errors. Verification: - pylint 10.00/10 on all touched files. - pytest: 7/7 new tests pass; machine/data_classes.py 100%, machine/result_handler.py 97%. - Full module pytest --cov-fail-under=80 still green (83.67% total). --- modules/python/machine/__init__.py | 0 modules/python/machine/data_classes.py | 76 ++++++++++++++++++ modules/python/machine/result_handler.py | 55 +++++++++++++ .../python/tests/test_machine_data_classes.py | 41 ++++++++++ .../tests/test_machine_result_handler.py | 78 +++++++++++++++++++ 5 files changed, 250 insertions(+) create mode 100644 modules/python/machine/__init__.py create mode 100644 modules/python/machine/data_classes.py create mode 100644 modules/python/machine/result_handler.py create mode 100644 modules/python/tests/test_machine_data_classes.py create mode 100644 modules/python/tests/test_machine_result_handler.py diff --git a/modules/python/machine/__init__.py b/modules/python/machine/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/modules/python/machine/data_classes.py b/modules/python/machine/data_classes.py new file mode 100644 index 0000000000..133c074fd9 --- /dev/null +++ b/modules/python/machine/data_classes.py @@ -0,0 +1,76 @@ +"""Data classes for the Machine API perf test. + +Differences from ado-telescope's k8s/data_classes.py: +- OperationNames is an Enum (not @dataclass(frozen=True)). +- cloud_data typed as Optional[Dict] (truthful). +- Dropped dead types: BaseConfig, MachineRequestBase, CreateMachineRequest, DeleteMachineRequest. +- Dropped unused fields: api_response, time, feature_name. +""" +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, List, Optional + + +class OperationNames(str, Enum): + """String enum of supported Machine API CRUD operations.""" + CREATE_MACHINE = "create_machine" + SCALE_MACHINE = "scale_machine" + + +# Disable too-many-instance-attributes: this is a flat configuration record that +# mirrors CLI flags 1:1. Splitting it would just reintroduce wrappers. +@dataclass +class MachineConfig: # pylint: disable=too-many-instance-attributes + """Top-level run configuration for a Machine API perf invocation.""" + cloud: str + cluster_name: str + resource_group: str + agentpool_name: str + vm_size: str + timeout: int + result_dir: str + readiness_wait_timeout: int = 1200 + region: Optional[str] = None + operation: Optional[str] = None + tags: Optional[Dict[str, str]] = None + machine_name: Optional[str] = None + scale_machine_count: int = 0 + use_batch_api: bool = False + machine_workers: int = 1 + + +# Disable too-many-instance-attributes: 10 fields all map to ARM Machine PUT body +# inputs; bundling them would just shift the noise. +@dataclass +class ScaleMachineRequest: # pylint: disable=too-many-instance-attributes + """Request payload for scaling an agent pool by creating N Machine resources.""" + cluster_name: str + resource_group: str + agentpool_name: str + vm_size: str + scale_machine_count: int + use_batch_api: bool + machine_workers: int + timeout: int = 300 + readiness_wait_timeout: int = 1200 + tags: Optional[Dict[str, str]] = None + machine_name: Optional[str] = None + + +# Disable too-many-instance-attributes: this dataclass is the on-disk JSON +# schema; reducing fields would silently drop telemetry columns. +@dataclass +class MachineOperationResponse: # pylint: disable=too-many-instance-attributes + """Per-operation response written to disk and aggregated by collect.py.""" + operation_name: str + succeeded: bool = False + start_time: Optional[str] = None + end_time: Optional[str] = None + error: str = "" + command_execution_time: float = 0 + node_readiness_time: float = 0 + successful_machines: List[str] = field(default_factory=list) + percentile_node_readiness_times: Dict[str, Dict[str, Any]] = field(default_factory=dict) + batch_command_execution_times: Dict[str, float] = field(default_factory=dict) + cloud_data: Optional[Dict] = None + warning_message: Optional[str] = None diff --git a/modules/python/machine/result_handler.py b/modules/python/machine/result_handler.py new file mode 100644 index 0000000000..0a0e2300c1 --- /dev/null +++ b/modules/python/machine/result_handler.py @@ -0,0 +1,55 @@ +"""Persist per-operation results to JSON. + +Differences from ado-telescope's k8s/result_handler.py: +- Output is a NESTED dict {"config": ..., "response": ...} + (not flat **-spread that overwrites overlapping keys). +- UTC timestamp in filename. +- Uses utils.common.save_info_to_file when feasible. +""" +import functools +import os +from dataclasses import asdict, is_dataclass +from datetime import datetime, timezone + +from utils.common import save_info_to_file +from utils.logger_config import get_logger + +logger = get_logger(__name__) + + +def _serialize(obj): + """Convert dataclasses to dicts; pass everything else through unchanged.""" + if is_dataclass(obj): + return asdict(obj) + return obj + + +def save_test_result(func): + """Decorator that writes the wrapped method's response to a JSON file. + + The file path is derived from ``self.config`` (cloud / cluster_name / + machine_name|agentpool_name) plus a UTC unix timestamp. Persistence + failures are logged but never propagated, so test orchestration is + insulated from disk errors. + """ + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + response = func(self, *args, **kwargs) + try: + config = self.config + op_name = response.operation_name + suffix = config.machine_name or config.agentpool_name + timestamp = int(datetime.now(timezone.utc).timestamp()) + filename = f"{op_name}-{config.cloud}-{config.cluster_name}-{suffix}-{timestamp}.json" + path = os.path.join(config.result_dir, filename) + os.makedirs(config.result_dir, exist_ok=True) + payload = { + "config": _serialize(config), + "response": _serialize(response), + } + save_info_to_file(payload, path) + logger.info("Wrote result to %s", path) + except Exception as exc: # pylint: disable=broad-except + logger.warning("Failed to save result: %s", exc) + return response + return wrapper diff --git a/modules/python/tests/test_machine_data_classes.py b/modules/python/tests/test_machine_data_classes.py new file mode 100644 index 0000000000..4ce6c84661 --- /dev/null +++ b/modules/python/tests/test_machine_data_classes.py @@ -0,0 +1,41 @@ +from machine.data_classes import ( + MachineConfig, ScaleMachineRequest, MachineOperationResponse, OperationNames, +) + +def test_operation_names_is_enum_with_required_values(): + assert OperationNames.CREATE_MACHINE.value == "create_machine" + assert OperationNames.SCALE_MACHINE.value == "scale_machine" + +def test_machine_config_defaults(): + cfg = MachineConfig( + cloud="azure", cluster_name="c", resource_group="rg", + agentpool_name="ap", vm_size="Standard_D2_v3", + timeout=600, result_dir="/tmp/x", + ) + assert cfg.scale_machine_count == 0 + assert cfg.use_batch_api is False + assert cfg.machine_workers == 1 + assert cfg.region is None + assert cfg.operation is None + assert cfg.tags is None + assert cfg.machine_name is None + +def test_machine_operation_response_defaults_have_correct_types(): + r = MachineOperationResponse(operation_name="scale_machine") + assert r.succeeded is False + assert r.successful_machines == [] + assert r.percentile_node_readiness_times == {} + assert r.batch_command_execution_times == {} + assert r.command_execution_time == 0 + assert r.node_readiness_time == 0 + assert r.cloud_data is None # dict | None, not str + +def test_scale_machine_request_required_fields(): + req = ScaleMachineRequest( + cluster_name="c", resource_group="rg", agentpool_name="ap", + vm_size="Standard_D2_v3", scale_machine_count=5, + use_batch_api=False, machine_workers=2, + ) + assert req.timeout == 300 + assert req.tags is None + assert req.machine_name is None diff --git a/modules/python/tests/test_machine_result_handler.py b/modules/python/tests/test_machine_result_handler.py new file mode 100644 index 0000000000..41a8a03d87 --- /dev/null +++ b/modules/python/tests/test_machine_result_handler.py @@ -0,0 +1,78 @@ +import json +import logging +import os +import glob +from unittest.mock import patch + +from machine.data_classes import MachineConfig, MachineOperationResponse +from machine.result_handler import save_test_result + + +class _FakeMgr: + """Minimal stand-in for MachineManager exposing only ``config``.""" + def __init__(self, config): + self.config = config + + +def test_save_test_result_writes_nested_dict(tmp_path): + cfg = MachineConfig( + cloud="azure", cluster_name="cl", resource_group="rg", + agentpool_name="ap", vm_size="Standard_D2_v3", + timeout=600, result_dir=str(tmp_path), + machine_name="m1", + ) + + @save_test_result + def fake_op(self): # pylint: disable=unused-argument + return MachineOperationResponse( + operation_name="scale_machine", + succeeded=True, + command_execution_time=12.5, + ) + + fake_op(_FakeMgr(cfg)) + files = glob.glob(str(tmp_path / "scale_machine-*.json")) + assert len(files) == 1 + with open(files[0], encoding="utf-8") as fh: + payload = json.loads(fh.read()) + # Nested, not flat-merged. Distinct keys preserved. + assert "config" in payload and "response" in payload + assert payload["config"]["cloud"] == "azure" + assert payload["response"]["operation_name"] == "scale_machine" + assert payload["response"]["succeeded"] is True + # Filename includes operation, cloud, cluster, machine_name. + assert "scale_machine-azure-cl-m1-" in os.path.basename(files[0]) + + +def test_save_test_result_uses_agentpool_when_no_machine_name(tmp_path): + cfg = MachineConfig( + cloud="azure", cluster_name="cl", resource_group="rg", + agentpool_name="apool", vm_size="x", timeout=1, result_dir=str(tmp_path), + ) + + @save_test_result + def fake(self): # pylint: disable=unused-argument + return MachineOperationResponse(operation_name="create_machine", succeeded=True) + + fake(_FakeMgr(cfg)) + fs = glob.glob(str(tmp_path / "create_machine-*.json")) + assert any("create_machine-azure-cl-apool-" in os.path.basename(f) for f in fs) + + +def test_save_test_result_swallows_write_errors(tmp_path, caplog): + cfg = MachineConfig( + cloud="azure", cluster_name="cl", resource_group="rg", + agentpool_name="ap", vm_size="x", timeout=1, result_dir=str(tmp_path), + machine_name="m1", + ) + + @save_test_result + def fake(self): # pylint: disable=unused-argument + return MachineOperationResponse(operation_name="scale_machine", succeeded=True) + + with patch("machine.result_handler.save_info_to_file", side_effect=OSError("disk full")): + with caplog.at_level(logging.WARNING, logger="machine.result_handler"): + response = fake(_FakeMgr(cfg)) + + assert response.operation_name == "scale_machine" + assert any("Failed to save result" in rec.message for rec in caplog.records)