litellm/tests/unit/integration_support/test_workers.py
devin-ai-integration[bot] 02feb67c20
test(integration): cut CircleCI proxy boot time with concurrent worker stacks and single-worker test proxies (#46037)
* test(integration): build worker stacks concurrently and record proxy boot phases

The controller built every xdist worker's database, Redis, upstream and gateway
proxy one after another before any test ran, about 95 s per extensions shard,
and since every multi-worker suite is now isolated the same serial wait hits
mcp, security and cost too. The stacks now start on a thread pool bounded by
the CPU count. Each stack reads its endpoints and results directory from an
explicit environment instead of a patched os.environ, every stack that started
is registered for cleanup, and a failure in one stops the others before the
error is raised

Owned proxy startup.json now records the wall-clock spawn time, the worker
count and when the Prisma CLI child ran, when the port started accepting and
when the first worker answered readiness, and exit.json records when the stop
started and ended, so the boot time can be split and overlapping gateway boots
can be seen in the artifacts

* test(integration): boot one uvicorn worker where a test does not assert cross-worker behaviour

A 2-worker owned proxy takes about twice as long to become ready as a 1-worker
one, because the uvicorn parent imports the app and each spawned worker imports
it again. The passthrough upstream error visibility cases, the single-request
S3 dedupe cases and the single-request spend log payload cases send one or two
requests and assert on the response, the proxy log and the spend row, none of
which depends on a second worker, so they now boot the default single worker

Cases that do rely on two workers keep them, the concurrent S3 burst through a
sink outage, previous_response_id replay, response cache hits, the concurrent
spend bursts and upstream stop and recovery

* test(observability): settle OTel excluded-services traces by a quiet period instead of a full window

_trace_spans slept through its whole 15 or 30 s window on every call even when
the trace had long stopped growing. It now polls and returns once the trace
has spans and has not gained one for five tenant export intervals, and the
module pins the tenant batch exporter's schedule delay to 1 s so that bound is
set by the test rather than by the SDK default. Absence checks still run only
after the trace stopped growing, and against a build that leaks postgres spans
to the tenant they still fail

These cases also boot one uvicorn worker now. None of them asserts anything
about a second worker

---------

Co-authored-by: Yuneng Jiang <yuneng@berri.ai>
2026-10-12 09:48:42 -07:00

133 lines
5.2 KiB
Python

import threading
from contextlib import ExitStack
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Final
import httpx
import pytest
from tests.integration._support.client import Gateway
from tests.integration._support.workers import (
GatewayProfile,
WorkerStack,
gateway_profile,
readiness_failure,
start_worker_stacks,
)
from tests.integration.run import worker_settings
HEALTHY: Final = {
"status": "healthy",
"cache_type": "redis",
"ping_response": True,
"set_cache_response": "success",
}
@dataclass(frozen=True, slots=True)
class Subscribers:
count: int
def pubsub_numsub(self, *channels: str) -> tuple[tuple[str, int], ...]:
return tuple((channel, self.count) for channel in channels)
@pytest.mark.parametrize("subscribers", (0, 1, 2))
def test_readiness_requires_a_subscriber_for_each_proxy(subscribers: int) -> None:
def respond(request: httpx.Request) -> httpx.Response:
if request.url.path == "/cache/ping":
assert request.headers["authorization"] == "Bearer owned-key"
return httpx.Response(200, json=HEALTHY)
return httpx.Response(200)
with httpx.Client(base_url="http://127.0.0.1:4000", transport=httpx.MockTransport(respond)) as client:
primary: Final = Gateway(client, "owned-key", "http://127.0.0.1:8190")
failure: Final = readiness_failure(client, primary.upstream_url, (primary, primary), Subscribers(subscribers))
assert failure == (None if subscribers == 2 else f"auth-cache subscribers {subscribers}/2")
@pytest.mark.parametrize(
("field", "value"),
(("status", "unhealthy"), ("cache_type", "local"), ("ping_response", False), ("set_cache_response", "failure")),
)
def test_readiness_rejects_a_proxy_without_working_shared_redis(field: str, value: str | bool) -> None:
def respond(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={**HEALTHY, field: value})
with httpx.Client(base_url="http://127.0.0.1:4000", transport=httpx.MockTransport(respond)) as client:
primary: Final = Gateway(client, "owned-key", "http://127.0.0.1:8190")
failure: Final = readiness_failure(client, primary.upstream_url, (primary,), Subscribers(1))
assert failure == "proxy 0 Redis read/write health"
@pytest.mark.parametrize(
("group", "peer", "cost_map"),
(
("management", True, False),
("mcp", True, False),
("cost", False, True),
("security", False, False),
("extensions", False, False),
),
)
def test_each_group_gets_the_worker_gateway_its_shared_proxy_used_to_provide(
group: str, peer: bool, cost_map: bool
) -> None:
assert gateway_profile(worker_settings(group, 4)) == GatewayProfile(
peer=peer, replica=False, cost_map=cost_map, coverage_file=None
)
def test_replica_runs_and_coverage_runs_reach_every_worker_gateway() -> None:
profile: Final = gateway_profile(
{
**worker_settings("management", 2),
"INTEGRATION_PROXY_READ_REPLICA_URL": "postgresql://reader@127.0.0.1/circle_test",
"INTEGRATION_COVERAGE_FILE": "/results/coverage/data",
}
)
assert profile == GatewayProfile(
peer=True, replica=True, cost_map=False, coverage_file=Path("/results/coverage/data")
)
def _stack(name: str, closed: threading.Event) -> WorkerStack:
resources: Final = ExitStack()
resources.callback(closed.set)
return WorkerStack(resources, MappingProxyType({"INTEGRATION_RESULTS_DIR": name}))
def test_worker_stacks_start_together_and_return_in_worker_order(tmp_path: Path) -> None:
directories: Final = tuple(tmp_path / f"gw{index}" for index in range(3))
closed: Final = MappingProxyType({directory: threading.Event() for directory in directories})
together: Final = threading.Barrier(len(directories), timeout=10)
def build(directory: Path) -> WorkerStack:
together.wait()
return _stack(directory.name, closed[directory])
with ExitStack() as resources:
environments: Final = start_worker_stacks(directories, build, resources, len(directories))
assert [environment["INTEGRATION_RESULTS_DIR"] for environment in environments] == ["gw0", "gw1", "gw2"]
assert not any(event.is_set() for event in closed.values())
assert all(event.is_set() for event in closed.values())
def test_a_failed_worker_stack_stops_every_sibling_that_started(tmp_path: Path) -> None:
directories: Final = tuple(tmp_path / f"gw{index}" for index in range(3))
closed: Final = MappingProxyType({directory: threading.Event() for directory in directories})
together: Final = threading.Barrier(len(directories), timeout=10)
def build(directory: Path) -> WorkerStack:
together.wait()
if directory.name == "gw1":
raise RuntimeError("gw1 gateway never became ready")
return _stack(directory.name, closed[directory])
with ExitStack() as resources:
with pytest.raises(RuntimeError, match="gw1 gateway never became ready"):
start_worker_stacks(directories, build, resources, len(directories))
assert closed[directories[0]].is_set()
assert closed[directories[2]].is_set()