diff --git a/tests/conftest.py b/tests/conftest.py index 91c1b2fa9da6..837373cead4e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,6 +6,7 @@ import os import shutil import tempfile +import time from pathlib import Path from typing import Generator, Optional @@ -26,7 +27,7 @@ ) from tests.utils.constants import TEST_MODELS, DynamoPortRange from tests.utils.managed_process import ManagedProcess -from tests.utils.output_paths import resolve_test_output_path +from tests.utils.output_paths import prepare_test_output_dir, resolve_test_output_path from tests.utils.port_utils import ( ServicePorts, allocate_contiguous_ports, @@ -44,6 +45,8 @@ _gpu_indices_key: pytest.StashKey[list[int] | None] = pytest.StashKey() _gpu_slots_key: pytest.StashKey[int | None] = pytest.StashKey() _collection_env_snapshot_key: pytest.StashKey[dict[str, str]] = pytest.StashKey() +# Session start time; the logger fixture removes test output older than this. +_output_session_start_key: pytest.StashKey[float] = pytest.StashKey() # Controller-side accumulator for collection-env changes reported by xdist workers. _collection_env_changes_key: pytest.StashKey[dict] = pytest.StashKey() @@ -56,6 +59,7 @@ def _is_xdist_worker(config: pytest.Config) -> bool: @pytest.hookimpl(tryfirst=True) def pytest_sessionstart(session: pytest.Session) -> None: + session.stash[_output_session_start_key] = time.time() if not collection_env_guard_disabled(): session.config.stash[_collection_env_snapshot_key] = snapshot_collection_env() @@ -624,8 +628,10 @@ def logger(request): log_dir = resolve_test_output_path(request.node.name) log_path = os.path.join(log_dir, "test.log.txt") logger = logging.getLogger() - shutil.rmtree(log_dir, ignore_errors=True) - os.makedirs(log_dir, exist_ok=True) + session_start = request.session.stash.setdefault( + _output_session_start_key, time.time() + ) + prepare_test_output_dir(log_dir, session_start) handler = logging.FileHandler(log_path, mode="w") formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT) handler.setFormatter(formatter) diff --git a/tests/deploy/dgd_utils.py b/tests/deploy/dgd_utils.py index 620e07de4833..10417eacd107 100644 --- a/tests/deploy/dgd_utils.py +++ b/tests/deploy/dgd_utils.py @@ -66,6 +66,7 @@ PORT_FORWARD_REQUEST_RETRY_LIMIT = 1 DISCOVERY_SNAPSHOT_TIMEOUT = 15 DISCOVERY_RESOURCE_TIMEOUT = 3 +READINESS_DIAGNOSTICS_TIMEOUT = 30 _KR8S_VCLUSTER_CONNECTION_ERRORS = (httpx.TransportError, kr8s.APITimeoutError) @@ -1055,7 +1056,48 @@ async def _wait_for_condition( desired_state_val: str = "successful", ): start_time = time.time() + # One deadline for the whole wait, so a stalled Kubernetes request + # cannot run past it and skip the pod diagnostics below. + try: + async with asyncio.timeout(timeout): + if await self._poll_for_condition( + start_time, + timeout, + sleep, + log_interval, + desired_ready_condition_val, + desired_state_val, + ): + return True + except TimeoutError: + pass + + # Collect pod diagnostics before raising + try: + async with asyncio.timeout(READINESS_DIAGNOSTICS_TIMEOUT): + pod_details = await self._get_pod_status_details() + except TimeoutError: + pod_details = [] + elapsed = time.time() - start_time + msg = ( + f"Deployment {self._deployment_name} failed to reach " + f"Ready={desired_ready_condition_val}, state={desired_state_val} " + f"within {elapsed:.0f}s (timeout={timeout}s)" + ) + if pod_details: + detail_lines = "\n".join(f" {d.format()}" for d in pod_details) + msg += f"\n\nPod status at timeout:\n{detail_lines}" + raise TimeoutError(msg) + async def _poll_for_condition( + self, + start_time: float, + timeout: int, + sleep, + log_interval, + desired_ready_condition_val: bool, + desired_state_val: str, + ) -> bool: self._logger.info( f"Waiting for Deployment {self._deployment_name} to have Ready condition {desired_ready_condition_val} and state {desired_state_val}" ) @@ -1172,19 +1214,7 @@ async def _wait_for_condition( f"Unexpected exception while checking deployment status: {e}" ) await asyncio.sleep(sleep) - - # Collect pod diagnostics before raising - pod_details = await self._get_pod_status_details() - elapsed = time.time() - start_time - msg = ( - f"Deployment {self._deployment_name} failed to reach " - f"Ready={desired_ready_condition_val}, state={desired_state_val} " - f"within {elapsed:.0f}s (timeout={timeout}s)" - ) - if pod_details: - detail_lines = "\n".join(f" {d.format()}" for d in pod_details) - msg += f"\n\nPod status at timeout:\n{detail_lines}" - raise TimeoutError(msg) + return False async def _get_pod_status_details(self) -> List[PodStatusDetail]: """Collect container-level status for all pods owned by this deployment. @@ -1941,6 +1971,8 @@ async def _capture_discovery_state(self): ), ) # DWM ownership is through Pod UIDs; a DGD label selector can miss it. + # Read raw JSON: client models reject `endpoints: null`, which the API + # returns for an EndpointSlice with no ready endpoints. for name, read in resources: record = { "namespace": self.namespace, @@ -1949,8 +1981,19 @@ async def _capture_discovery_state(self): } try: async with asyncio.timeout(DISCOVERY_RESOURCE_TIMEOUT): - response = await read(_request_timeout=DISCOVERY_RESOURCE_TIMEOUT) - record["response"] = api_client.sanitize_for_serialization(response) + response = await read( + _request_timeout=DISCOVERY_RESOURCE_TIMEOUT, + _preload_content=False, + ) + try: + body = await response.text() + finally: + response.release() + if not 200 <= response.status <= 299: + raise exceptions.ApiException( + status=response.status, reason=f"{response.reason}: {body}" + ) + record["response"] = json.loads(body) except Exception as error: record["error"] = f"{type(error).__name__}: {error}" self._logger.warning( diff --git a/tests/deploy/test_dgd.py b/tests/deploy/test_dgd.py index 552321cedf1a..514e017b07fc 100644 --- a/tests/deploy/test_dgd.py +++ b/tests/deploy/test_dgd.py @@ -199,6 +199,9 @@ async def test_deployment( deployment_spec=deployment_spec, namespace=namespace, skip_service_restart=skip_service_restart, + # Below @pytest.mark.timeout(1200), leaving room for the model wait + # and cleanup, so a stuck rollout fails with pod diagnostics. + readiness_timeout=900, ) as deployment: # Get frontend pod for port forwarding frontend_pods = deployment.get_pods([deployment.frontend_service_name]) @@ -341,7 +344,8 @@ def send_with_retry(url, payload, *, timeout, method, stream): and any( endpoint.get("targetRef", {}).get("uid") in pod_uids and endpoint.get("conditions", {}).get("ready") - for endpoint in item["endpoints"] + # The API returns `endpoints: null` for a slice with no endpoints. + for endpoint in item["endpoints"] or () ) for item in snapshots["endpointslices"] ) diff --git a/tests/deploy/test_dgd_utils.py b/tests/deploy/test_dgd_utils.py index 08aa102125c9..08da110213ea 100644 --- a/tests/deploy/test_dgd_utils.py +++ b/tests/deploy/test_dgd_utils.py @@ -4,6 +4,7 @@ """Unit tests for schema-aware DynamoGraphDeployment helpers.""" import asyncio +import json from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, PropertyMock @@ -13,6 +14,7 @@ import pytest import requests import yaml +from kubernetes_asyncio import client from tests.deploy import dgd_utils from tests.deploy.dgd_utils import DeploymentSpec, ManagedDeployment @@ -346,3 +348,136 @@ async def delete(*, fail_on_timeout=True): pass assert events == expected_events + + +class _FakeHttpResponse: + """The parts of an aiohttp response that kubernetes_asyncio reads.""" + + def __init__(self, payload, status=200, reason="OK"): + self.status = status + self.reason = reason + self.headers = {"Content-Type": "application/json"} + self._body = json.dumps(payload).encode() + self.released = False + + async def read(self): + return self._body + + async def text(self): + return self._body.decode() + + def release(self): + self.released = True + + +class _FakeHttpSession: + def __init__(self, payloads): + self.payloads = payloads + self.responses = [] + + async def request(self, method, url, **kwargs): + resource = url.rsplit("/", 1)[-1].split("?", 1)[0] + response = _FakeHttpResponse(*self.payloads[resource]) + self.responses.append(response) + return response + + async def close(self): + pass + + +async def _capture_discovery(tmp_path, payloads): + deployment = managed_deployment(tmp_path) + api_client = client.ApiClient(client.Configuration(host="http://kubernetes.test")) + await api_client.rest_client.pool_manager.close() + session = _FakeHttpSession(payloads) + api_client.rest_client.pool_manager = session + deployment._custom_api = client.CustomObjectsApi(api_client) + deployment._core_api = client.CoreV1Api(api_client) + + try: + await deployment._capture_discovery_state() + finally: + await api_client.close() + + assert len(session.responses) == 5 + assert all(response.released for response in session.responses) + + +_EMPTY_LIST = ({"apiVersion": "v1", "metadata": {}, "items": []},) + + +async def test_discovery_capture_records_endpointslice_without_endpoints( + tmp_path, +): + endpoint_slice = { + "metadata": { + "name": "frontend-abc12", + "labels": {"kubernetes.io/service-name": "frontend"}, + }, + "addressType": "IPv4", + "endpoints": None, + } + await _capture_discovery( + tmp_path, + { + "dynamographdeployments": _EMPTY_LIST, + "dynamoworkermetadatas": _EMPTY_LIST, + "pods": _EMPTY_LIST, + "services": _EMPTY_LIST, + "endpointslices": ( + { + "apiVersion": "discovery.k8s.io/v1", + "kind": "EndpointSliceList", + "metadata": {}, + "items": [endpoint_slice], + }, + ), + }, + ) + + record = json.loads((tmp_path / "discovery" / "endpointslices.json").read_text()) + assert "error" not in record, record + assert record["response"]["items"] == [endpoint_slice] + + +async def test_discovery_capture_records_api_error_body(tmp_path): + forbidden = { + "kind": "Status", + "status": "Failure", + "message": "pods is forbidden: cannot list resource pods", + "code": 403, + } + + await _capture_discovery( + tmp_path, + { + "dynamographdeployments": _EMPTY_LIST, + "dynamoworkermetadatas": _EMPTY_LIST, + "pods": (forbidden, 403, "Forbidden"), + "services": _EMPTY_LIST, + "endpointslices": _EMPTY_LIST, + }, + ) + + record = json.loads((tmp_path / "discovery" / "pods.json").read_text()) + assert "response" not in record, record + assert "403" in record["error"] + assert forbidden["message"] in record["error"] + + +async def test_readiness_wait_deadline_covers_stalled_request(tmp_path, monkeypatch): + deployment = managed_deployment(tmp_path) + + async def stalled_status(**kwargs): + await asyncio.sleep(60) + + deployment._custom_api = SimpleNamespace( + get_namespaced_custom_object=stalled_status + ) + monkeypatch.setattr( + deployment, "_get_pod_status_details", AsyncMock(return_value=[]) + ) + + with pytest.raises(TimeoutError, match="failed to reach Ready=True"): + async with asyncio.timeout(10): + await deployment._wait_for_ready(timeout=1) diff --git a/tests/utils/output_paths.py b/tests/utils/output_paths.py index 4bef225953ab..a61ce9a0658b 100644 --- a/tests/utils/output_paths.py +++ b/tests/utils/output_paths.py @@ -8,7 +8,9 @@ output out of the git working tree by default. """ +import glob import os +import shutil import tempfile from pathlib import Path from typing import Union @@ -59,3 +61,44 @@ def resolve_test_output_path(path: Union[str, Path]) -> str: os.path.join(tempfile.gettempdir(), "dynamo_tests"), ) return os.path.join(log_root, path_str) + + +# File timestamps use a coarse kernel clock that can trail time.time() by a +# few milliseconds, so output just created this session must not look stale. +_STALE_OUTPUT_MARGIN_S = 1.0 + + +def prepare_test_output_dir(log_dir: str, session_start: float) -> None: + """Create an empty output directory for one execution of a test. + + Output last modified before ``session_start`` is left from an earlier + session and is removed. Output written during this session belongs to an + earlier attempt of this test, retried by Datadog or pytest-rerunfailures, + or to a same-named test in another file or xdist worker; it is moved to the + first free ``.attempt`` so it is uploaded too. Checking the + time instead of counting attempts gives the same answer in every xdist + worker, because the workers share the output directory. + """ + for path in [log_dir, *glob.glob(f"{glob.escape(log_dir)}.attempt*")]: + try: + stale = os.path.getmtime(path) < session_start - _STALE_OUTPUT_MARGIN_S + except OSError: + continue + if stale: + shutil.rmtree(path, ignore_errors=True) + attempt = 1 + while os.path.exists(log_dir): + archive = f"{log_dir}.attempt{attempt}" + attempt += 1 + try: + # mkdir claims the slot atomically, so two workers cannot pick the + # same one; rename then replaces the claimed empty directory. + os.mkdir(archive) + except FileExistsError: + continue + try: + os.rename(log_dir, archive) + except FileNotFoundError: + os.rmdir(archive) + break + os.makedirs(log_dir, exist_ok=True)