Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test(integration): isolate every multi-worker integration suite by default (#46027)

devin-ai-integration[bot]e16d45629192
diff --git a/.circleci/scripts/run_integration.sh b/.circleci/scripts/run_integration.sh
index 0210c2dc6f7..b18526e084e 100644
--- a/.circleci/scripts/run_integration.sh
+++ b/.circleci/scripts/run_integration.sh
@@ -128,20 +128,14 @@ fi
sudo iptables -L integration_only -n -v -x > "$results/egress-guard.txt"
awk '$3 == "REJECT" && $1 > 0 { rejected=1 } END { exit !rejected }' "$results/egress-guard.txt"
-isolated_workers=false
if [ "$mode" = parity ]; then
export INTEGRATION_WORKERS=1
else
case "$suite" in
- management|accounting) export INTEGRATION_WORKERS=2; isolated_workers=true ;;
- providers|extensions) export INTEGRATION_WORKERS=4; isolated_workers=true ;;
+ management|accounting) export INTEGRATION_WORKERS=2 ;;
+ providers|extensions) export INTEGRATION_WORKERS=4 ;;
esac
fi
-if [ "$isolated_workers" = false ]; then
- setsid env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" INTEGRATION_RUN_ID="$integration_identity" \
- .venv/bin/python -m integration._support.upstream > "$results/upstream.log" 2>&1 &
- upstream_pid=$!
-fi
if [ "$suite" = cost ]; then
export INTEGRATION_WORKERS=8
fi
@@ -151,6 +145,15 @@ fi
if [ "$suite" = mcp ]; then
export INTEGRATION_WORKERS=4 INTEGRATION_COVERAGE=1
fi
+isolated_workers=false
+if [ "${INTEGRATION_WORKERS:-1}" -gt 1 ]; then
+ isolated_workers=true
+fi
+if [ "$isolated_workers" = false ]; then
+ setsid env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" INTEGRATION_RUN_ID="$integration_identity" \
+ .venv/bin/python -m integration._support.upstream > "$results/upstream.log" 2>&1 &
+ upstream_pid=$!
+fi
coverage_data="$PWD/$results/coverage/data"
proxy_command=(.venv/bin/python -m integration._support.proxy)
if [ "${INTEGRATION_COVERAGE:-0}" = 1 ]; then
@@ -191,9 +194,6 @@ start_proxy() {
> "$results/$log_name" 2>&1 &
launched_pid=$!
}
-if { [ "$suite" = management ] || [ "$suite" = mcp ]; } && [ "$isolated_workers" = true ]; then
- export INTEGRATION_PEER_URL=http://127.0.0.1:4001
-fi
if [ "$isolated_workers" = false ]; then
start_proxy 4000 proxy.log
proxy_pid="$launched_pid"
@@ -239,13 +239,24 @@ if [ "${CIRCLE_NODE_TOTAL:-1}" -gt 1 ]; then
shard_arguments=(--shard-files "$results/node-files.txt")
fi
+shared_services=()
+worker_coverage=()
+if [ "$isolated_workers" = false ]; then
+ shared_services=(
+ "REDIS_HOST=$REDIS_HOST" "REDIS_PORT=$REDIS_PORT"
+ "INTEGRATION_PROXY_URL=$INTEGRATION_PROXY_URL" "INTEGRATION_PEER_URL=$INTEGRATION_PEER_URL"
+ "INTEGRATION_UPSTREAM_URL=$INTEGRATION_UPSTREAM_URL" "INTEGRATION_MASTER_KEY=$INTEGRATION_MASTER_KEY"
+ )
+elif [ "${INTEGRATION_COVERAGE:-0}" = 1 ]; then
+ worker_coverage=("INTEGRATION_COVERAGE_FILE=$coverage_data")
+fi
+
env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \
INTEGRATION_RUN_ID="$integration_identity" \
- DATABASE_URL="$DATABASE_URL" REDIS_HOST="$REDIS_HOST" REDIS_PORT="$REDIS_PORT" \
- INTEGRATION_PROXY_URL="$INTEGRATION_PROXY_URL" INTEGRATION_PEER_URL="$INTEGRATION_PEER_URL" \
- INTEGRATION_UPSTREAM_URL="$INTEGRATION_UPSTREAM_URL" \
+ DATABASE_URL="$DATABASE_URL" \
+ "${shared_services[@]}" "${worker_coverage[@]}" \
INTEGRATION_WORKERS="${INTEGRATION_WORKERS:-1}" \
- INTEGRATION_MASTER_KEY="$INTEGRATION_MASTER_KEY" LITELLM_MODE=PRODUCTION \
+ LITELLM_MODE=PRODUCTION \
LITELLM_LICENSE="${LITELLM_LICENSE:-}" \
INTEGRATION_SEED="$INTEGRATION_SEED" \
INTEGRATION_ORDER_SEED="$INTEGRATION_ORDER_SEED" \
diff --git a/tests/integration/README.md b/tests/integration/README.md
index 8f818225505..b65c4f36219 100644
--- a/tests/integration/README.md
+++ b/tests/integration/README.md
@@ -8,9 +8,9 @@ The Redis cluster IAM contracts in `sdk/test_redis_cluster_iam_auth.py` start th
The `cost` group is driven by the `CostTrackingTestCase` literals under `cost_calculation/cases/<provider>.py` (gathered by `cost_calculation/catalog.py`), with the scripted cost map in `cost_calculation/cost_map.py`. Each case has a name, contract ID, cost-map model, optional deployment overrides, request body, tagged response and exact or recount expectations. Request bodies use `$MODEL` for the registered proxy model, while responses use `$REQUEST_ID` for the per-run scenario ID. To add a case, add a cost-map entry when the model is new, add the request body and exact provider response data, and add hand-computed expected values. The upstream serves each stored response for any path under `/<scenario_id>`, while the test-owned cost map is served over loopback through `LITELLM_MODEL_COST_MAP_URL`
-Use `tests/integration/run.py management`, `accounting`, `database`, `providers`, `extensions`, `mcp`, `sdk` or `cost` to run a selected group. The group to directory mapping is the `GROUPS` literal at the top of `run.py`; a new directory needs a `GROUPS` entry and an `OWNED_DIRECTORIES` entry in `_support/manifest.py`. Set `INTEGRATION_WORKERS` above 1 to run a group under pytest-xdist. Management, accounting, providers and extensions give each worker a private database, Redis, upstream, fake provider and proxy, with a peer and read-only database role where required. The pytest controller owns these services and closes them after worker failures. Their cases use pytest-xdist load groups inside the files selected by CircleCI timing splits. Module and class fixtures are grouped automatically, so authors do not need scheduling markers. Function fixtures remain independently schedulable. Tests that own an independent mutable sink for every case should use function fixtures, so a shared module fixture does not serialize them or share pending observations. Nested harness probes discard the parent run's shard, worker and result settings, then supply their own selections. MCP keeps its existing resource ownership and explicit load groups. Automatic group suffixes are removed from JUnit and execution records to preserve case identities. Owned proxy helpers wait for a healthy response from every configured, live worker before yielding. Serial runs keep the supplied deployment, including routing parity runs. Set `INTEGRATION_PROXY_URL`, `INTEGRATION_UPSTREAM_URL`, `INTEGRATION_MASTER_KEY` and `DATABASE_URL` to an isolated test deployment. When that deployment runs more than one proxy worker, set `INTEGRATION_PROXY_WORKERS` to the count so a test that writes a model and then calls it waits out the config reload interval, the only cross-worker convergence bound the wire exposes. The runner selects the new domain directories explicitly; the legacy OCI and sandbox selections remain separate
+Use `tests/integration/run.py management`, `accounting`, `database`, `providers`, `extensions`, `mcp`, `sdk` or `cost` to run a selected group. The group to directory mapping is the `GROUPS` literal at the top of `run.py`; a new directory needs a `GROUPS` entry and an `OWNED_DIRECTORIES` entry in `_support/manifest.py`. Set `INTEGRATION_WORKERS` above 1 to run a group under pytest-xdist. Every group run by more than one worker gives each worker a private database, Redis, scripted upstream process, fake provider and proxy, with a peer and read-only database role where required. There is no opt-in list and no shared proxy, upstream, database or Redis in that mode: `run_integration.sh` does not start them and does not hand their addresses to the run, so a test can only reach its own worker's services. The pytest controller owns these services and closes them after worker failures. Their cases use pytest-xdist load groups inside the files selected by CircleCI timing splits. Module and class fixtures are grouped automatically, so authors do not need scheduling markers. Function fixtures remain independently schedulable. Tests that own an independent mutable sink for every case should use function fixtures, so a shared module fixture does not serialize them or share pending observations. Nested harness probes discard the parent run's shard, worker and result settings, then supply their own selections. MCP keeps its explicit load groups. Automatic group suffixes are removed from JUnit and execution records to preserve case identities. Owned proxy helpers wait for a healthy response from every configured, live worker before yielding. Serial runs keep the supplied deployment, including routing parity runs. Set `INTEGRATION_PROXY_URL`, `INTEGRATION_UPSTREAM_URL`, `INTEGRATION_MASTER_KEY` and `DATABASE_URL` to an isolated test deployment. When that deployment runs more than one proxy worker, set `INTEGRATION_PROXY_WORKERS` to the count so a test that writes a model and then calls it waits out the config reload interval, the only cross-worker convergence bound the wire exposes. The runner selects the new domain directories explicitly; the legacy OCI and sandbox selections remain separate
-Management also requires `INTEGRATION_PEER_URL`, `REDIS_HOST` and `REDIS_PORT`. CircleCI starts two directly addressed proxy processes sharing only that job's stores. The test-only CLI wrapper supplies enterprise route entitlement, following the existing behavior suite's convention. It does not qualify license validation; run it with one worker and no reload
+Management and MCP also require `INTEGRATION_PEER_URL`, `REDIS_HOST` and `REDIS_PORT`. Under several workers each worker gets a second directly addressed proxy sharing only that worker's stores, and a single-worker run uses the two proxies `run_integration.sh` starts. The test-only CLI wrapper supplies enterprise route entitlement, following the existing behavior suite's convention. It does not qualify license validation; run it with one worker and no reload
The generated lifecycle models use 20 examples, eight steps, generation and shrinking, with isolated resources per example. HTTP operation caps include generation and shrinking and exempt cleanup. Local qualification defaults to seed 4106601 and canonical order; CircleCI derives exploration and ordering seeds from the checked-out revision and workflow ID. The ordering seed shuffles files, scoped fixture configurations and cases within each configuration. Ordering keeps shared module and class configurations together where their dependencies permit it. Dependent fixtures with their own module parameters can still rebuild an outer configuration, with every case retained
@@ -54,9 +54,9 @@ The sdk shard exercises the SDK's own HTTP clients against local protocol peers
The extensions shard uses the built-in generic callback and guardrail transports. It checks callback correlation and credential exclusion, guardrail rewriting and denial, retained OpenAI consumers and A2A wire versions. CircleCI runs it on eight xlarge nodes using its file timing splitter. Each node runs its assigned files with four pytest workers, each owning its database, Redis, upstream and proxy. The dependent coverage job verifies all eight execution records against the candidate case inventory. Tests must not assume a particular set of sibling files
-The security shard uses four pytest workers on an xlarge machine, each with a private database and Redis. Route sweeps use a new HTTP client for every call and share only the TLS verification context, so authentication and response cookies cannot cross callers. The canary rig supplies owned OpenAI and Anthropic endpoints and synthetic credentials and rejects attempted external egress
+The security shard uses four pytest workers on an xlarge machine, each with its own isolated services like every other multi-worker group. Route sweeps use a new HTTP client for every call and share only the TLS verification context, so authentication and response cookies cannot cross callers. The canary rig supplies owned OpenAI and Anthropic endpoints and synthetic credentials and rejects attempted external egress
-The two mcp nodes own separate services and use the same case census as providers and extensions. Their coverage data is combined into one MCP report after both nodes finish. Each node runs the MCP gateway against SDK peers owned by each test (`_support/mcp.py`): streamable HTTP, SSE and stdio peers, an OpenAPI-spec app, and an OAuth 2.1 authorization-server double. Every peer records the requests it receives so a test can assert what reached the peer, not only what the proxy answered. The shard runs with `INTEGRATION_WORKERS` set and with `INTEGRATION_COVERAGE=1`, which starts the proxy under `coverage run --parallel-mode` limited to the MCP modules and stores `coverage.txt` plus an HTML report with the job artifacts. A test that fails because the product is wrong is skipped with `pytest.skip("BUG: <symptom>")` so the skip list in `execution.json` is the open MCP bug list
+The two mcp nodes own separate services and use the same case census as providers and extensions. Their coverage data is combined into one MCP report after both nodes finish. Each node runs the MCP gateway against SDK peers owned by each test (`_support/mcp.py`): streamable HTTP, SSE and stdio peers, an OpenAPI-spec app, and an OAuth 2.1 authorization-server double. Every peer records the requests it receives so a test can assert what reached the peer, not only what the proxy answered. The shard runs with `INTEGRATION_WORKERS` set and with `INTEGRATION_COVERAGE=1`, which starts every worker's proxy and peer under `coverage run --parallel-mode` limited to the MCP modules and stores `coverage.txt` plus an HTML report with the job artifacts. `mcp_coverage.toml` measures lines through `sys.monitoring`, because the CPython 3.12 trace function that branch measurement needs made a covered proxy take about four times as long to become ready. A test that fails because the product is wrong is skipped with `pytest.skip("BUG: <symptom>")` so the skip list in `execution.json` is the open MCP bug list
Browser contracts live in `tests/e2e/ui/tests/integrationCritical` and run only through `tests/e2e/ui/integration.config.ts`. The expected browser results are listed in `expected.json` in that directory and checked by `.circleci/scripts/verify_integration_browser.py`. The CircleCI browser shard builds the checked-out dashboard, starts the owned proxy with that build, and verifies one exact browser result without retries or skips. The default Playwright selection excludes this directory. The focused project flow asserts the submitted create and clear values, fresh SQL state and actual blocked/restored serving while preserving model restrictions
diff --git a/tests/integration/_support/database.py b/tests/integration/_support/database.py
index 3ad4f205e12..ef7d2ba68e1 100644
--- a/tests/integration/_support/database.py
+++ b/tests/integration/_support/database.py
@@ -27,8 +27,8 @@ def write_rows(query: LiteralString, parameters: tuple[str, ...], *, database_ur
@contextmanager
-def scratch_database() -> Generator[str]:
- name: Final = f"integration_{uuid.uuid4().hex}"
+def scratch_database(prefix: str = "integration") -> Generator[str]:
+ name: Final = f"{prefix}_{uuid.uuid4().hex}"
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as admin:
admin.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(name)))
try:
diff --git a/tests/integration/_support/process.py b/tests/integration/_support/process.py
index a67117f00ff..597ae2370be 100644
--- a/tests/integration/_support/process.py
+++ b/tests/integration/_support/process.py
@@ -34,6 +34,7 @@ DB_PUSH: Final = ("--use_prisma_db_push",)
MIGRATE_DEPLOY: Final = ()
LEGACY_MIGRATE_DEPLOY: Final = ("--use_legacy_migration_resolver",)
CONFIGURATION: Final = TypeAdapter(dict[str, object])
+MCP_COVERAGE_CONFIG: Final = Path(__file__).resolve().parents[1] / "mcp_coverage.toml"
def proxy_database_environment() -> Mapping[str, str]:
@@ -97,6 +98,7 @@ def owned_proxy(
remove_environment: tuple[str, ...] = (),
workers: int = 1,
database_setup: tuple[str, ...] = DB_PUSH,
+ coverage_file: Path | None = None,
) -> Iterator[Gateway]:
with owned_proxy_process(
gateway,
@@ -106,6 +108,7 @@ def owned_proxy(
remove_environment=remove_environment,
workers=workers,
database_setup=database_setup,
+ coverage_file=coverage_file,
) as owned:
yield owned.gateway
@@ -396,14 +399,18 @@ def owned_proxy_process(
workers: int = 1,
database_setup: tuple[str, ...] = DB_PUSH,
extra_arguments: tuple[str, ...] = (),
+ coverage_file: Path | None = None,
) -> Iterator[OwnedProxy]:
root: Final = _proxy_root()
- environment: Final = _proxy_environment(gateway, overrides, remove_environment)
+ environment: Final = _proxy_environment(
+ gateway, {**overrides, **({"COVERAGE_FILE": str(coverage_file)} if coverage_file else {})}, remove_environment
+ )
output: Final = Path(os.environ.get("INTEGRATION_RESULTS_DIR", str(directory)))
output.mkdir(parents=True, exist_ok=True)
command: Final = (
sys.executable,
"-m",
+ *(("coverage", "run", f"--rcfile={MCP_COVERAGE_CONFIG}", "-m") if coverage_file else ()),
"integration._support.proxy",
"--config",
str(worker_configuration(config or root / "tests/integration/proxy_config.yaml", directory)),
@@ -620,9 +627,9 @@ def _harness_root() -> Path:
@contextmanager
-def owned_upstream(directory: Path, *, tls: bool = False) -> Generator[UpstreamSlot]:
+def owned_upstream(directory: Path, *, tls: bool = False, port: int | None = None) -> Generator[UpstreamSlot]:
certificate: Final = self_signed_certificate(directory) if tls else None
- slot: Final = UpstreamSlot(directory, _free_port(), _harness_root(), certificate)
+ slot: Final = UpstreamSlot(directory, port or _free_port(), _harness_root(), certificate)
try:
slot.start()
yield slot
diff --git a/tests/integration/_support/routing.py b/tests/integration/_support/routing.py
index 14f4741367a..1f8f5626031 100644
--- a/tests/integration/_support/routing.py
+++ b/tests/integration/_support/routing.py
@@ -21,6 +21,7 @@ WRITER_ROLE: Final = "litellm_writer"
READER_ROLE: Final = "litellm_reader"
ROLES: Final = (READER_ROLE, WRITER_ROLE)
DATABASE_NAME: Final = "circle_test"
+WORKER_DATABASE_PREFIX: Final = "integration_worker"
OBSERVED_FILE: Final = "routing-observed.json"
DIFF_FILE: Final = "routing-diff.txt"
EITHER_ROLE_FILE: Final = Path(__file__).resolve().parents[1] / "routing" / "either_role.json"
@@ -216,10 +217,10 @@ def snapshot(connection: psycopg.Connection[object]) -> Mapping[tuple[str, str],
SELECT r.rolname, s.query, s.calls
FROM pg_stat_statements s
JOIN pg_roles r ON r.oid = s.userid
- WHERE s.dbid = (SELECT oid FROM pg_database WHERE datname = %s)
+ WHERE s.dbid IN (SELECT oid FROM pg_database WHERE datname = %s OR starts_with(datname, %s))
AND r.rolname = ANY(%s)
""",
- (DATABASE_NAME, list(ROLES)),
+ (DATABASE_NAME, f"{WORKER_DATABASE_PREFIX}_", list(ROLES)),
).fetchall()
return MappingProxyType(
{
diff --git a/tests/integration/_support/upstream.py b/tests/integration/_support/upstream.py
index 6b36d56a757..8c3c88990e1 100644
--- a/tests/integration/_support/upstream.py
+++ b/tests/integration/_support/upstream.py
@@ -753,6 +753,7 @@ def main() -> None:
port=cast(int, arguments.port),
access_log=False,
timeout_keep_alive=125,
+ timeout_graceful_shutdown=5,
ssl_certfile=cast(str | None, arguments.ssl_certfile),
ssl_keyfile=cast(str | None, arguments.ssl_keyfile),
)
diff --git a/tests/integration/_support/workers.py b/tests/integration/_support/workers.py
index 2502e62477e..843f5dec4ac 100644
--- a/tests/integration/_support/workers.py
+++ b/tests/integration/_support/workers.py
@@ -6,6 +6,7 @@ import time
import uuid
from collections.abc import Iterator, Mapping
from contextlib import contextmanager, nullcontext
+from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Final, Protocol
@@ -22,6 +23,7 @@ from redis.exceptions import TimeoutError as RedisTimeoutError
from tests.integration._support.client import Gateway
from tests.integration._support.database import scratch_database
from tests.integration._support.redis_process import owned_redis
+from tests.integration._support.routing import WORKER_DATABASE_PREFIX
READINESS_OBJECT: Final = TypeAdapter(dict[str, object])
SUBSCRIBER_COUNTS: Final = TypeAdapter(tuple[tuple[str, int], ...])
@@ -116,11 +118,43 @@ def _replica_urls(database: str) -> Mapping[str, str]:
)
+@dataclass(frozen=True, slots=True)
+class GatewayProfile:
+ peer: bool
+ replica: bool
+ cost_map: bool
+ coverage_file: Path | None
+
+
+def gateway_profile(environment: Mapping[str, str]) -> GatewayProfile:
+ coverage: Final = environment.get("INTEGRATION_COVERAGE_FILE", "")
+ return GatewayProfile(
+ peer=environment.get("INTEGRATION_WORKER_PEER") == "1",
+ replica=bool(environment.get("INTEGRATION_PROXY_READ_REPLICA_URL")),
+ cost_map=environment.get("INTEGRATION_WORKER_COST_MAP") == "1",
+ coverage_file=Path(coverage) if coverage else None,
+ )
+
+
+def cost_map_environment(upstream: str) -> Mapping[str, str]:
+ return MappingProxyType(
+ {
+ "LITELLM_MODEL_COST_MAP_URL": f"{upstream}/_cost_map",
+ "MODEL_COST_MAP_MIN_MODEL_COUNT": "1",
+ "MODEL_COST_MAP_MAX_SHRINK_RATIO": "0",
+ "GEMINI_API_BASE": upstream,
+ "ANTHROPIC_API_BASE": upstream,
+ "GEMINI_API_KEY": "sk-scripted-provider",
+ "ANTHROPIC_API_KEY": "sk-scripted-provider",
+ }
+ )
+
+
@contextmanager
def worker_services(directory: Path, *, replica: bool = False) -> Iterator[Mapping[str, str]]:
directory.mkdir(parents=True, exist_ok=True)
with (
- scratch_database() as database,
+ scratch_database(WORKER_DATABASE_PREFIX) as database,
owned_redis(directory) as cache,
):
yield MappingProxyType(
@@ -136,25 +170,37 @@ def worker_services(directory: Path, *, replica: bool = False) -> Iterator[Mappi
@contextmanager
-def worker_gateway(directory: Path, *, peer: bool, replica: bool) -> Iterator[Mapping[str, str]]:
- from tests.integration._support.asgi import asgi_server
- from tests.integration._support.process import owned_proxy
- from tests.integration._support.upstream import Provider
+def worker_gateway(directory: Path, profile: GatewayProfile) -> Iterator[Mapping[str, str]]:
+ from tests.integration._support.process import owned_proxy, owned_upstream
- port: Final = urlsplit(os.environ["INTEGRATION_UPSTREAM_URL"]).port
+ upstream: Final = os.environ["INTEGRATION_UPSTREAM_URL"]
+ port: Final = urlsplit(upstream).port
assert port is not None
key: Final = f"sk-{uuid.uuid4().hex}"
- with worker_services(directory, replica=replica) as services:
+ removed: Final = ("LITELLM_LOCAL_MODEL_COST_MAP",) if profile.cost_map else ()
+ with worker_services(directory, replica=profile.replica) as services:
overrides: Final = {
**services,
"DATABASE_URL": services["INTEGRATION_PROXY_DATABASE_URL"],
- **({"DATABASE_URL_READ_REPLICA": services["INTEGRATION_PROXY_READ_REPLICA_URL"]} if replica else {}),
+ **(
+ {"DATABASE_URL_READ_REPLICA": services["INTEGRATION_PROXY_READ_REPLICA_URL"]} if profile.replica else {}
+ ),
+ "LITELLM_ENABLE_MCP_STDIO": "true",
+ **(cost_map_environment(upstream) if profile.cost_map else {}),
}
with (
- asgi_server(Provider().app(), port=port, keepalive_seconds=125) as upstream,
+ owned_upstream(directory, port=port),
httpx.Client(base_url="http://127.0.0.1:1", trust_env=False) as client,
- owned_proxy(Gateway(client, key, upstream), directory, overrides) as primary,
- owned_proxy(primary, directory, overrides) if peer else nullcontext(None) as secondary,
+ owned_proxy(
+ Gateway(client, key, upstream),
+ directory,
+ overrides,
+ remove_environment=removed,
+ coverage_file=profile.coverage_file,
+ ) as primary,
+ owned_proxy(primary, directory, overrides, remove_environment=removed, coverage_file=profile.coverage_file)
+ if profile.peer
+ else nullcontext(None) as secondary,
):
with Redis(host=services["REDIS_HOST"], port=int(services["REDIS_PORT"]), socket_timeout=2) as cache:
wait_for_services(upstream, (primary, secondary) if secondary is not None else (primary,), cache)
diff --git a/tests/integration/compatibility/test_integration_worker_cleanup.py b/tests/integration/compatibility/test_integration_worker_cleanup.py
index a3d849ffe98..a95927dee5e 100644
--- a/tests/integration/compatibility/test_integration_worker_cleanup.py
+++ b/tests/integration/compatibility/test_integration_worker_cleanup.py
@@ -65,7 +65,9 @@ def test_worker_crash_fails_the_run_and_releases_its_database_and_processes(tmp_
"PYTHONPATH": f"{root}:{root / 'tests'}:{root / 'tests' / 'e2e'}",
"PYTEST_ADDOPTS": "",
"INTEGRATION_WORKER_ISOLATION": "1",
- "INTEGRATION_PEER_URL": "",
+ "INTEGRATION_WORKER_PEER": "",
+ "INTEGRATION_WORKER_COST_MAP": "",
+ "INTEGRATION_COVERAGE_FILE": "",
"INTEGRATION_PROXY_READ_REPLICA_URL": "",
"INTEGRATION_RESULTS_DIR": str(tmp_path / "results"),
"WORKER_CRASH_RECORD": str(record),
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
index 047347ae962..8bbf4e71842 100644
--- a/tests/integration/conftest.py
+++ b/tests/integration/conftest.py
@@ -24,7 +24,7 @@ from tests.integration._support.manifest import OWNED_DIRECTORIES
from tests.integration._support.ordering import collected_case, fixture_groups, scheduling_groups
from tests.integration._support.provider import SharedProvider, shared_provider
from tests.integration._support.routing import RoutingPlugin
-from tests.integration._support.workers import worker_endpoints, worker_gateway
+from tests.integration._support.workers import gateway_profile, worker_endpoints, worker_gateway
from tests.integration.run import GITHUB_FILES
if TYPE_CHECKING:
@@ -84,8 +84,7 @@ def pytest_xdist_setupnodes(config: pytest.Config, specs: Sequence[XSpec]) -> No
resources: Final = ExitStack()
config.add_cleanup(resources.close)
destination: Final = Path(os.environ["INTEGRATION_RESULTS_DIR"])
- peer_needed: Final = bool(os.environ.get("INTEGRATION_PEER_URL"))
- replica_needed: Final = bool(os.environ.get("INTEGRATION_PROXY_READ_REPLICA_URL"))
+ profile: Final = gateway_profile(os.environ)
for index, spec in enumerate(specs):
results: Final = destination / f"gw{index}"
endpoints: Final = worker_endpoints()
@@ -93,9 +92,7 @@ def pytest_xdist_setupnodes(config: pytest.Config, specs: Sequence[XSpec]) -> No
for name, value in endpoints.items():
environment.setenv(name, value)
environment.setenv("INTEGRATION_RESULTS_DIR", str(results))
- services: Final = resources.enter_context(
- worker_gateway(results / "runtime", peer=peer_needed, replica=replica_needed)
- )
+ services: Final = resources.enter_context(worker_gateway(results / "runtime", profile))
spec.env = {
**STRING_ENVIRONMENT.validate_python(spec.env),
**endpoints,
diff --git a/tests/integration/database/test_harness_lifecycle.py b/tests/integration/database/test_harness_lifecycle.py
index bee5261ea0e..6993342f2e5 100644
--- a/tests/integration/database/test_harness_lifecycle.py
+++ b/tests/integration/database/test_harness_lifecycle.py
@@ -54,6 +54,17 @@ class ExitRecord(TypedDict):
Relay = DatabaseRelay | DroppedConnectionRelay | HeldStatementRelay
RelayFactory = Callable[[str, bytes], AbstractContextManager[tuple[Relay, str]]]
STARTED_WORKER: Final = re.compile(r"Started server process \[(\d+)\]")
+NESTED_RUN_SECONDS: Final = 60.0
+WORKER_STACK_BOOT_SECONDS: Final = 30.0
+OUTER_TEST_SLACK_SECONDS: Final = 30.0
+
+
+def _nested_run_seconds(workers: int) -> float:
+ return NESTED_RUN_SECONDS + (workers * WORKER_STACK_BOOT_SECONDS if workers > 1 else 0.0)
+
+
+def _nested_run(*values: object, workers: int) -> object:
+ return pytest.param(*values, marks=pytest.mark.timeout(_nested_run_seconds(workers) + OUTER_TEST_SLACK_SECONDS))
def _nested_pytest_environment(environment: Mapping[str, str]) -> dict[str, str]:
@@ -62,6 +73,7 @@ def _nested_pytest_environment(environment: Mapping[str, str]) -> dict[str, str]
"INTEGRATION_RESULTS_DIR",
"INTEGRATION_ROUTING",
"INTEGRATION_WORKER_ISOLATION",
+ "INTEGRATION_COVERAGE_FILE",
"INTEGRATION_CASE_SHARDS",
"INTEGRATION_CASE_SHARD_INDEX",
"CIRCLE_NODE_TOTAL",
@@ -451,7 +463,10 @@ def test_native_file_selection_reuses_fixtures_and_qualifies_an_empty_shard(
)
[email protected](("workers", "seed"), ((1, 1848224111), (2, 0), (2, 984872314)))
+ ("workers", "seed"),
+ tuple(_nested_run(workers, seed, workers=workers) for workers, seed in ((1, 1848224111), (2, 0), (2, 984872314))),
+)
@pytest.mark.parametrize("class_parameters", (False, True))
def test_mixed_fixture_scopes_reuse_outer_and_inner_configurations(
tmp_path: Path, workers: int, seed: int, class_parameters: bool
@@ -511,7 +526,7 @@ def test_mixed_fixture_scopes_reuse_outer_and_inner_configurations(
env=_nested_pytest_environment(os.environ),
capture_output=True,
text=True,
- timeout=60,
+ timeout=_nested_run_seconds(workers),
check=False,
)
assert result.returncode == 0, result.stdout + result.stderr
@@ -536,16 +551,21 @@ def test_mixed_fixture_scopes_reuse_outer_and_inner_configurations(
assert len(executed) == len(frozenset(executed)) == expected_passes
[email protected]("workers", (1, 2))
[email protected]("workers", tuple(_nested_run(workers, workers=workers) for workers in (1, 2)))
def test_direct_and_dependent_consumers_reuse_the_same_module_parameter(tmp_path: Path, workers: int) -> None:
source: Final = Path(__file__).resolve().parents[3]
root: Final = tmp_path / "probe-root"
for relative in (
"pyproject.toml",
"tests/__init__.py",
+ "tests/_fake_openai_endpoint_server.py",
"tests/integration/__init__.py",
"tests/integration/conftest.py",
"tests/integration/run.py",
+ "tests/integration/proxy_config.yaml",
+ "tests/integration/mcp_coverage.toml",
+ "tests/integration/cost_calculation/cost_map.py",
+ "tests/integration/cost_calculation/cost_tracking_case.py",
):
destination: Final = root / relative
destination.parent.mkdir(parents=True, exist_ok=True)
@@ -609,7 +629,7 @@ def test_direct_and_dependent_consumers_reuse_the_same_module_parameter(tmp_path
),
capture_output=True,
text=True,
- timeout=60,
+ timeout=_nested_run_seconds(workers),
check=False,
)
assert result.returncode == 0, result.stdout + result.stderr
diff --git a/tests/integration/mcp_coverage.toml b/tests/integration/mcp_coverage.toml
index 2357269b59f..daa782eade2 100644
--- a/tests/integration/mcp_coverage.toml
+++ b/tests/integration/mcp_coverage.toml
@@ -1,5 +1,6 @@
[tool.coverage.run]
-branch = true
+branch = false
+core = "sysmon"
parallel = true
relative_files = true
include = [
diff --git a/tests/integration/run.py b/tests/integration/run.py
index 1f9a64bd1ea..6dcfe3900d7 100644
--- a/tests/integration/run.py
+++ b/tests/integration/run.py
@@ -5,6 +5,7 @@ import json
import os
import subprocess
import sys
+from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
@@ -37,6 +38,10 @@ GITHUB_FILES: Final = frozenset(
)
+PEER_GROUPS: Final = frozenset({"management", "mcp"})
+COST_MAP_GROUPS: Final = frozenset({"cost"})
+
+
@dataclass(frozen=True, slots=True)
class Selection:
nodes: tuple[str, ...]
@@ -60,6 +65,18 @@ def uncollected(nodes: tuple[str, ...], collected: frozenset[str]) -> tuple[str,
return tuple(node for node in nodes if file_of(node) not in collected_files)
+def worker_settings(group: str, workers: int) -> Mapping[str, str]:
+ if workers < 2:
+ return MappingProxyType({})
+ return MappingProxyType(
+ {
+ "INTEGRATION_WORKER_ISOLATION": "1",
+ "INTEGRATION_WORKER_PEER": "1" if group in PEER_GROUPS else "",
+ "INTEGRATION_WORKER_COST_MAP": "1" if group in COST_MAP_GROUPS else "",
+ }
+ )
+
+
def main() -> int:
parser: Final = argparse.ArgumentParser()
parser.add_argument("group", choices=tuple(GROUPS))
@@ -97,11 +114,7 @@ def main() -> int:
"LITELLM_LOCAL_MODEL_COST_MAP": "True",
"LITELLM_MODE": "PRODUCTION",
"PYTHON_DOTENV_DISABLED": "1",
- **(
- {"INTEGRATION_WORKER_ISOLATION": "1"}
- if options.workers > 1 and options.group in {"management", "accounting", "providers", "extensions"}
- else {}
- ),
+ **worker_settings(options.group, options.workers),
}
result: Final = subprocess.call(
[
diff --git a/tests/integration/security/conftest.py b/tests/integration/security/conftest.py
deleted file mode 100644
index b9f33c71f63..00000000000
--- a/tests/integration/security/conftest.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from __future__ import annotations
-
-import os
-from collections.abc import Iterator
-from pathlib import Path
-from typing import Final
-
-import pytest
-
-from tests.integration._support.workers import worker_services
-
-
[email protected](scope="session", autouse=True)
-def isolated_security_worker(worker_id: str, tmp_path_factory: pytest.TempPathFactory) -> Iterator[None]:
- if worker_id == "master":
- yield
- return
- directory: Final = tmp_path_factory.mktemp("security-worker")
- results: Final = Path(os.environ.get("INTEGRATION_RESULTS_DIR", str(directory))) / worker_id
- results.mkdir(parents=True, exist_ok=True)
- with pytest.MonkeyPatch.context() as environment:
- environment.setenv("INTEGRATION_RESULTS_DIR", str(results))
- with worker_services(directory) as services:
- for name, value in services.items():
- environment.setenv(name, value)
- yield
diff --git a/tests/unit/integration_support/test_workers.py b/tests/unit/integration_support/test_workers.py
index 457b953e481..68c43335e32 100644
--- a/tests/unit/integration_support/test_workers.py
+++ b/tests/unit/integration_support/test_workers.py
@@ -1,11 +1,13 @@
from dataclasses import dataclass
+from pathlib import Path
from typing import Final
import httpx
import pytest
from tests.integration._support.client import Gateway
-from tests.integration._support.workers import readiness_failure
+from tests.integration._support.workers import GatewayProfile, gateway_profile, readiness_failure
+from tests.integration.run import worker_settings
HEALTHY: Final = {
"status": "healthy",
@@ -49,3 +51,34 @@ def test_readiness_rejects_a_proxy_without_working_shared_redis(field: str, valu
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"
+
+
+ ("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://[email protected]/circle_test",
+ "INTEGRATION_COVERAGE_FILE": "/results/coverage/data",
+ }
+ )
+ assert profile == GatewayProfile(
+ peer=True, replica=True, cost_map=False, coverage_file=Path("/results/coverage/data")
+ )
diff --git a/tests/unit/test_integration_run.py b/tests/unit/test_integration_run.py
index 36612525572..4a8551e07a4 100644
--- a/tests/unit/test_integration_run.py
+++ b/tests/unit/test_integration_run.py
@@ -1,6 +1,8 @@
from typing import Final
-from tests.integration.run import select, uncollected
+import pytest
+
+from tests.integration.run import GROUPS, select, uncollected, worker_settings
_GROUP: Final = (
"tests/integration/cost_calculation/test_cost_tracking.py",
@@ -34,3 +36,13 @@ def test_a_node_id_whose_file_collected_tests_is_not_empty() -> None:
def test_a_selected_file_that_collected_nothing_is_reported() -> None:
assert uncollected(_GROUP, frozenset({_CELL})) == ("tests/integration/cost_calculation/test_rollups.py",)
+
+
[email protected]("group", tuple(GROUPS))
+def test_every_group_run_by_several_workers_gives_each_worker_its_own_stack(group: str) -> None:
+ assert worker_settings(group, 2)["INTEGRATION_WORKER_ISOLATION"] == "1"
+
+
[email protected]("group", tuple(GROUPS))
+def test_a_single_worker_run_keeps_the_supplied_deployment(group: str) -> None:
+ assert worker_settings(group, 1) == {}