Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
5 changes: 2 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,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,
Expand Down Expand Up @@ -624,8 +624,7 @@ 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)
prepare_test_output_dir(log_dir, request.node.nodeid)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
handler = logging.FileHandler(log_path, mode="w")
formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT)
handler.setFormatter(formatter)
Expand Down
13 changes: 11 additions & 2 deletions tests/deploy/dgd_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1941,6 +1941,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,
Expand All @@ -1949,8 +1951,15 @@ 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:
response.raise_for_status()
Comment thread
glamr-agent marked this conversation as resolved.
Resolved
record["response"] = await response.json()
finally:
response.release()
except Exception as error:
record["error"] = f"{type(error).__name__}: {error}"
self._logger.warning(
Expand Down
6 changes: 5 additions & 1 deletion tests/deploy/test_dgd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down Expand Up @@ -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"]
)
Expand Down
85 changes: 85 additions & 0 deletions tests/deploy/test_dgd_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -346,3 +348,86 @@ async def delete(*, fail_on_timeout=True):
pass

assert events == expected_events


class _FakeHttpResponse:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need these?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nursery: I changed nothing. In tests/deploy/test_dgd_utils.py, _FakeHttpSession and _FakeHttpResponse let the two discovery tests use the real kubernetes_asyncio client without a Kubernetes cluster.

I checked _capture_discovery and ManagedDeployment._capture_discovery_state. Only the HTTP session is replaced. The client still handles the response, so the EndpointSlice test can catch the old failure when its model rejects endpoints: null. Returning a dictionary from a mocked API method would skip that step and miss the failure.

The second test checks that a 403 response saves the API server's error message. Both tests also check that all five responses are released. These classes supply the response methods and status fields those paths need.

"""The parts of an aiohttp response that kubernetes_asyncio reads."""

def __init__(self, payload):
self.status = 200
self.reason = "OK"
self.headers = {"Content-Type": "application/json"}
self._body = json.dumps(payload).encode()
self.released = False

async def read(self):
return self._body

async def json(self):
return json.loads(self._body)

def raise_for_status(self):
pass

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 test_discovery_capture_records_endpointslice_without_endpoints(
tmp_path,
):
deployment = managed_deployment(tmp_path)
api_client = client.ApiClient(client.Configuration(host="http://kubernetes.test"))
await api_client.rest_client.pool_manager.close()
empty = {"apiVersion": "v1", "metadata": {}, "items": []}
endpoint_slice = {
"metadata": {
"name": "frontend-abc12",
"labels": {"kubernetes.io/service-name": "frontend"},
},
"addressType": "IPv4",
"endpoints": None,
}
session = _FakeHttpSession(
{
"dynamographdeployments": empty,
"dynamoworkermetadatas": empty,
"pods": empty,
"services": empty,
"endpointslices": {
"apiVersion": "discovery.k8s.io/v1",
"kind": "EndpointSliceList",
"metadata": {},
"items": [endpoint_slice],
},
}
)
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()

record = json.loads((tmp_path / "discovery" / "endpointslices.json").read_text())
assert "error" not in record, record
assert record["response"]["items"] == [endpoint_slice]
assert len(session.responses) == 5
assert all(response.released for response in session.responses)
28 changes: 28 additions & 0 deletions tests/utils/output_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -59,3 +61,29 @@ 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)


# Executions seen per test in this process. Retries (Datadog, pytest-rerunfailures)
# run again in the same process, including under xdist.
_output_dir_attempts: dict[str, int] = {}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def prepare_test_output_dir(log_dir: str, test_id: str) -> None:
"""Create an empty output directory for one execution of a test.

The first execution of ``test_id`` in this process removes stale output
left by earlier sessions. A repeat execution moves the previous attempt's
output to ``<log_dir>.attempt<N>`` instead of deleting it, so a failed
attempt's logs survive a passing retry and are uploaded with it.
"""
attempt = _output_dir_attempts.get(test_id, 0) + 1
_output_dir_attempts[test_id] = attempt
if attempt == 1:
Comment thread
glamr-agent marked this conversation as resolved.
Resolved
shutil.rmtree(log_dir, ignore_errors=True)
for stale in glob.glob(f"{glob.escape(log_dir)}.attempt*"):
shutil.rmtree(stale, ignore_errors=True)
elif os.path.exists(log_dir):
previous = f"{log_dir}.attempt{attempt - 1}"
shutil.rmtree(previous, ignore_errors=True)
os.rename(log_dir, previous)
os.makedirs(log_dir, exist_ok=True)
34 changes: 33 additions & 1 deletion tests/utils/test_output_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

import pytest

from tests.utils.output_paths import resolve_test_output_path
from tests.utils import output_paths
from tests.utils.output_paths import prepare_test_output_dir, resolve_test_output_path

pytestmark = [pytest.mark.pre_merge, pytest.mark.unit, pytest.mark.gpu_0]

Expand Down Expand Up @@ -46,3 +47,34 @@ def test_absolute_output_paths_are_unchanged(
path = absolute if as_path else str(absolute)

assert resolve_test_output_path(path) == str(absolute)


def test_repeat_execution_keeps_previous_attempt_output(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
monkeypatch.setattr(output_paths, "_output_dir_attempts", {})
log_dir = tmp_path / "test_deployment[sglang-agg_embed-normal]"
test_id = "tests/deploy/test_dgd.py::test_deployment[sglang-agg_embed-normal]"
log_dir.mkdir()
(log_dir / "stale.txt").write_text("earlier session")
stale_attempt = tmp_path / f"{log_dir.name}.attempt1"
stale_attempt.mkdir()

prepare_test_output_dir(str(log_dir), test_id)

assert list(log_dir.iterdir()) == []
assert not stale_attempt.exists()

(log_dir / "test.log.txt").write_text("first attempt")
prepare_test_output_dir(str(log_dir), test_id)

assert list(log_dir.iterdir()) == []
assert (stale_attempt / "test.log.txt").read_text() == "first attempt"

(log_dir / "test.log.txt").write_text("second attempt")
prepare_test_output_dir(str(log_dir), test_id)

assert (stale_attempt / "test.log.txt").read_text() == "first attempt"
second_attempt = tmp_path / f"{log_dir.name}.attempt2"
assert (second_attempt / "test.log.txt").read_text() == "second attempt"
assert list(log_dir.iterdir()) == []
Loading