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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test(integration): stop GET /__observations from draining the upstream log (#47256)
yuneng-jiang44d99475a559
diff --git a/tests/integration/README.md b/tests/integration/README.mdindex 496c88050ee..c32fda2f944 100644--- a/tests/integration/README.md+++ b/tests/integration/README.md@@ -34,7 +34,7 @@ The CircleCI workflow starts its own database and Redis, restricts test-phase egThere is no hand-maintained list of test cases. A positional argument is a file of the group or a pytest node id inside one (`path::test[param]`), so one cell of a parametrized file can run alone. The runner fails only when pytest fails, when collection errors, or when a selected file collects zero tests. Older tests still carry `@pytest.mark.covers(...)` decorators; the marker stays registered so they collect, but the IDs are not checked against anything and new tests should not use it. The GitHub Actions coverage census reads the `GROUPS` literal in `run.py` and treats every `tests/integration/<directory>/test_*.py` file in a scheduled group as owned by CircleCI-Provider sentinels currently use the controlled server, not live recordings. The provider shard also runs the existing strict replay controls for changed requests, exhausted interactions, leftover interactions and no provider connection. Future recorded scenarios must use that replay-only implementation; missing recordings cannot fall back to a real provider. The observation endpoint is destructive and the current selection runs serially against one owned upstream+Provider sentinels currently use the controlled server, not live recordings. The provider shard also runs the existing strict replay controls for changed requests, exhausted interactions, leftover interactions and no provider connection. Future recorded scenarios must use that replay-only implementation; missing recordings cannot fall back to a real provider. `GET /__observations` returns every request the upstream recorded since the last `DELETE /__observations`, and reading it never clears it. An autouse fixture resets it before each test, so a test that needs a clean slate between phases sends the DELETE itself. A check that a request never reached the upstream asserts on the same read that shows a request sent after it did reach the upstream, so the absence cannot pass on an empty or reset logTranslation tests in `translation/` compare exact provider requests and LiteLLM responses against a shared fake provider; `translation/README.md` has their rulesdiff --git a/tests/integration/_support/upstream.py b/tests/integration/_support/upstream.pyindex 186bc345fab..85da60a37ad 100644--- a/tests/integration/_support/upstream.py+++ b/tests/integration/_support/upstream.py@@ -11,7 +11,6 @@ import zlibfrom collections import dequefrom collections.abc import AsyncIterator, Callable, Iterator, Mappingfrom dataclasses import dataclass, field-from queue import SimpleQueuefrom types import MappingProxyTypefrom typing import Final, cast@@ -184,9 +183,23 @@ class ScenarioStore:return self._scenarios.get(scenario_id)+class ObservationLog:+ def __init__(self) -> None:+ self._entries: list[Observation] = []++ def put(self, observation: Observation) -> None:+ self._entries.append(observation)++ def snapshot(self) -> tuple[Observation, ...]:+ return tuple(self._entries)++ def clear(self) -> None:+ self._entries.clear()++@dataclass(frozen=True, slots=True)class Provider:- observations: SimpleQueue[Observation] = field(default_factory=SimpleQueue)+ observations: ObservationLog = field(default_factory=ObservationLog)scripts: dict[str, deque[int]] = field(default_factory=dict)scenario_store: ScenarioStore = field(default_factory=ScenarioStore)interactions: dict[str, InteractionState] = field(default_factory=dict)@@ -271,7 +284,10 @@ class Provider:return JSONResponse({"configured": len(statuses)})async def observed(self, request: Request) -> Response:- values: Final = tuple(self.observations.get() for _ in range(self.observations.qsize()))+ if request.method == "DELETE":+ self.observations.clear()+ return Response(status_code=204)+ values: Final = self.observations.snapshot()return JSONResponse({"requests": [@@ -622,7 +638,7 @@ class Provider:return Starlette(routes=[Route("/health", health),- Route("/__observations", self.observed),+ Route("/__observations", self.observed, methods=["GET", "DELETE"]),Route("/__scripts/{model}", self.script, methods=["POST", "DELETE", "GET"]),Route("/__scenarios", self.register_scenario, methods=["POST"]),Route("/__scenarios/{scenario_id}", self.delete_scenario, methods=["DELETE"]),diff --git a/tests/integration/authorization/_guardrail_opt_out.py b/tests/integration/authorization/_guardrail_opt_out.pyindex e813993edf4..38854a29dc2 100644--- a/tests/integration/authorization/_guardrail_opt_out.py+++ b/tests/integration/authorization/_guardrail_opt_out.py@@ -61,8 +61,8 @@ def chat(candidate: Gateway, model: str, key: str, marker: str, *, stream: booldef upstream_observations(gateway: Gateway) -> tuple[dict[str, JsonValue], ...]:with httpx.Client(timeout=5, trust_env=False) as client:- drained: Final = object_value(client.get(f"{gateway.upstream_url}/__observations").json())- requests: Final = drained["requests"]+ observed: Final = object_value(client.get(f"{gateway.upstream_url}/__observations").json())+ requests: Final = observed["requests"]assert isinstance(requests, list)return tuple(object_value(entry) for entry in requests)diff --git a/tests/integration/authorization/_hidden_alias_budget.py b/tests/integration/authorization/_hidden_alias_budget.pyindex eb099e56026..bee2a585cff 100644--- a/tests/integration/authorization/_hidden_alias_budget.py+++ b/tests/integration/authorization/_hidden_alias_budget.py@@ -201,10 +201,14 @@ def exhausted_key(rig: AliasRig, scenario: Scenario) -> str:def upstream_requests(upstream_url: str) -> tuple[str, ...]:- drained: Final = JSON_OBJECT.validate_json(+ observed: Final = JSON_OBJECT.validate_json(httpx.get(f"{upstream_url}/__observations", timeout=15, trust_env=False).content)- return tuple(json.dumps(entry) for entry in JSON_LIST.validate_python(drained["requests"]))+ return tuple(json.dumps(entry) for entry in JSON_LIST.validate_python(observed["requests"]))+++def reset_upstream_requests(upstream_url: str) -> None:+ httpx.delete(f"{upstream_url}/__observations", timeout=15, trust_env=False).raise_for_status()def upstream_hits(observed: tuple[str, ...], marker: str) -> int:diff --git a/tests/integration/authorization/test_access_group_model_listing.py b/tests/integration/authorization/test_access_group_model_listing.pyindex 13439d19769..c8757bdab9d 100644--- a/tests/integration/authorization/test_access_group_model_listing.py+++ b/tests/integration/authorization/test_access_group_model_listing.py@@ -79,6 +79,10 @@ def _observed(upstream: httpx.Client) -> list[dict[str, JsonValue]]:return requests+def _reset_observations(upstream: httpx.Client) -> None:+ upstream.delete("/__observations").raise_for_status()++def _chat(proxy: Gateway, model: str, key: str, text: str) -> httpx.Response:return proxy.request("POST",@@ -135,7 +139,7 @@ def test_access_group_assignment_grants_and_revokes_on_gateway_and_peer(team_key: Final = scenario.key(team_id=team_id)assigned_key: Final = scenario.key(models=["no-default-models"])hashed_key: Final = sha256(assigned_key.encode()).hexdigest()- _observed(upstream)+ _reset_observations(upstream)_assert_denied(_chat(gateway, model, team_key, "control team"), model, "team_model_access_denied")_assert_denied(_chat(gateway, model, assigned_key, "control key"), model, "key_model_access_denied")assert _observed(upstream) == []@@ -173,6 +177,7 @@ def test_access_group_assignment_grants_and_revokes_on_gateway_and_peer()expected.append(_observation(text))assert _observed(upstream) == expected+ _reset_observations(upstream)removed_team: Final = gateway.request("PUT", f"{route_prefix}/{access_group_id}", {"assigned_team_ids": []})assert removed_team.status_code == 200, removed_team.text@@ -183,6 +188,7 @@ def test_access_group_assignment_grants_and_revokes_on_gateway_and_peer(still_granted: Final = f"still granted {uuid.uuid4().hex}"_assert_served(_chat(gateway, model, assigned_key, still_granted))assert _observed(upstream) == [_observation(still_granted)]+ _reset_observations(upstream)removed_key: Final = gateway.request("PUT", f"{route_prefix}/{access_group_id}", {"assigned_key_ids": []})assert removed_key.status_code == 200, removed_key.text@@ -203,6 +209,7 @@ def test_access_group_assignment_grants_and_revokes_on_gateway_and_peer(_assert_served(_chat(gateway, model, key, text))regranted.append(_observation(text))assert _observed(upstream) == regranted+ _reset_observations(upstream)deleted: Final = gateway.request("DELETE", f"{route_prefix}/{access_group_id}")assert deleted.status_code == 204, deleted.text@@ -266,6 +273,7 @@ def test_deleting_an_access_group_revokes_a_still_assigned_team_and_key(gateway:)_assert_served(key_response)assert _observed(upstream) == [_observation(team_text), _observation(key_text)]+ _reset_observations(upstream)deleted: Final = gateway.request("DELETE", f"{route_prefix}/{access_group_id}")assert deleted.status_code == 204, deleted.text@@ -310,12 +318,13 @@ def test_access_group_revocation_reaches_a_warmed_peer_before_the_cache_ttl(assert created.status_code == 201, created.textaccess_group_id: Final = string_value(created.json()["access_group_id"])scenario.cleanups.callback(gateway.request, "DELETE", f"{route_prefix}/{access_group_id}")- _observed(upstream)+ _reset_observations(upstream)if revocation == "team":warmed: Final = _chat(peer, model, team_key, "warm team")assert warmed.status_code == 200, warmed.textassert _observed(upstream) == [_observation("warm team")]+ _reset_observations(upstream)team_update: Final = gateway.request("PUT", f"{route_prefix}/{access_group_id}", {"assigned_team_ids": []})assert team_update.status_code == 200, team_update.text_assert_denied(@@ -331,6 +340,7 @@ def test_access_group_revocation_reaches_a_warmed_peer_before_the_cache_ttl(warmed: Final = _chat(peer, model, assigned_key, "warm key")assert warmed.status_code == 200, warmed.textassert _observed(upstream) == [_observation("warm key")]+ _reset_observations(upstream)key_update: Final = gateway.request("PUT", f"{route_prefix}/{access_group_id}", {"assigned_key_ids": []})assert key_update.status_code == 200, key_update.text_assert_denied(@@ -351,6 +361,7 @@ def test_access_group_revocation_reaches_a_warmed_peer_before_the_cache_ttl(_observation("warm delete team"),_observation("warm delete key"),]+ _reset_observations(upstream)deleted: Final = gateway.request("DELETE", f"{route_prefix}/{access_group_id}")assert deleted.status_code == 204, deleted.text_assert_denied(@@ -383,7 +394,7 @@ def test_raw_key_in_assigned_key_ids_grants_the_same_access_as_the_hashed_key(gamodel: Final = scenario.model()key: Final = scenario.key(models=["no-default-models"])hashed_key: Final = sha256(key.encode()).hexdigest()- _observed(upstream)+ _reset_observations(upstream)_assert_denied(_chat(gateway, model, key, "control"), model, "key_model_access_denied")assert _observed(upstream) == []diff --git a/tests/integration/authorization/test_end_user_block.py b/tests/integration/authorization/test_end_user_block.pyindex fd283380d8f..7b1eb8da74a 100644--- a/tests/integration/authorization/test_end_user_block.py+++ b/tests/integration/authorization/test_end_user_block.py@@ -36,6 +36,10 @@ def _observed(upstream: httpx.Client) -> list[dict[str, JsonValue]]:return requests+def _reset_observations(upstream: httpx.Client) -> None:+ upstream.delete("/__observations").raise_for_status()++def _chat(gateway: Gateway, model: str, key: str, end_user: str) -> httpx.Response:return gateway.request("POST",@@ -215,7 +219,7 @@ def test_blocked_end_user_is_refused_on_every_proxy_and_unblock_restores():rig: Final = _two_callback_proxies(gateway, tmp_path, stack)with rig.first.scenario() as scenario:- _observed(upstream)+ _reset_observations(upstream)end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"created: Final = rig.first.request("POST", "/customer/new", {"user_id": end_user, "max_budget": 100.0})assert created.status_code == 200, created.text@@ -224,7 +228,7 @@ def test_blocked_end_user_is_refused_on_every_proxy_and_unblock_restores(key: Final = scenario.key(models=[model])served: Final = _chat(rig.first, model, key, end_user)assert served.status_code == 200, served.text- _observed(upstream)+ _reset_observations(upstream)rig.first.request("POST", block_route, {"user_ids": [end_user]})assert eventually(diff --git a/tests/integration/authorization/test_hidden_alias_budget_bypass_chaos.py b/tests/integration/authorization/test_hidden_alias_budget_bypass_chaos.pyindex 3e6acfc72de..980e7251a66 100644--- a/tests/integration/authorization/test_hidden_alias_budget_bypass_chaos.py+++ b/tests/integration/authorization/test_hidden_alias_budget_bypass_chaos.py@@ -26,6 +26,7 @@ from integration.authorization._hidden_alias_budget import (install_aliases,landed_all_once,remove_aliases,+ reset_upstream_requests,settle_candidate,settle_chat,upstream_hits,@@ -73,7 +74,7 @@ def test_mixed_concurrent_burst_through_hidden_free_aliases_lands_each_call_oncemarkers: Final = tuple(f"burst-{_KINDS[index % len(_KINDS)]}-{index}-{uuid.uuid4().hex}" for index in range(30))with rig.gateway.scenario() as scenario:key: Final = exhausted_key(rig, scenario)- upstream_requests(rig.gateway.upstream_url)+ reset_upstream_requests(rig.gateway.upstream_url)responses: Final = _send_all(lambda marker: _mixed_call(rig, key, marker), markers)assert [response.status_code for response in responses] == [200] * len(markers), [response.text for response in responses if response.status_code != 200@@ -96,7 +97,7 @@ def test_alias_flipped_to_a_free_group_during_a_burst_only_ever_serves_or_refusesettle_chat(rig, alias, rig.gateway.key, 200)key: Final = exhausted_key(rig, scenario)settle_chat(rig, alias, key, BUDGET_EXCEEDED)- upstream_requests(rig.gateway.upstream_url)+ reset_upstream_requests(rig.gateway.upstream_url)def wave(candidate: Gateway) -> frozenset[int]:markers: Final = _burst_markers("flip", _WAVE)diff --git a/tests/integration/authorization/test_key_guardrail_opt_out_chaos.py b/tests/integration/authorization/test_key_guardrail_opt_out_chaos.pyindex 3ceae540ba9..4815eebe2f1 100644--- a/tests/integration/authorization/test_key_guardrail_opt_out_chaos.py+++ b/tests/integration/authorization/test_key_guardrail_opt_out_chaos.py@@ -21,7 +21,6 @@ from integration.authorization._guardrail_opt_out import (guardrail_config,non_admin_caller,stored_metadata,- upstream_hits,upstream_observations,)@@ -226,9 +225,14 @@ def test_exempt_burst_survives_guardrail_sink_outage(gateway: Gateway, tmp_path:"synthetic policy denial" in response.text or response.status_code == 500for response in non_exempt_outage), [response.text for response in non_exempt_outage if response.status_code not in {400, 500}]- assert all(upstream_hits(gateway, f"outage-{index}-") == 0 for index in range(1, 20, 2)), (- upstream_observations(gateway)- )+ control_marker: Final = "control-" + uuid.uuid4().hex+ control: Final = chat(candidate, model, exempt, control_marker)+ assert control.status_code == 200, control.text+ observed: Final = upstream_observations(gateway)+ bodies: Final = tuple(json.dumps(entry.get("body")) for entry in observed)+ assert any(control_marker in body for body in bodies), observed+ assert all(any(f"outage-{index}-" in body for body in bodies) for index in range(0, 20, 2)), observed+ assert not any(any(f"outage-{index}-" in body for body in bodies) for index in range(1, 20, 2)), observedsink.start()recovered: Final = chat(candidate, model, plain, "recovered-" + uuid.uuid4().hex)diff --git a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py b/tests/integration/authorization/test_rag_query_vector_store_allowlist.pyindex c1777c66c39..c90b689599b 100644--- a/tests/integration/authorization/test_rag_query_vector_store_allowlist.py+++ b/tests/integration/authorization/test_rag_query_vector_store_allowlist.py@@ -734,14 +734,21 @@ def test_explicit_false_flag_keeps_legacy_vector_store_outcomes(tmp_path: Path)models=_json_array(model), object_permission=_permission_for_stores("vs_some_other_store"))- allowed: Final = _rag_query(gateway, model, allowed_marker, no_permission_key)denied: Final = _rag_query(gateway, model, denied_marker, excluding_key)+ allowed: Final = _rag_query(gateway, model, allowed_marker, no_permission_key)- assert allowed.status_code == 200, allowed.text- assert len(_searches_for_marker(upstream_gateway, allowed_marker)) == 1assert denied.status_code == 401, denied.textassert denied.json()["error"]["type"] == "key_vector_store_access_denied"- assert _searches_for_marker(upstream_gateway, denied_marker) == ()+ assert allowed.status_code == 200, allowed.text+ searches: Final = tuple(+ str(observation["body"])+ for observation in upstream_observations(upstream_gateway)+ if observation["path"] == f"/vector_stores/{CONFIG_STORE_ID}/search"+ )+ assert (+ sum(allowed_marker in body for body in searches),+ sum(denied_marker in body for body in searches),+ ) == (1, 0), searchesdef _strict_no_registry_config(directory: Path) -> Path:diff --git a/tests/integration/authorization/test_team_member_permissions.py b/tests/integration/authorization/test_team_member_permissions.pyindex 5d29aceb10c..22752becfcb 100644--- a/tests/integration/authorization/test_team_member_permissions.py+++ b/tests/integration/authorization/test_team_member_permissions.py@@ -71,8 +71,8 @@ class _HTTPErrorResponse(BaseModel):@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:- response: Final = client.get("/__observations")- assert response.status_code == 200, response.text+ response: Final = client.delete("/__observations")+ assert response.status_code == 204, response.textyield clientdiff --git a/tests/integration/authorization/test_team_scoped_models.py b/tests/integration/authorization/test_team_scoped_models.pyindex 2982fbdb4eb..8f8e12ae498 100644--- a/tests/integration/authorization/test_team_scoped_models.py+++ b/tests/integration/authorization/test_team_scoped_models.py@@ -41,7 +41,7 @@ class _ErrorResponse(BaseModel):@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as client:- client.get("/__observations").raise_for_status()+ client.delete("/__observations").raise_for_status()yield client@@ -166,6 +166,7 @@ def test_team_model_alias_routes_a_team_key_to_its_target(assert string_value(response.json()["model"]) == aliasobserved: Final = _observed_requests(upstream)assert _calls_to(observed, provider_model) == 1, observed+ upstream.delete("/__observations").raise_for_status()unaliased: Final = _chat(gateway, f"alias-{uuid.uuid4().hex}", key)assert unaliased.status_code == 403, unaliased.textassert unaliased.json()["error"]["type"] == "key_model_access_denied"@@ -189,6 +190,7 @@ def test_team_model_add_and_delete_change_what_a_warmed_team_key_can_call(_model_denied(initially_denied)observed_before_add: Final = _observed_provider_models(upstream)assert observed_before_add == (provider_one,), repr(observed_before_add)+ upstream.delete("/__observations").raise_for_status()added: Final = gateway.request("POST", "/team/model/add", {"team_id": team, "models": [model_two, model_three]})assert added.status_code == 200, added.textdiff --git a/tests/integration/authorization/test_wildcard_model_access.py b/tests/integration/authorization/test_wildcard_model_access.pyindex f63c2aac84a..9aa55be0da5 100644--- a/tests/integration/authorization/test_wildcard_model_access.py+++ b/tests/integration/authorization/test_wildcard_model_access.py@@ -40,7 +40,7 @@ def candidate(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Gateway]:@pytest.fixturedef upstream(candidate: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=candidate.upstream_url, timeout=5, trust_env=False) as client:- client.get("/__observations").raise_for_status()+ client.delete("/__observations").raise_for_status()yield client@@ -78,6 +78,7 @@ def test_a_key_without_models_inherits_the_users_exact_and_wildcard_grants(assert _chat(candidate, f"anthropic/{wildcard_model}", key).status_code == 200assert _chat(candidate, "good-model", key).status_code == 200assert _observed_models(upstream) == [wildcard_model, "good-model-upstream"]+ upstream.delete("/__observations").raise_for_status()denied: Final = tuple(_chat(candidate, outside, key)for outside in (f"groq/{wildcard_model}", f"bedrock/anthropic.{wildcard_model}")diff --git a/tests/integration/caching/response_cache_case.py b/tests/integration/caching/response_cache_case.pyindex 8dfb6a0a479..a1850ebdb9d 100644--- a/tests/integration/caching/response_cache_case.py+++ b/tests/integration/caching/response_cache_case.py@@ -216,22 +216,19 @@ MESSAGE_STREAM_WITHOUT_CONTENT_BLOCKS: Final = SseResponse(class Upstream:- """The owned upstream's observations, drained once per read and kept, filtered per deployment."""+ """The owned upstream's observations, filtered per deployment."""def __init__(self, url: str = CONTROL_URL) -> None:self._url: Final = url.rstrip("/")- self._seen: tuple[dict[str, JsonValue], ...] = ()def received(self, identity: str) -> tuple[dict[str, JsonValue], ...]:with httpx.Client(timeout=10, trust_env=False) as client:payload: Final = JSON_OBJECT.validate_json(client.get(f"{self._url}/__observations").content)requests: Final = payload["requests"]assert isinstance(requests, list)- self._seen = (- *self._seen,- *(object_value(item) for item in requests),- ) # rebind-ok: drained observations accumulate- return tuple(item for item in self._seen if f"/{identity}/" in string_value(item.get("path", "")))+ return tuple(+ item for item in map(object_value, requests) if f"/{identity}/" in string_value(item.get("path", ""))+ )def calls(self, identity: str) -> int:"""The LLM calls the deployment took; the proxy's boot-time ``GET /v1/models`` discovery of a configdiff --git a/tests/integration/compatibility/_status_code_audit.py b/tests/integration/compatibility/_status_code_audit.pyindex 4ba1ee6b102..e0e457fb11d 100644--- a/tests/integration/compatibility/_status_code_audit.py+++ b/tests/integration/compatibility/_status_code_audit.py@@ -6,7 +6,6 @@ upstream's observation feed, so a cell asserts both what the caller got and whatfrom __future__ import annotationsimport json-import osimport uuidfrom collections.abc import Iterator, Mapping, Sequencefrom contextlib import contextmanager@@ -140,35 +139,30 @@ def openai_error(message: str, param: str) -> JsonResponse:class Upstream:- """Reads the scripted upstream's destructive observation feed and keeps every record it drained."""-def __init__(self, url: str) -> None:self.url = url.rstrip("/")- self.items: tuple[dict[str, JsonValue], ...] = ()- def drain(self) -> None:+ def reset(self) -> None:+ with httpx.Client(timeout=10, trust_env=False) as client:+ client.delete(f"{self.url}/__observations").raise_for_status()++ def observed(self) -> tuple[dict[str, JsonValue], ...]:with httpx.Client(timeout=10, trust_env=False) as client:payload: Final = JSON_OBJECT.validate_python(client.get(f"{self.url}/__observations?include_method=true").json())requests: Final = payload.get("requests")assert isinstance(requests, list)- self.items = (*self.items, *(object_value(item) for item in requests if isinstance(item, dict)))+ return tuple(object_value(item) for item in requests if isinstance(item, dict))def calls(self, identity: str) -> tuple[dict[str, JsonValue], ...]:- self.drain()return tuple(item- for item in self.items+ for item in self.observed()if f"/{identity}/" in str(item.get("path")) and not str(item.get("path", "")).endswith("/models"))-def drain_rig_upstream() -> None:- """Drops every observation earlier cells left on the shared upstream, so a cell reads only its own calls."""- Upstream(os.environ["INTEGRATION_UPSTREAM_URL"]).drain()--def assert_no_provider_call(gateway: Gateway, *identities: str) -> None:upstream: Final = Upstream(gateway.upstream_url)assert {identity: upstream.calls(identity) for identity in identities} == dict.fromkeys(identities, ())diff --git a/tests/integration/compatibility/test_missing_body_param_status.py b/tests/integration/compatibility/test_missing_body_param_status.pyindex 673fb0acc51..b2c5b1c74b6 100644--- a/tests/integration/compatibility/test_missing_body_param_status.py+++ b/tests/integration/compatibility/test_missing_body_param_status.py@@ -641,7 +641,7 @@ class _Observations:)requests: Final = payload.get("requests")assert isinstance(requests, list)- self.items = (*self.items, *(object_value(item) for item in requests if isinstance(item, dict)))+ self.items = tuple(object_value(item) for item in requests if isinstance(item, dict))return self.itemsdef for_scenario(self, identity: str) -> tuple[dict[str, JsonValue], ...]:diff --git a/tests/integration/compatibility/test_openai_sdk_client_paths_chaos.py b/tests/integration/compatibility/test_openai_sdk_client_paths_chaos.pyindex 9710d8a1b5c..9a6b9fcd60b 100644--- a/tests/integration/compatibility/test_openai_sdk_client_paths_chaos.py+++ b/tests/integration/compatibility/test_openai_sdk_client_paths_chaos.py@@ -128,7 +128,7 @@ class _Observations:payload: Final = JSON_OBJECT.validate_python(client.get(f"{self.url}/__observations").json())requests: Final = payload.get("requests")assert isinstance(requests, list)- self.items = (*self.items, *(object_value(item) for item in requests if isinstance(item, dict)))+ self.items = tuple(object_value(item) for item in requests if isinstance(item, dict))return self.itemsdiff --git a/tests/integration/compatibility/test_status_code_followups.py b/tests/integration/compatibility/test_status_code_followups.pyindex 662f37aed1a..b6f1ebb07ca 100644--- a/tests/integration/compatibility/test_status_code_followups.py+++ b/tests/integration/compatibility/test_status_code_followups.py@@ -89,7 +89,7 @@ class _Observations:)requests: Final = payload.get("requests")assert isinstance(requests, list)- self.items = (*self.items, *(object_value(item) for item in requests if isinstance(item, dict)))+ self.items = tuple(object_value(item) for item in requests if isinstance(item, dict))return self.itemsdef provider_calls(self, identity: str) -> tuple[dict[str, JsonValue], ...]:diff --git a/tests/integration/compatibility/test_status_code_followups_chaos.py b/tests/integration/compatibility/test_status_code_followups_chaos.pyindex f1ea9e60330..dfff737d17a 100644--- a/tests/integration/compatibility/test_status_code_followups_chaos.py+++ b/tests/integration/compatibility/test_status_code_followups_chaos.py@@ -183,9 +183,7 @@ def _burst(chaos: _Chaos, phase: str) -> tuple[_Outcome, ...]:def _upstream_hits(slot: UpstreamSlot, markers: frozenset[str]) -> Mapping[str, int]:- upstream: Final = Upstream(slot.url)- upstream.drain()- bodies: Final = tuple(json.dumps(item.get("body")) for item in upstream.items)+ bodies: Final = tuple(json.dumps(item.get("body")) for item in Upstream(slot.url).observed())return {marker: sum(marker in body for body in bodies) for marker in markers}diff --git a/tests/integration/compatibility/test_status_code_followups_defaults.py b/tests/integration/compatibility/test_status_code_followups_defaults.pyindex a0c73d12dec..13a6b1b73eb 100644--- a/tests/integration/compatibility/test_status_code_followups_defaults.py+++ b/tests/integration/compatibility/test_status_code_followups_defaults.py@@ -28,7 +28,6 @@ from integration.compatibility._status_code_audit import (USER_MESSAGES,assembled_text,assert_no_provider_call,- drain_rig_upstream,deployment,error_body,invalid_request,@@ -47,11 +46,6 @@ from tests.integration.cost_calculation.cost_tracking_case import BinaryResponsepytestmark: Final = pytest.mark.timeout(180)[email protected](autouse=True)-def _drained_upstream() -> None:- drain_rig_upstream()--@dataclass(frozen=True, slots=True)class _Rig:gateway: Gatewaydiff --git a/tests/integration/compatibility/test_status_code_followups_requests.py b/tests/integration/compatibility/test_status_code_followups_requests.pyindex cffaf09ec55..29822a21d34 100644--- a/tests/integration/compatibility/test_status_code_followups_requests.py+++ b/tests/integration/compatibility/test_status_code_followups_requests.py@@ -20,7 +20,6 @@ from integration.compatibility._status_code_audit import (RESPONSES_FRAMES,assembled_text,assert_no_provider_call,- drain_rig_upstream,invalid_request,json_response,one_outbound,@@ -38,11 +37,6 @@ from tests.integration.cost_calculation.cost_tracking_case import StoredResponsepytestmark: Final = pytest.mark.timeout(180)[email protected](autouse=True)-def _drained_upstream() -> None:- drain_rig_upstream()--_OCR: Final[dict[str, JsonValue]] = {"pages": [{"index": 0, "markdown": "scripted page", "images": [], "dimensions": None}],"model": "mistral-ocr-latest",diff --git a/tests/integration/compatibility/test_status_code_followups_usage_chat.py b/tests/integration/compatibility/test_status_code_followups_usage_chat.pyindex 6d9d9507158..de9ec16cf30 100644--- a/tests/integration/compatibility/test_status_code_followups_usage_chat.py+++ b/tests/integration/compatibility/test_status_code_followups_usage_chat.py@@ -71,7 +71,7 @@ def _tool_results(usage_chat: _UsageChat, start_date: str, end_date: str) -> tup"""Runs one chat turn whose model calls every tool with these dates; returns the tool messages the follow-upmodel call carried, keyed by tool, and the tool statuses the SSE stream reported."""register_scenario(usage_chat.identity, json_response(_tool_calls(start_date, end_date)))- Upstream(usage_chat.gateway.upstream_url).drain()+ Upstream(usage_chat.gateway.upstream_url).reset()with usage_chat.gateway.client.stream("POST","/usage/ai/chat",diff --git a/tests/integration/configuration/test_effective_settings.py b/tests/integration/configuration/test_effective_settings.pyindex 029a5c7220e..acdaacfcfb5 100644--- a/tests/integration/configuration/test_effective_settings.py+++ b/tests/integration/configuration/test_effective_settings.py@@ -868,7 +868,7 @@ def test_saved_retry_setting_controls_real_attempts_and_restores(gateway: Gatewaassert object_value(gateway.get("/router/settings")["current_values"])["num_retries"] == retriesconfigured: Final = upstream.post(f"/__scripts/{provider_model}", json={"statuses": [500, 200]})assert configured.status_code == 200, configured.text- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -1110,7 +1110,7 @@ def test_credential_value_update_and_model_reload_reach_provider(gateway: Gatewa"PATCH", f"/model/{identity}/update", {"model_info": {"description": value}})assert response.status_code == 200, response.text- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()assert (object_value(gateway.chat(model, text=f"{name} {value} reload={reload}")["usage"])["total_tokens"]== 40diff --git a/tests/integration/conftest.py b/tests/integration/conftest.pyindex 672ab7b6c6a..d605bd3d7d7 100644--- a/tests/integration/conftest.py+++ b/tests/integration/conftest.py@@ -323,10 +323,16 @@ def pytest_runtest_teardown(item: pytest.Item, nextitem: pytest.Item | None) ->return (yield)[email protected](autouse=True)+def _reset_upstream_observations() -> None:+ upstream: Final = os.environ.get("INTEGRATION_UPSTREAM_URL")+ if upstream is not None:+ httpx.delete(f"{upstream}/__observations", timeout=5, trust_env=False).raise_for_status()++@pytest.fixturedef gateway() -> Iterator[Gateway]:with gateway_from_environment() as value:- httpx.get(f"{value.upstream_url}/__observations", timeout=5, trust_env=False).raise_for_status()yield valuediff --git a/tests/integration/management/test_batch_output_file_listing.py b/tests/integration/management/test_batch_output_file_listing.pyindex 26d1ae8de46..8aa01b0564e 100644--- a/tests/integration/management/test_batch_output_file_listing.py+++ b/tests/integration/management/test_batch_output_file_listing.py@@ -389,7 +389,7 @@ def test_fallback_output_file_details_refresh_once_provider_recovers(gateway: Gaassert details["bytes"] == OUTPUT_BYTES, detailsassert (details["filename"], details["purpose"]) == ("output.jsonl", "batch_output"), detailsassert "litellm_details_fallback" not in details, details- assert _metadata_hit_count(gateway, batch.scenario) == 1+ assert _metadata_hit_count(gateway, batch.scenario) - metadata_hits_before_recovery == 1refreshed_files: Final = _list_files(gateway, batch.owner_key, purpose="batch_output")refreshed_output: Final = next((file for file in refreshed_files if file.get("id") == output_id), None)@@ -647,5 +647,5 @@ def test_repeated_batch_retrieve_does_not_refetch_saved_file_details(gateway: GaNone,)assert output_after == output_before, output_after- additional_hits: Final = _metadata_hit_count(gateway, batch.scenario)+ additional_hits: Final = _metadata_hit_count(gateway, batch.scenario) - hits_beforeassert additional_hits == 0, f"Repeated batch retrieval fetched metadata {additional_hits} more times"diff --git a/tests/integration/management/test_fallback_management_public_names.py b/tests/integration/management/test_fallback_management_public_names.pyindex a5b311e38eb..fcbeee9dc60 100644--- a/tests/integration/management/test_fallback_management_public_names.py+++ b/tests/integration/management/test_fallback_management_public_names.py@@ -53,7 +53,7 @@ def migrated_database(tmp_path_factory: pytest.TempPathFactory) -> None:@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as client:- client.get("/__observations").raise_for_status()+ client.delete("/__observations").raise_for_status()yield client@@ -206,7 +206,7 @@ def test_rule_by_team_public_name_fires_on_chat_completions(gateway: Gateway, upcreated: Final = _create_fallback(gateway, scenario, primary, [fallback])assert created.status_code == 200, created.textupstream.post(f"/__scripts/{primary_provider}", json={"statuses": [500]}).raise_for_status()- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()answered: Final = eventually(lambda: gateway.request("POST",diff --git a/tests/integration/management/test_model_health_check.py b/tests/integration/management/test_model_health_check.pyindex 9945d16af07..57a05daca94 100644--- a/tests/integration/management/test_model_health_check.py+++ b/tests/integration/management/test_model_health_check.py@@ -110,7 +110,7 @@ def test_health_check_of_a_model_added_through_the_api_calls_its_upstream_and_reassert (object_value(gateway.chat(model, key=key, text=f"health {uuid.uuid4().hex}")["usage"])["total_tokens"] == 40)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()health: Final = gateway.request("GET", "/health", params={"model": model})assert health.status_code == 200, health.textreport: Final = health.json()diff --git a/tests/integration/management/test_organization_lifecycle.py b/tests/integration/management/test_organization_lifecycle.pyindex cdbf3c15b18..dbd8cce542e 100644--- a/tests/integration/management/test_organization_lifecycle.py+++ b/tests/integration/management/test_organization_lifecycle.py@@ -179,6 +179,7 @@ def test_organization_delete_revokes_org_and_team_keys_on_gateway_and_peer(gatewresponse: Final = _chat(proxy, model, key, text)assert response.status_code == 200, response.textassert _observed(upstream) == [_observation(text)]+ upstream.delete("/__observations").raise_for_status()deleted: Final = gateway.request("DELETE", "/organization/delete", {"organization_ids": [organization_id]})assert deleted.status_code == 200, deleted.text@@ -207,6 +208,7 @@ def test_organization_delete_revokes_org_and_team_keys_on_gateway_and_peer(gatewresponse: Final = _chat(proxy, model, other_key, text)assert response.status_code == 200, response.textassert _observed(upstream) == [_observation(text)]+ upstream.delete("/__observations").raise_for_status()hashed: Final = tuple(sha256(key.encode()).hexdigest() for key in (organization_key, team_key))assert _key_rows(*hashed) == []diff --git a/tests/integration/management/test_team_block.py b/tests/integration/management/test_team_block.pyindex 37c9da33c06..3d1f9e430ea 100644--- a/tests/integration/management/test_team_block.py+++ b/tests/integration/management/test_team_block.py@@ -38,8 +38,7 @@ class _ErrorResponse(BaseModel):@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:- response: Final = client.get("/__observations")- assert response.status_code == 200, response.text+ client.delete("/__observations").raise_for_status()yield client@@ -74,6 +73,7 @@ def test_team_block_and_unblock_update_endpoint_info_and_db_state(assert peer_before.status_code == 200, peer_before.textobserved_before_block: Final = _models(upstream)assert observed_before_block == (provider_model, provider_model), repr(observed_before_block)+ upstream.delete("/__observations").raise_for_status()blocked_response: Final = gateway.request("POST", "/team/block", {"team_id": team})assert blocked_response.status_code == 200, blocked_response.text@@ -96,6 +96,7 @@ def test_team_block_and_unblock_update_endpoint_info_and_db_state(assert _ErrorResponse.model_validate_json(cold_denied.text).error.type == "auth_error", cold_denied.textafter_cold_denied: Final = _models(upstream)assert after_cold_denied == (), repr(after_cold_denied)+ upstream.delete("/__observations").raise_for_status()unblocked_response: Final = gateway.request("POST", "/team/unblock", {"team_id": team})assert unblocked_response.status_code == 200, unblocked_response.text@@ -139,6 +140,7 @@ def test_unblocking_a_team_restores_warmed_keys_on_both_proxies(assert peer_before.status_code == 200, peer_before.textobserved_before_block: Final = _models(upstream)assert observed_before_block == (provider_model, provider_model), repr(observed_before_block)+ upstream.delete("/__observations").raise_for_status()blocked_response: Final = gateway.request("POST", "/team/block", {"team_id": team})assert blocked_response.status_code == 200, blocked_response.text@@ -148,6 +150,7 @@ def test_unblocking_a_team_restores_warmed_keys_on_both_proxies(assert _ErrorResponse.model_validate_json(cold_denied.text).error.type == "auth_error", cold_denied.textafter_cold_denied: Final = _models(upstream)assert after_cold_denied == (), repr(after_cold_denied)+ upstream.delete("/__observations").raise_for_status()unblocked_response: Final = gateway.request("POST", "/team/unblock", {"team_id": team})assert unblocked_response.status_code == 200, unblocked_response.text@@ -177,6 +180,7 @@ def test_warmed_team_keys_are_refused_on_both_proxies_after_block(assert peer_before.status_code == 200, peer_before.textobserved_before_block: Final = _models(upstream)assert observed_before_block == (provider_model, provider_model), repr(observed_before_block)+ upstream.delete("/__observations").raise_for_status()blocked_response: Final = gateway.request("POST", "/team/block", {"team_id": team})assert blocked_response.status_code == 200, blocked_response.text@@ -210,6 +214,7 @@ def test_a_new_team_key_is_refused_on_a_peer_that_cached_the_team_before_block(assert peer_before.status_code == 200, peer_before.textobserved_before_block: Final = _models(upstream)assert observed_before_block == (provider_model,), repr(observed_before_block)+ upstream.delete("/__observations").raise_for_status()blocked_response: Final = gateway.request("POST", "/team/block", {"team_id": team})assert blocked_response.status_code == 200, blocked_response.textdiff --git a/tests/integration/management/test_team_member_lifecycle.py b/tests/integration/management/test_team_member_lifecycle.pyindex f2b8abaa9f1..2fb90b4b925 100644--- a/tests/integration/management/test_team_member_lifecycle.py+++ b/tests/integration/management/test_team_member_lifecycle.py@@ -123,8 +123,7 @@ class _BulkDeleteResponse(BaseModel):@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:- response: Final = client.get("/__observations")- assert response.status_code == 200, response.text+ client.delete("/__observations").raise_for_status()yield client@@ -209,6 +208,7 @@ def test_member_delete_revokes_the_removed_members_warmed_key(assert stayer_warm.status_code == 200, stayer_warm.textobserved_before_delete: Final = _models(upstream)assert observed_before_delete == (provider_model, provider_model), repr(observed_before_delete)+ upstream.delete("/__observations").raise_for_status()delete_body: Final = ({"team_id": team, "user_id": leaver}@@ -252,6 +252,7 @@ def test_member_delete_revokes_the_removed_members_warmed_key(_refused(refused, 401, "token_not_found_in_db")after_refused: Final = _models(upstream)assert after_refused == (), repr(after_refused)+ upstream.delete("/__observations").raise_for_status()stayer_after: Final = _chat(gateway, model, stayer_key, "stayer after delete " + uuid.uuid4().hex)assert stayer_after.status_code == 200, stayer_after.textobserved_after_delete: Final = _models(upstream)@@ -282,6 +283,7 @@ def test_member_delete_by_email_removes_a_legacy_email_only_roster_entry(assert leaver_warm.status_code == 200, leaver_warm.textobserved_before_delete: Final = _models(upstream)assert observed_before_delete == (provider_model,), repr(observed_before_delete)+ upstream.delete("/__observations").raise_for_status()stayer_roster: Final = _roster_member(stayer, None)legacy_roster: Final = {"role": "user", "user_id": None, "user_email": email}@@ -320,6 +322,7 @@ def test_member_delete_by_email_removes_a_legacy_email_only_roster_entry(_refused(refused, 401, "token_not_found_in_db")after_refused: Final = _models(upstream)assert after_refused == (), repr(after_refused)+ upstream.delete("/__observations").raise_for_status()served: Final = _chat(gateway, model, stayer_key, "stayer after legacy delete " + uuid.uuid4().hex)assert served.status_code == 200, served.textobserved: Final = _models(upstream)@@ -351,6 +354,7 @@ def test_member_delete_by_case_variant_email_removes_member_and_refuses_warmed_kassert warmed.status_code == 200, warmed.textobserved_before_delete: Final = _models(upstream)assert observed_before_delete == (provider_model,), repr(observed_before_delete)+ upstream.delete("/__observations").raise_for_status()deleted: Final = gateway.request("POST",@@ -540,6 +544,7 @@ def test_member_add_list_mixing_id_and_email_applies_budget_and_allowed_models(denied_one: Final = _chat(gateway, model_two, key_one, "mixed member one denied")_refused(denied_one, 403, "team_model_access_denied")after_denied_one: Final = _models(upstream)+ upstream.delete("/__observations").raise_for_status()allowed_two: Final = _chat(gateway, model_one, key_two, "mixed member two allowed")assert allowed_two.status_code == 200, allowed_two.textdenied_two: Final = _chat(gateway, model_two, key_two, "mixed member two denied")@@ -801,6 +806,7 @@ def test_bulk_delete_removes_exactly_the_named_members_and_revokes_their_access(assert stayer_warm.status_code == 200, stayer_warm.textobserved_before_delete: Final = _models(upstream)assert observed_before_delete == (provider_model, provider_model, provider_model), repr(observed_before_delete)+ upstream.delete("/__observations").raise_for_status()probe_user: Final = scenario.user()admin_route_before: Final = gateway.request(@@ -851,9 +857,11 @@ def test_bulk_delete_removes_exactly_the_named_members_and_revokes_their_access(denied_admin: Final = _chat(gateway, model, admin_key, "deleted admin key")_refused(denied_admin, 401, "token_not_found_in_db")observed_after_admin_denied: Final = _models(upstream)+ upstream.delete("/__observations").raise_for_status()denied_member: Final = _chat(gateway, model, member_key, "deleted member key")_refused(denied_member, 401, "token_not_found_in_db")observed_after_member_denied: Final = _models(upstream)+ upstream.delete("/__observations").raise_for_status()denied_admin_route: Final = gateway.request("POST","/team/member_add",@@ -900,6 +908,7 @@ def test_bulk_delete_by_case_variant_email_removes_member_and_refuses_warmed_keyassert warmed.status_code == 200, warmed.textobserved_before_delete: Final = _models(upstream)assert observed_before_delete == (provider_model,), repr(observed_before_delete)+ upstream.delete("/__observations").raise_for_status()deleted: Final = gateway.request("POST",diff --git a/tests/integration/management/test_user_delete_revokes_keys.py b/tests/integration/management/test_user_delete_revokes_keys.pyindex 37886cd94bb..324963a0da9 100644--- a/tests/integration/management/test_user_delete_revokes_keys.py+++ b/tests/integration/management/test_user_delete_revokes_keys.py@@ -123,6 +123,7 @@ def test_user_delete_revokes_keys_and_memberships(gateway: Gateway, peer: Gatewaassert _chat(proxy, model, key, text).status_code == 200expected.append(_observation(text))assert _observed(upstream) == expected+ upstream.delete("/__observations").raise_for_status()deleted: Final = gateway.request("POST", "/user/delete", {"user_ids": [user_id]})assert deleted.status_code == 200, deleted.textdiff --git a/tests/integration/management/test_user_updates_wedged_coordination_redis.py b/tests/integration/management/test_user_updates_wedged_coordination_redis.pyindex 5ec5f85eef2..7934e927d93 100644--- a/tests/integration/management/test_user_updates_wedged_coordination_redis.py+++ b/tests/integration/management/test_user_updates_wedged_coordination_redis.py@@ -458,6 +458,7 @@ def test_user_budget_update_propagates_to_gateway_and_peer(gateway: Gateway, pee== 200)assert _observed(upstream) == [_chat_observation(warm)]+ upstream.delete("/__observations").raise_for_status()_wait_for_spend(user_id, 0.11)shrink: Final = gateway.request("POST", "/user/update", {"user_id": user_id, "max_budget": 0.01})@@ -490,6 +491,7 @@ def test_user_budget_update_propagates_to_gateway_and_peer(gateway: Gateway, pee== 200)assert _observed(upstream) == [_chat_observation(text)]+ upstream.delete("/__observations").raise_for_status()_wait_for_spend(user_id, 0.23)email: Final = f"{user_id}@integration.local"@@ -522,6 +524,7 @@ def test_user_models_update_with_metadata_propagates_to_gateway_and_peer(gateway== 200)assert _observed(upstream) == [_chat_observation(warm)]+ upstream.delete("/__observations").raise_for_status()narrowed: Final = gateway.request("POST",@@ -563,6 +566,7 @@ def test_user_models_update_with_metadata_propagates_to_gateway_and_peer(gateway== 200)assert _observed(upstream) == [_chat_observation(text)]+ upstream.delete("/__observations").raise_for_status()def test_partial_user_update_preserves_sibling_fields(gateway: Gateway) -> None:@@ -616,6 +620,7 @@ def test_user_models_only_update_is_enforced_on_the_gateway(gateway: Gateway) ->warmed: Final = _user_chat(gateway, model, key, warm)assert warmed.status_code == 200, warmed.textassert _observed(upstream) == [_chat_observation(warm)]+ upstream.delete("/__observations").raise_for_status()narrowed: Final = gateway.request("POST", "/user/update", {"user_id": user_id, "models": ["no-default-models"]})assert narrowed.status_code == 200, narrowed.text@@ -643,12 +648,13 @@ def test_user_models_update_without_metadata_propagates_to_gateway_and_peer(gatescenario.cleanups.callback(lambda: gateway.request("POST", "/user/delete", {"user_ids": [user_id]}))key: Final = string_value(gateway.post("/key/generate", {"user_id": user_id})["key"])- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()for proxy in (gateway, peer):warm: Final = f"warm {uuid.uuid4().hex}"warmed: Final = _user_chat(proxy, model, key, warm)assert warmed.status_code == 200, warmed.textassert _observed(upstream) == [_chat_observation(warm)]+ upstream.delete("/__observations").raise_for_status()narrowed: Final = gateway.request("POST", "/user/update", {"user_id": user_id, "models": ["no-default-models"]})assert narrowed.status_code == 200, narrowed.textdiff --git a/tests/integration/management/test_vector_store_config_ownership.py b/tests/integration/management/test_vector_store_config_ownership.pyindex fbf21d7af06..7dcf0a6a51b 100644--- a/tests/integration/management/test_vector_store_config_ownership.py+++ b/tests/integration/management/test_vector_store_config_ownership.py@@ -329,7 +329,7 @@ def test_chat_with_config_store_searches_upstream_and_injects_context_after_listmodel: Final = scenario.model()marker: Final = f"lit6337 {uuid.uuid4().hex}"assert CONFIG_STORE_ID in listed_ids(gateway)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()completion: Final = gateway.post("/v1/chat/completions",{"model": model, "messages": [{"role": "user", "content": marker}], "vector_store_ids": [CONFIG_STORE_ID]},@@ -353,7 +353,7 @@ def test_passthrough_search_on_config_store_uses_yaml_credentials_after_listing(with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream:marker: Final = f"lit6337 passthrough {uuid.uuid4().hex}"assert CONFIG_STORE_ID in listed_ids(gateway)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()searched: Final = gateway.request("POST", f"/v1/vector_stores/{CONFIG_STORE_ID}/search", {"query": marker})assert searched.status_code == 200, searched.textdata: Final = listed_rows(searched)diff --git a/tests/integration/observability/_logging_only_scope_support.py b/tests/integration/observability/_logging_only_scope_support.pyindex 24c5083d95a..3d29f7ab8c5 100644--- a/tests/integration/observability/_logging_only_scope_support.py+++ b/tests/integration/observability/_logging_only_scope_support.py@@ -76,6 +76,8 @@ _AUDIT_POLICY_REQUEST_COUNT: Final[ContextVar[int]] = ContextVar("audit_policy_r_AUDIT_UPSTREAM_REQUEST_COUNT: Final[ContextVar[int]] = ContextVar("audit_upstream_request_count", default=0)+_AUDIT_UPSTREAM_WINDOW_COUNT: Final[ContextVar[int]] = ContextVar("audit_upstream_window_count", default=0)+@dataclass(frozen=True, slots=True)class CallerResult:@@ -220,7 +222,11 @@ def _record_policy_request_count(count: int) -> None:def _record_upstream_request_count(count: int) -> None:- _AUDIT_UPSTREAM_REQUEST_COUNT.set(_AUDIT_UPSTREAM_REQUEST_COUNT.get() + count)+ _AUDIT_UPSTREAM_WINDOW_COUNT.set(count)+++def _upstream_request_count() -> int:+ return _AUDIT_UPSTREAM_REQUEST_COUNT.get() + _AUDIT_UPSTREAM_WINDOW_COUNT.get()@contextmanager@@ -906,7 +912,13 @@ def _decryption_only_changes_encrypted_values(stored: JsonValue, decrypted: Jsonreturn stored == decrypted-def _drain_upstream(upstream_url: str) -> tuple[dict[str, JsonValue], ...]:+def _reset_upstream(upstream_url: str) -> None:+ httpx.delete(f"{upstream_url.rstrip('/')}/__observations", trust_env=False, timeout=15).raise_for_status()+ _AUDIT_UPSTREAM_REQUEST_COUNT.set(_upstream_request_count())+ _AUDIT_UPSTREAM_WINDOW_COUNT.set(0)+++def _upstream_requests(upstream_url: str) -> tuple[dict[str, JsonValue], ...]:response: Final = httpx.get(f"{upstream_url.rstrip('/')}/__observations", trust_env=False, timeout=15)response.raise_for_status()requests: Final = object_value(JSON_OBJECT.validate_python(response.json())).get("requests")@@ -936,9 +948,9 @@ def _record_audit_properties(response_ids_token: Final = _AUDIT_RESPONSE_IDS.set(())policy_count_token: Final = _AUDIT_POLICY_REQUEST_COUNT.set(0)upstream_count_token: Final = _AUDIT_UPSTREAM_REQUEST_COUNT.set(0)+ upstream_window_token: Final = _AUDIT_UPSTREAM_WINDOW_COUNT.set(0)try:- response: Final = httpx.get(f"{gateway.upstream_url.rstrip('/')}/__observations", trust_env=False, timeout=15)- response.raise_for_status()+ _reset_upstream(gateway.upstream_url)yieldfinally:node_id: Final = request.node.nodeid@@ -947,10 +959,11 @@ def _record_audit_properties(record_property("inventory_id", inventory_ids[0] if inventory_ids else "support")record_property("response_ids", ",".join(_AUDIT_RESPONSE_IDS.get()))record_property("policy_edge_request_count", str(_AUDIT_POLICY_REQUEST_COUNT.get()))- record_property("upstream_request_count", str(_AUDIT_UPSTREAM_REQUEST_COUNT.get()))+ record_property("upstream_request_count", str(_upstream_request_count()))_AUDIT_RESPONSE_IDS.reset(response_ids_token)_AUDIT_POLICY_REQUEST_COUNT.reset(policy_count_token)_AUDIT_UPSTREAM_REQUEST_COUNT.reset(upstream_count_token)+ _AUDIT_UPSTREAM_WINDOW_COUNT.reset(upstream_window_token)def _policy_call_id_matches(payload: Mapping[str, JsonValue], call_id: str) -> bool:diff --git a/tests/integration/observability/test_guardrail_effects.py b/tests/integration/observability/test_guardrail_effects.pyindex b38ad2a3873..b3481057b3b 100644--- a/tests/integration/observability/test_guardrail_effects.py+++ b/tests/integration/observability/test_guardrail_effects.py@@ -227,7 +227,7 @@ def test_guardrail_denial_prevents_provider_and_preserves_allowed_control(gatewamodel: Final = scenario.model()key: Final = scenario.key(models=[model])with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()denied: Final = candidate.request("POST","/v1/chat/completions",@@ -1183,7 +1183,7 @@ def test_responses_pre_call_denial_streams_sse_with_typed_message_item(gateway:with owned_proxy(gateway, tmp_path, {}, config=config) as candidate, candidate.scenario() as scenario:model: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()response: Final = candidate.request("POST","/v1/responses",@@ -1225,7 +1225,7 @@ def test_responses_pre_call_denial_returns_json_with_typed_message_item(gateway:with owned_proxy(gateway, tmp_path, {}, config=config) as candidate, candidate.scenario() as scenario:model: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()response: Final = candidate.request("POST", "/v1/responses", {"model": model, "input": "say hi", "guardrails": [identity]})@@ -1397,7 +1397,7 @@ def test_responses_pre_call_denial_stream_event_vocabulary(gateway: Gateway, tmpwith owned_proxy(gateway, tmp_path, {}, config=config) as candidate, candidate.scenario() as scenario:model: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()response: Final = candidate.request("POST","/v1/responses",@@ -1453,7 +1453,7 @@ def test_responses_pre_call_denial_stream_requests_have_distinct_ids(gateway: Gawith owned_proxy(gateway, tmp_path, {}, config=config) as candidate, candidate.scenario() as scenario:model: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()responses: Final = tuple(candidate.request("POST",@@ -1589,7 +1589,7 @@ def test_responses_unguarded_stream_reaches_upstream(gateway: Gateway, tmp_path:assert denied.status_code == 200, denied.textmodel: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()response: Final = candidate.request("POST","/v1/responses",@@ -1936,7 +1936,7 @@ def test_responses_pre_call_denial_stream_survives_worker_burst(gateway: Gatewaymodel: Final = scenario.model(api_base=_dead_api_base())healthy: Final = scenario.model(use_chat_completions_api=True)with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as observed:- observed.get("/__observations")+ observed.delete("/__observations").raise_for_status()def burst(index: int) -> httpx.Response:if index % 3 == 0:diff --git a/tests/integration/observability/test_logging_only_scope_chaos.py b/tests/integration/observability/test_logging_only_scope_chaos.pyindex bc8f7bb9da2..c132e883349 100644--- a/tests/integration/observability/test_logging_only_scope_chaos.py+++ b/tests/integration/observability/test_logging_only_scope_chaos.py@@ -27,14 +27,15 @@ from _logging_only_scope_support import (_configuration,_direction,_directions_for_audit_leg,- _drain_upstream,_guardrail_entries,_is_base_audit_leg,_json_contains_exact_string,_policy_call_id_matches,+ _reset_upstream,_spend_rows,_spend_rows_for_calls,_spend_rows_matching_call,+ _upstream_requests,wire_server,)from _logging_only_scope_support import (@@ -42,10 +43,10 @@ from _logging_only_scope_support import ()from anthropic import APIConnectionError as AnthropicAPIConnectionErrorfrom integration._support.client import Gateway, eventually+from integration._support.ports import allocate_portfrom integration._support.process import owned_proxy, owned_proxy_processfrom integration._support.timing import Timed, assert_not_delayed_by, timedfrom integration._support.wire import Reply, Request-from integration._support.ports import allocate_portfrom openai import APIConnectionError as OpenAIAPIConnectionErrorfrom pydantic import JsonValue@@ -83,7 +84,7 @@ def test_K1_policy_edge_restart_mid_burst_keeps_output_observation_fail_open(gat)for call in chaos_calls)- control_upstream: Final = _drain_upstream(gateway.upstream_url)+ control_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(control_upstream) == 30, control_upstreamassert (tuple(@@ -92,6 +93,7 @@ def test_K1_policy_edge_restart_mid_burst_keeps_output_observation_fail_open(gat)== (1,) * 30), control_upstream+ _reset_upstream(gateway.upstream_url)config: Final = _configuration(tmp_path,identity,@@ -155,7 +157,7 @@ def test_K1_policy_edge_restart_mid_burst_keeps_output_observation_fail_open(gatassert all(result.text == controls[index].text for index, result in results), resultscandidate_ids: Final = tuple(result.response_id for _, result in results)assert len(set(candidate_ids)) == 30, candidate_ids- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 30, observed_upstreamassert (tuple(@@ -246,7 +248,7 @@ def test_K2_policy_edge_delay_does_not_delay_concurrent_callers(gateway: Gatewaywith ThreadPoolExecutor(max_workers=30) as control_pool:timed_controls: Final = tuple(control_pool.map(run_control, chaos_calls))controls: Final = tuple(control.value for control in timed_controls)- control_upstream: Final = _drain_upstream(gateway.upstream_url)+ control_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(control_upstream) == 30, control_upstreamassert (tuple(@@ -255,6 +257,7 @@ def test_K2_policy_edge_delay_does_not_delay_concurrent_callers(gateway: Gateway)== (1,) * 30), control_upstream+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as edge:config: Final = _configuration(tmp_path, identity, edge.url, "output", model_list=model_list)with owned_proxy(gateway, tmp_path, {}, config=config, workers=2) as candidate:@@ -306,7 +309,7 @@ def test_K2_policy_edge_delay_does_not_delay_concurrent_callers(gateway: Gateway), payloads_for_callresponse_ids: Final = tuple(result.response_id for _, result, _ in results)assert len(set(response_ids)) == 30, response_ids- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 30, upstreamassert (tuple(@@ -370,7 +373,8 @@ def test_K3_two_worker_sigkill_checks_post_kill_spend_rows()for call in calls)- assert len(_drain_upstream(gateway.upstream_url)) == 30+ assert len(_upstream_requests(gateway.upstream_url)) == 30+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as edge:config: Final = _configuration(tmp_path, identity, edge.url, "output", model_list=model_list)with owned_proxy_process(gateway, tmp_path, {}, config=config, workers=2) as owned:@@ -476,7 +480,7 @@ def test_K3_two_worker_sigkill_checks_post_kill_spend_rows(assert len(set(response_ids)) == len(response_ids), response_idsserved_calls: Final = tuple(call for call, _ in served)requested_call_ids: Final = frozenset(call.call_id for call in calls + post_kill_calls)- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert all(sum(_json_contains_exact_string(observation["body"], call.prompt) for observation in upstream) == 1for call in served_calls@@ -602,7 +606,7 @@ def test_K4_proxy_restart_after_fifteen_responses_records_lost_ids()for call in calls)- control_upstream: Final = _drain_upstream(gateway.upstream_url)+ control_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(control_upstream) == 30, control_upstreamassert (tuple(@@ -611,6 +615,7 @@ def test_K4_proxy_restart_after_fifteen_responses_records_lost_ids()== (1,) * 30), control_upstream+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as edge:config: Final = _configuration(tmp_path, identity, edge.url, "output", model_list=model_list)restart_gate: Final = threading.Event()@@ -711,7 +716,7 @@ def test_K4_proxy_restart_after_fifteen_responses_records_lost_ids(results: Final = first_results + second_resultsexpected_response_ids: Final = frozenset(result.response_id for result in results)assert len(expected_response_ids) == 30, results- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 30, upstreamassert (tuple(diff --git a/tests/integration/observability/test_logging_only_scope_config.py b/tests/integration/observability/test_logging_only_scope_config.pyindex 7c976ed25b3..0841c91f8ca 100644--- a/tests/integration/observability/test_logging_only_scope_config.py+++ b/tests/integration/observability/test_logging_only_scope_config.py@@ -20,7 +20,6 @@ from _logging_only_scope_support import (_delete_database_guardrail,_direction,_directions_for_audit_leg,- _drain_upstream,_empty_proxy_configuration,_guardrail_entries,_guardrail_mode_values,@@ -33,9 +32,11 @@ from _logging_only_scope_support import (_post_guardrail_body,_presidio_configuration,_provider_response,+ _reset_upstream,_response_body_without_ids,_spend_row_for_call_id,_spend_rows,+ _upstream_requests,wire_server,)from _logging_only_scope_support import (@@ -112,7 +113,7 @@ def test_G7_database_invalid_scope_reads_preserve_pre_call_blocking(gateway: Gat{"model": model, "messages": [{"role": "user", "content": prompt}]},)assert blocked_response.status_code == 400, blocked_response.text- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()finally:_delete_database_guardrail(identity)finally:@@ -157,7 +158,8 @@ def test_native_content_filter_scope_logs_without_blocking("openai_sync", "chat", gateway, model, prompt, False, f"{scenario_id}-baseline")assert baseline.status == 200 and baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)guarded: Final = _call_client("openai_sync", "chat", candidate, model, prompt, False, f"{scenario_id}-guarded")@@ -166,7 +168,7 @@ def test_native_content_filter_scope_logs_without_blocking(_response_body_without_ids(baseline.body),), (guarded, baseline)assert guarded.text == reply, guarded- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 1, observed_upstreamassert prompt in json.dumps(observed_upstream[0]["body"]), observed_upstreamrows: Final = _spend_rows(model, 2)@@ -252,7 +254,8 @@ def test_model_armor_directional_scope_uses_real_service_account_oauth("openai_sync", "chat", gateway, model, prompt, False, f"{scenario_id}-baseline")assert baseline.status == 200 and baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(oauth, policy_edge=False) as token_edge, wire_server(model_armor) as armor_edge:config: Final = _model_armor_configuration(tmp_path, identity, armor_edge.url, token_edge.url + "/token", scope@@ -266,7 +269,7 @@ def test_model_armor_directional_scope_uses_real_service_account_oauth(_response_body_without_ids(baseline.body),), (result, baseline)assert result.text == reply, result- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreameventually(lambda: armor_edge.received.qsize(),@@ -391,10 +394,11 @@ def test_presidio_scope_matches_no_scope_behavior(gateway: Gateway, tmp_path: Pa"openai_sync", "chat", no_scope_proxy, model, prompt, False, f"{scenario_id}-no-scope")assert no_scope_result.status == 200 and no_scope_result.text == reply, no_scope_result- no_scope_upstream: Final = _drain_upstream(gateway.upstream_url)+ no_scope_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(no_scope_upstream) == 1 and prompt in json.dumps(no_scope_upstream[0]["body"]), (no_scope_upstream)+ _reset_upstream(gateway.upstream_url)eventually(lambda: no_scope_analyzer_response_seen.is_set() and no_scope_anonymizer_response_seen.is_set(),bool,@@ -418,7 +422,7 @@ def test_presidio_scope_matches_no_scope_behavior(gateway: Gateway, tmp_path: Pano_scope_result.status,_response_body_without_ids(no_scope_result.body),), (scoped_result, no_scope_result)- scoped_upstream: Final = _drain_upstream(gateway.upstream_url)+ scoped_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(scoped_upstream) == 1 and prompt in json.dumps(scoped_upstream[0]["body"]), (scoped_upstream)@@ -549,7 +553,8 @@ def test_yaml_scope_loading_keeps_guardrail_enforcement()assert baseline.status_code == 200, baseline.textassert baseline.json()["choices"][0]["message"]["content"] == reply, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)guarded: Final = candidate.request("POST","/v1/chat/completions",@@ -558,7 +563,7 @@ def test_yaml_scope_loading_keeps_guardrail_enforcement()assert guarded.status_code == expected_status, guarded.textcaller_body: Final = JSON_OBJECT.validate_python(guarded.json())- candidate_upstream: Final = _drain_upstream(gateway.upstream_url)+ candidate_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(candidate_upstream) == (0 if expected_status == 400 else 1), candidate_upstreamif expected_status == 200:assert _response_body_without_ids(caller_body) == _response_body_without_ids(@@ -641,7 +646,8 @@ def test_database_guardrail_load_keeps_pre_call_blocking(headers={"x-litellm-call-id": f"{scenario_id}-baseline"},)assert baseline.status_code == 200, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:_insert_database_guardrail(identity, guardrail.url, scope)try:@@ -660,7 +666,7 @@ def test_database_guardrail_load_keeps_pre_call_blocking(headers={"x-litellm-call-id": call_id},)assert guarded.status_code == 400 and "synthetic DB denial" in guarded.text, guarded.text- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()payloads: Final = tuple(JSON_OBJECT.validate_json(call.body) for call in guardrail.drain())assert tuple(_direction(payload) for payload in payloads) == ("request",), payloadsassert _policy_call_id_matches(payloads[0], call_id), payloads@@ -704,7 +710,8 @@ def test_G6_database_guardrail_polling_normalizes_invalid_scope_without_reinitiaheaders={"x-litellm-call-id": f"{scenario_id}-baseline"},)assert baseline.status_code == 200, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(denial) as original_policy, wire_server(denial) as updated_policy:_insert_database_guardrail(identity, original_policy.url, None)try:@@ -790,7 +797,7 @@ def test_G6_database_guardrail_polling_normalizes_invalid_scope_without_reinitia)for entry in entries) == ((identity, "pre_call", "guardrail_intervened"),), (call_id, entries)- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()finally:_delete_database_guardrail(identity)finally:@@ -1059,7 +1066,7 @@ def test_H5_management_put_rejection_preserves_database_and_runtime(gateway: Gatafter_policy: Final = tuple(JSON_OBJECT.validate_json(call.body) for call in guardrail.drain())assert len(after_policy) == 1 and _policy_call_id_matches(after_policy[0], after_call_id), after_policyassert after_policy[0]["texts"] == [prompt], after_policy- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()for call_id in (before_call_id, after_call_id):entries: Final = _guardrail_entries(_spend_row_for_call_id(call_id))assert tuple(@@ -1135,7 +1142,7 @@ def test_H6_management_patch_clears_scope_when_switching_to_blocking_only_mode(assert tuple(_direction(call) for call in calls) == ("request",), callsassert _policy_call_id_matches(calls[0], call_id), callsassert calls[0]["texts"] == [prompt], calls- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()entries: Final = _guardrail_entries(_spend_row_for_call_id(call_id))assert tuple((@@ -1225,7 +1232,7 @@ def test_H7_management_patch_rejection_preserves_pre_call_guardrail(gateway: Gatassert _policy_call_id_matches(policy_after[0], after_call_id), policy_afterassert policy_before[0]["texts"] == [prompt], policy_beforeassert policy_after[0]["texts"] == [prompt], policy_after- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()for call_id in (before_call_id, after_call_id):entries: Final = _guardrail_entries(_spend_row_for_call_id(call_id))assert tuple(@@ -1272,7 +1279,8 @@ def test_management_patch_default_on_heals_stored_scope(headers={"x-litellm-call-id": f"{scenario_id}-baseline"},)assert baseline.status_code == 200, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:_insert_database_guardrail(identity,@@ -1316,7 +1324,7 @@ def test_management_patch_default_on_heals_stored_scope(assert tuple(_direction(call) for call in calls) == ("request",), callsassert _policy_call_id_matches(calls[0], call_id), callsassert calls[0]["texts"] == [prompt], calls- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()entries: Final = _guardrail_entries(_spend_row_for_call_id(call_id))assert tuple((entry["guardrail_name"], entry["guardrail_mode"], entry["guardrail_status"])@@ -1362,7 +1370,8 @@ def test_H10_management_patch_null_scope_restores_both_directions(gateway: Gatew)control: Final = _call_client("openai_sync", "chat", candidate, model, prompt, False, control_call_id)assert control.status == 200 and control.text == reply, control- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)created: Final = _create_guardrail(candidate,identity,@@ -1391,7 +1400,7 @@ def test_H10_management_patch_null_scope_restores_both_directions(gateway: Gatewcontrol.status,_response_body_without_ids(control.body),), (result, control)- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1, upstreamassert prompt in json.dumps(upstream[0]["body"]), upstreamexpected_directions: Final = ("request", "response")@@ -1451,7 +1460,8 @@ def test_H11_management_patch_same_scope_is_idempotent_and_output_only(gateway:)control: Final = _call_client("openai_sync", "chat", candidate, model, prompt, False, control_call_id)assert control.status == 200 and control.text == reply, control- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)created: Final = _create_guardrail(candidate,identity,@@ -1485,7 +1495,7 @@ def test_H11_management_patch_same_scope_is_idempotent_and_output_only(gateway:control.status,_response_body_without_ids(control.body),), (result, control)- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreameventually(lambda: guardrail.received.qsize(),@@ -1588,7 +1598,7 @@ def test_H13_unauthenticated_management_and_chat_requests_do_not_scan(gateway: Gassert unauthorized_chat.status_code == 401, unauthorized_chat.textassert _management_guardrail_rows(f"{identity}-unauthorized") == ()assert guardrail.drain() == ()- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()finally:delete_scenario(upstream_handle)@@ -1743,7 +1753,7 @@ def test_K5_yaml_flag_on_blocking_guardrail_boots_and_keeps_blocking(gateway: Gaheaders={"x-litellm-call-id": f"{scenario_id}-guarded"},)assert guarded.status_code == 400 and "synthetic yaml flag denial" in guarded.text, guarded.text- assert _drain_upstream(gateway.upstream_url) == ()+ assert _upstream_requests(gateway.upstream_url) == ()payloads: Final = tuple(JSON_OBJECT.validate_json(call.body) for call in guardrail.drain())assert tuple(_direction(payload) for payload in payloads) == ("request",), payloadslog_text: Final = owned.log.read_text()diff --git a/tests/integration/observability/test_logging_only_scope_runtime.py b/tests/integration/observability/test_logging_only_scope_runtime.pyindex 83bebb64960..8da26f20eae 100644--- a/tests/integration/observability/test_logging_only_scope_runtime.py+++ b/tests/integration/observability/test_logging_only_scope_runtime.py@@ -29,7 +29,6 @@ from _logging_only_scope_support import (_direction,_directions_for_audit_leg,_directions_for_scope,- _drain_upstream,_empty_proxy_configuration,_guardrail_entries,_guardrail_mode_status_pairs,@@ -38,6 +37,7 @@ from _logging_only_scope_support import (_policy_call_id,_policy_call_id_matches,_provider_response,+ _reset_upstream,_response_body_without_ids,_response_text,_spend_row_for_call_id,@@ -45,6 +45,7 @@ from _logging_only_scope_support import (_spend_rows,_spend_rows_for_calls,_spend_rows_matching_call,+ _upstream_requests,wire_server,)from _logging_only_scope_support import (@@ -150,10 +151,11 @@ def test_runtime_directional_scope_matches_client_call_and_spend_log(baseline: Final = _call_client(client_kind, endpoint, gateway, model, prompt, stream, baseline_call_id)- baseline_upstream: Final = _drain_upstream(gateway.upstream_url)+ baseline_upstream: Final = _upstream_requests(gateway.upstream_url)assert baseline.status == 200, baseline.bodyassert baseline.text == reply, baselineassert len(baseline_upstream) == 1, baseline_upstream+ _reset_upstream(gateway.upstream_url)result: Final = _call_client(client_kind, endpoint, candidate, model, prompt, stream, guarded_call_id)@@ -162,7 +164,7 @@ def test_runtime_directional_scope_matches_client_call_and_spend_log(_response_body_without_ids(baseline.body),), (result, baseline)assert result.text == reply, result- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 1, observed_upstreamassert prompt in json.dumps(observed_upstream[0]["body"]), observed_upstreambase_default_directions: Final = BASE_DEFAULT_NORMAL_DIRECTIONS[(endpoint, stream)]@@ -263,7 +265,8 @@ def test_A_unset_scope_matches_measured_endpoint_stream_default(f"{scenario_id}-baseline",)assert baseline.status == 200 and baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)result: Final = _call_client(client_kind,endpoint,@@ -278,7 +281,7 @@ def test_A_unset_scope_matches_measured_endpoint_stream_default(_response_body_without_ids(baseline.body),), (result, baseline)assert result.text == reply, result- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreamexpected_directions: Final = BASE_DEFAULT_NORMAL_DIRECTIONS[(endpoint, stream)]eventually(@@ -397,7 +400,7 @@ def test_logging_only_monitor_counts_only_the_observed_direction()for identity in (input_identity, output_identity))- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 4, observed_upstreamfor identity, baseline_response, guarded_response in cases:assert baseline_response.status_code == guarded_response.status_code == 200, (@@ -591,16 +594,18 @@ def test_cache_hit_directional_scope_uses_measured_base_default()assert baseline.status == 200, baseline.bodyassert baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)first: Final = _call_cache_client(endpoint, candidate, model, cached_prompt, f"{scenario_id}-first")assert (first.status, _response_body_without_ids(first.body)) == (baseline.status,_response_body_without_ids(baseline.body),), (first, baseline)assert first.text == reply, first- first_upstream: Final = _drain_upstream(gateway.upstream_url)+ first_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(first_upstream) == 1, first_upstreamassert cached_prompt in json.dumps(first_upstream[0]["body"]), first_upstream+ _reset_upstream(gateway.upstream_url)eventually(lambda: guardrail.received.qsize(),lambda count: count >= len(expected_miss_directions),@@ -617,7 +622,7 @@ def test_cache_hit_directional_scope_uses_measured_base_default(first.status,_response_body_without_ids(first.body),), (second, first)- assert _drain_upstream(gateway.upstream_url) == (), "The identical second request must hit Redis"+ assert _upstream_requests(gateway.upstream_url) == (), "The identical second request must hit Redis"rows: Final = _spend_rows(model, 3)eventually(lambda: guardrail.received.qsize(),@@ -738,7 +743,8 @@ def test_combined_modes_preserve_blocking_and_directional_observation()assert baseline.status_code == 200, baseline.textassert baseline.json()["choices"][0]["message"]["content"] == reply, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)guarded: Final = candidate.request("POST","/v1/chat/completions",@@ -756,7 +762,7 @@ def test_combined_modes_preserve_blocking_and_directional_observation(else expected_statuses)assert guarded.status_code == expected_status, guarded.text- candidate_upstream: Final = _drain_upstream(gateway.upstream_url)+ candidate_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(candidate_upstream) == (0 if row_id == "D1" else 1), candidate_upstreamif candidate_upstream:assert prompt in json.dumps(candidate_upstream[0]["body"]), candidate_upstream@@ -856,7 +862,8 @@ def test_logging_only_scope_respects_guardrail_selection_level()assert baseline.status_code == 200, baseline.textassert baseline.json()["choices"][0]["message"]["content"] == reply, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)guarded: Final = candidate.request("POST","/v1/chat/completions",@@ -868,7 +875,7 @@ def test_logging_only_scope_respects_guardrail_selection_level(assert _response_body_without_ids(JSON_OBJECT.validate_python(guarded.json())) == (_response_body_without_ids(JSON_OBJECT.validate_python(baseline.json()))), (guarded.text, baseline.text)- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 1, observed_upstreamassert prompt in json.dumps(observed_upstream[0]["body"]), observed_upstreamexpected_directions: Final = _directions_for_audit_leg(("request", "response"), scope)@@ -923,7 +930,8 @@ def test_X1_missing_and_null_scope_have_identical_scans(gateway: Gateway, tmp_paassert baseline.status_code == 200, baseline.textbaseline_body: Final = JSON_OBJECT.validate_json(baseline.content)baseline_reply: Final = _response_text("chat", baseline_body)- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)for suffix, scope, include_scope in variants:name: Final = f"{identity}-{suffix}"call_id: Final = f"{identity}-{suffix}"@@ -951,8 +959,9 @@ def test_X1_missing_and_null_scope_have_identical_scans(gateway: Gateway, tmp_pabody: Final = JSON_OBJECT.validate_json(response.content)assert body["choices"] == baseline_body["choices"], response.textassert _response_text("chat", body) == baseline_reply, response.text- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and identity in json.dumps(upstream[0]["body"]), upstream+ _reset_upstream(gateway.upstream_url)expected_directions: Final = _directions_for_audit_leg(("request", "response"), scope)eventually(lambda: edge.received.qsize(),@@ -992,7 +1001,8 @@ def test_X3_five_identical_requests_each_receive_one_response_scan(gateway: Gateheaders={"x-litellm-call-id": f"{identity}-baseline"},)assert baseline.status_code == 200, baseline.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as edge:config: Final = _configuration(tmp_path, identity, edge.url, "output")with owned_proxy(gateway, tmp_path, {}, config=config, workers=1) as candidate:@@ -1010,7 +1020,7 @@ def test_X3_five_identical_requests_each_receive_one_response_scan(gateway: Gateassert all(result.json()["choices"] == baseline.json()["choices"] for result in results), resultsresponse_ids: Final = tuple(str(result.json()["id"]) for result in results)assert len(set(response_ids)) == 5, response_ids- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 5, upstreameventually(lambda: edge.received.qsize(),@@ -1083,7 +1093,8 @@ def test_X2_scope_patch_toggles_during_concurrent_requests_keep_one_scan_per_res"openai_sync", "chat", gateway, model, f"synthetic X2 control {marker}", False, f"{marker}-control")assert baseline.status == 200, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as edge:config: Final = _empty_proxy_configuration(tmp_path, identity)with (@@ -1163,7 +1174,7 @@ def test_X2_scope_patch_toggles_during_concurrent_requests_keep_one_scan_per_respayload["texts"] == ([call.prompt] if _direction(payload) == "request" else [baseline.text])for payload in payloads_for_call), payloads_for_call- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 20, upstreamassert (tuple(@@ -1210,7 +1221,8 @@ def test_S1_logging_only_output_scope_fails_open_on_policy_500(gateway: Gateway,)control: Final = _call_client("openai_sync", "chat", gateway, model, prompt, False, control_call_id)assert control.status == 200 and control.text == reply, control- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:config: Final = _configuration(tmp_path, identity, guardrail.url, "output")with owned_proxy(gateway, tmp_path, {}, config=config, workers=1) as candidate:@@ -1223,7 +1235,7 @@ def test_S1_logging_only_output_scope_fails_open_on_policy_500(gateway: Gateway,), (result, control)expected_directions: Final = _directions_for_scope(("request", "response"), "output")directions_to_collect: Final = _directions_for_audit_leg(("request", "response"), "output")- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreameventually(lambda: guardrail.received.qsize(),@@ -1301,7 +1313,8 @@ def test_S2_logging_only_output_scope_scans_both_chat_choices(gateway: Gateway,)assert control.status_code == 200, control.textassert len(control.json()["choices"]) == 2, control.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:config: Final = _configuration(tmp_path, identity, guardrail.url, "output")with owned_proxy(gateway, tmp_path, {}, config=config, workers=1) as candidate:@@ -1315,7 +1328,7 @@ def test_S2_logging_only_output_scope_scans_both_chat_choices(gateway: Gateway,assert _response_body_without_ids(JSON_OBJECT.validate_python(result.json())) == (_response_body_without_ids(JSON_OBJECT.validate_python(control.json()))), (result.text, control.text)- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreamexpected_directions: Final = ("response",)eventually(@@ -1432,12 +1445,13 @@ def test_logging_only_scope_on_upstream_401_uses_measured_base_default(},timeout=60,)- control_upstream: Final = _drain_upstream(gateway.upstream_url)+ control_upstream: Final = _upstream_requests(gateway.upstream_url)control_upstream_count: Final = len(control_upstream)record_property("s3_control_upstream_request_count", control_upstream_count)assert control_upstream_count >= 1, control_upstreamassert control.status_code >= 400, control.textassert all(prompt in json.dumps(observation["body"]) for observation in control_upstream), control_upstream+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:config: Final = _configuration(tmp_path, identity, guardrail.url, scope)with owned_proxy(gateway, tmp_path, {}, config=config, workers=1) as candidate:@@ -1451,7 +1465,7 @@ def test_logging_only_scope_on_upstream_401_uses_measured_base_default(},timeout=60,)- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)upstream_count: Final = len(upstream)record_property("s3_candidate_upstream_request_count", upstream_count)assert upstream_count >= 1, upstream@@ -1519,7 +1533,8 @@ def test_S4_logging_only_input_scope_scans_every_multipart_text_part(gateway: Ga)assert control.status_code == 200, control.textassert control.json()["choices"][0]["message"]["content"] == reply, control.text- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)with wire_server(policy) as guardrail:config: Final = _configuration(tmp_path, identity, guardrail.url, "input")with owned_proxy(gateway, tmp_path, {}, config=config, workers=1) as candidate:@@ -1533,7 +1548,7 @@ def test_S4_logging_only_input_scope_scans_every_multipart_text_part(gateway: Gaassert _response_body_without_ids(JSON_OBJECT.validate_python(result.json())) == (_response_body_without_ids(JSON_OBJECT.validate_python(control.json()))), (result.text, control.text)- observed_upstream: Final = _drain_upstream(gateway.upstream_url)+ observed_upstream: Final = _upstream_requests(gateway.upstream_url)assert len(observed_upstream) == 1, observed_upstreamassert first_part in json.dumps(observed_upstream[0]["body"]), observed_upstreamassert second_part in json.dumps(observed_upstream[0]["body"]), observed_upstream@@ -1627,7 +1642,8 @@ def test_continue_on_input_failure_observes_flagged_input_and_response("openai_sync", "chat", gateway, model, prompt, False, f"{scenario_id}-baseline")assert baseline.status == 200 and baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)result: Final = _call_client("openai_sync", "chat", candidate, model, prompt, False, guarded_call_id)@@ -1636,7 +1652,7 @@ def test_continue_on_input_failure_observes_flagged_input_and_response(_response_body_without_ids(baseline.body),), (result, baseline)assert result.text == reply, result- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreameventually(lambda: guardrail.received.qsize(),@@ -1730,7 +1746,8 @@ def test_continue_on_input_failure_recovers_from_raising_input_scan("openai_sync", "chat", gateway, model, prompt, False, f"{scenario_id}-baseline")assert baseline.status == 200 and baseline.text == reply, baseline- assert len(_drain_upstream(gateway.upstream_url)) == 1+ assert len(_upstream_requests(gateway.upstream_url)) == 1+ _reset_upstream(gateway.upstream_url)result: Final = _call_client("openai_sync", "chat", candidate, model, prompt, False, guarded_call_id)@@ -1739,7 +1756,7 @@ def test_continue_on_input_failure_recovers_from_raising_input_scan(_response_body_without_ids(baseline.body),), (result, baseline)assert result.text == reply, result- upstream: Final = _drain_upstream(gateway.upstream_url)+ upstream: Final = _upstream_requests(gateway.upstream_url)assert len(upstream) == 1 and prompt in json.dumps(upstream[0]["body"]), upstreameventually(lambda: guardrail.received.qsize(),diff --git a/tests/integration/observability/test_presidio_entity_masking.py b/tests/integration/observability/test_presidio_entity_masking.pyindex 843afb51c5c..ab966873389 100644--- a/tests/integration/observability/test_presidio_entity_masking.py+++ b/tests/integration/observability/test_presidio_entity_masking.py@@ -169,7 +169,7 @@ def test_pre_call_masks_only_the_configured_entities_before_the_provider_sees_thhttpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):model: Final = scenario.model()- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()user_text: Final = f"{uuid.uuid4().hex} card {CARD}, email {EMAIL}, phone {PHONE}"response: Final = gateway.request("POST",diff --git a/tests/integration/pricing/test_configured_prices.py b/tests/integration/pricing/test_configured_prices.pyindex 8e97c9c8322..acf6a68879b 100644--- a/tests/integration/pricing/test_configured_prices.py+++ b/tests/integration/pricing/test_configured_prices.py@@ -424,7 +424,7 @@ def test_block_requests_for_models_without_pricing_refuses_unpriced_deployments(assert unpriced_model_info["input_cost_per_token"] is None, unpriced_model_infoassert unpriced_model_info["output_cost_per_token"] is None, unpriced_model_info- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()blocked: Final = _bounded_chat(gateway, unpriced, key, f"unpriced {uuid.uuid4().hex}")assert blocked.status_code == 403, blocked.textassert blocked.json() == {@@ -454,7 +454,7 @@ def test_block_requests_for_models_without_pricing_refuses_unpriced_deployments()disabled_settings: Final = object_value(settings_rows[0]["param_value"])assert disabled_settings["block_requests_for_models_without_pricing"] is False, disabled_settings- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()unpriced_content: Final = f"unpriced {uuid.uuid4().hex}"now_served: Final = _bounded_chat(gateway, unpriced, key, unpriced_content)assert now_served.status_code == 200, now_served.textdiff --git a/tests/integration/pricing/test_cost_margin_discount.py b/tests/integration/pricing/test_cost_margin_discount.pyindex bfd2002f871..b6cda8f125f 100644--- a/tests/integration/pricing/test_cost_margin_discount.py+++ b/tests/integration/pricing/test_cost_margin_discount.py@@ -63,7 +63,7 @@ def _upstream_chat(content: str, streamed: bool) -> dict[str, JsonValue]:def _chat_cost(gateway: Gateway, upstream: httpx.Client, model: str, key: str, expected: float) -> str:content: Final = f"margin {uuid.uuid4().hex}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -79,7 +79,7 @@ def _chat_cost(gateway: Gateway, upstream: httpx.Client, model: str, key: str, edef _streamed_chat(gateway: Gateway, upstream: httpx.Client, model: str, key: str) -> str:content: Final = f"margin stream {uuid.uuid4().hex}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -301,7 +301,7 @@ def test_streamed_response_cost_header_matches_billed_spend(gateway: Gateway) ->"Cost margin configuration updated successfully",)content: Final = f"margin stream header {uuid.uuid4().hex}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",diff --git a/tests/integration/pricing/test_per_second_pricing.py b/tests/integration/pricing/test_per_second_pricing.pyindex 144d05fdcc3..b7c8cf27a17 100644--- a/tests/integration/pricing/test_per_second_pricing.py+++ b/tests/integration/pricing/test_per_second_pricing.py@@ -64,8 +64,8 @@ def _stream_content(event: dict[str, JsonValue]) -> str:def _clear_observations(upstream: httpx.Client) -> None:- response: Final = upstream.get("/__observations")- assert response.status_code == 200, response.text+ response: Final = upstream.delete("/__observations")+ assert response.status_code == 204, response.textdef _observed_request_body(upstream: httpx.Client) -> dict[str, JsonValue]:diff --git a/tests/integration/pricing/test_service_tier_pricing.py b/tests/integration/pricing/test_service_tier_pricing.pyindex 43c021c4c16..ef194ed59b0 100644--- a/tests/integration/pricing/test_service_tier_pricing.py+++ b/tests/integration/pricing/test_service_tier_pricing.py@@ -22,7 +22,7 @@ def assert_chat_bills_rates(gateway: Gateway, model: str, service_tier: str | None, input_rate: float, output_rate: float) -> None:with httpx.Client(base_url=gateway.upstream_url, trust_env=False) as upstream:- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -223,7 +223,7 @@ def test_ultrafast_long_context_prompt_bills_ultrafast_long_context_rates()request_path, request_body, expected_upstream_path = _surface_request(surface, scenario_id, model, service_tier)with httpx.Client(base_url=gateway.upstream_url, trust_env=False) as upstream:- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST",request_path,diff --git a/tests/integration/providers/test_databricks_decisions_wire.py b/tests/integration/providers/test_databricks_decisions_wire.pyindex d96d6ab1be1..02e9d4f5dfc 100644--- a/tests/integration/providers/test_databricks_decisions_wire.py+++ b/tests/integration/providers/test_databricks_decisions_wire.py@@ -106,6 +106,11 @@ def _observed(gateway: Gateway) -> tuple[dict[str, JsonValue], ...]:return tuple(map(object_value, upstream.get("/__observations").json()["requests"]))+def _reset_observations(gateway: Gateway) -> None:+ with httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream:+ upstream.delete("/__observations").raise_for_status()++def _calls_to(requests: Sequence[dict[str, JsonValue]], handle: ScenarioHandle) -> list[dict[str, JsonValue]]:return [request for request in requests if string_value(request["path"]).startswith(f"/{handle.scenario_id}/")]@@ -545,6 +550,7 @@ def test_the_environment_key_and_base_serve_a_deployment_a_classifier_and_a_team_spend_row(decided[1].headers["x-litellm-call-id"])["api_base"]== f"{handle.api_base()}/environment-workspace{_ROUTE}")+ _reset_observations(candidate)router: Final = _router(scenario, _environment_classifier())routed: Final = _chat(candidate, router)@@ -556,6 +562,7 @@ def test_the_environment_key_and_base_serve_a_deployment_a_classifier_and_a_teamauthorization=f"Bearer {_ENV_KEY}",prompt_marker="design a distributed cache",)+ _reset_observations(candidate)team: Final = scenario.team(team_member_permissions=["/auto_router/manage"])member: Final = scenario.member(team)@@ -623,6 +630,7 @@ def test_the_environment_token_serves_a_deployment_and_a_classifier_when_no_envi(decision_call,) = _upstream_calls(candidate, handle)assert (decision_call["path"], decision_call["authorization"]) == (environment_path, f"Bearer {_ENV_TOKEN}")assert _spend_row(decided.headers["x-litellm-call-id"])["status"] == "success"+ _reset_observations(candidate)router: Final = _router(scenario, _environment_classifier())routed: Final = _chat(candidate, router)_assert_classified_by_the_complex_tier(routed, router)diff --git a/tests/integration/providers/test_decision_model_guardrail.py b/tests/integration/providers/test_decision_model_guardrail.pyindex 67e6f0918d1..81bc0fe544f 100644--- a/tests/integration/providers/test_decision_model_guardrail.py+++ b/tests/integration/providers/test_decision_model_guardrail.py@@ -190,7 +190,7 @@ def test_decision_guardrail_resolves_the_callers_team_model(other_team: Final = scenario.team(models=[chat])other_key: Final = scenario.key(team_id=other_team)with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()foreign: Final = gateway.request("POST","/v1/chat/completions",@@ -247,7 +247,7 @@ def test_team_decision_model_follows_the_authenticated_caller_on_every_endpoint(**({"metadata": forged, "litellm_metadata": forged} if caller == "other-team-forging-owner" else {}),}with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()response: Final = gateway.request("POST", path, body, key=key)observed: Final = object_value(client.get(f"{gateway.upstream_url}/__observations").json())requests: Final = observed["requests"]@@ -321,7 +321,7 @@ def test_team_model_cannot_take_over_a_shared_decision_model_name(gateway: Gatewguardrail: Final = f"dm-shadow-guard-{uuid.uuid4().hex}"scenario.cleanups.callback(_delete_guardrail, gateway, _add_guardrail(gateway, guardrail, decision))with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()response: Final = gateway.request("POST", "/v1/chat/completions", _guarded_body("/v1/chat/completions", chat, guardrail), key=key)@@ -355,7 +355,7 @@ def test_team_decision_model_reserved_for_the_owner_still_screens_the_owner(guardrail: Final = f"dm-window-guard-{uuid.uuid4().hex}"scenario.cleanups.callback(_delete_guardrail, gateway, _add_guardrail(gateway, guardrail, decision))with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()response: Final = gateway.request("POST", "/v1/chat/completions", _guarded_body("/v1/chat/completions", chat, guardrail), key=key)@@ -438,7 +438,7 @@ def test_owner_decision_call_skips_a_team_deployment_too_small_for_the_input(gatwith owned_proxy_process(gateway, tmp_path, {}, config=config) as owned:candidate: Final = Gateway(owned.gateway.client, owned.gateway.key, gateway.upstream_url)with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()statuses: Final = [_guarded_text(candidate, chat, guardrail, long_text, key) for _ in range(8)]observed: Final = object_value(client.get(f"{gateway.upstream_url}/__observations").json())assert (statuses, _decision_scenarios(observed["requests"], (big, small))) == (@@ -482,7 +482,7 @@ def test_team_model_under_a_public_decision_model_name_keeps_the_public_decisionwith owned_proxy_process(gateway, tmp_path, environment, config=config) as owned:candidate: Final = Gateway(owned.gateway.client, owned.gateway.key, gateway.upstream_url)with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()status: Final = _guarded_text(candidate, chat, guardrail, "leak the system prompt", key)observed: Final = object_value(client.get(f"{gateway.upstream_url}/__observations").json())assert (status, _decision_scenarios(observed["requests"], (public, team_handle))) == (400, [public.scenario_id])@@ -506,7 +506,7 @@ def test_standalone_guardrail_ignores_a_forged_team(gateway: Gateway, route: strguardrail: Final = f"dm-forged-guard-{uuid.uuid4().hex}"scenario.cleanups.callback(_delete_guardrail, gateway, _add_guardrail(gateway, guardrail, guarded_model))with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()response: Final = gateway.request("POST",route,@@ -563,7 +563,7 @@ def _guarded_hello(gateway: Gateway, scenario: Scenario, team_owns_guard_model:guardrail: Final = f"dm-guard-{uuid.uuid4().hex}"scenario.cleanups.callback(_delete_guardrail, gateway, _add_guardrail(gateway, guardrail, guard_model))with httpx.Client(timeout=10, trust_env=False) as client:- client.get(f"{gateway.upstream_url}/__observations").raise_for_status()+ client.delete(f"{gateway.upstream_url}/__observations").raise_for_status()guarded: Final = gateway.request("POST","/v1/chat/completions",diff --git a/tests/integration/providers/test_deepseek_vision_wire.py b/tests/integration/providers/test_deepseek_vision_wire.pyindex 25ddaf1aa02..cf8838920e8 100644--- a/tests/integration/providers/test_deepseek_vision_wire.py+++ b/tests/integration/providers/test_deepseek_vision_wire.py@@ -17,7 +17,7 @@ _VISION_CONTENT: Final[JsonValue] = [@pytest.mark.covers("other.provider_wire.deepseek.vision_image_content_list_reaches_provider")def test_deepseek_vision_forwards_image_url_content_list_instead_of_collapsing_to_text(gateway: Gateway) -> None:with gateway.scenario() as scenario, httpx.Client(base_url=gateway.upstream_url, trust_env=False) as upstream:- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()model: Final = scenario.model(model=f"deepseek/{_VISION_MODEL}",api_key=_API_KEY,diff --git a/tests/integration/providers/test_provider_lookup_status.py b/tests/integration/providers/test_provider_lookup_status.pyindex a231e7df9e4..a526d0eb2f0 100644--- a/tests/integration/providers/test_provider_lookup_status.py+++ b/tests/integration/providers/test_provider_lookup_status.py@@ -159,7 +159,7 @@ class _ObservationBuffer:payload: Final = JSON_OBJECT.validate_python(client.get(f"{self._url}/__observations").json())requests: Final = payload.get("requests")assert isinstance(requests, list)- self._items = (*self._items, *(object_value(item) for item in requests if isinstance(item, dict)))+ self._items = tuple(object_value(item) for item in requests if isinstance(item, dict))return self._itemsdef route(self, scenario_id: str, suffix: str) -> tuple[dict[str, JsonValue], ...]:diff --git a/tests/integration/providers/test_realtime_transcription_guardrail_session_update.py b/tests/integration/providers/test_realtime_transcription_guardrail_session_update.pyindex ba2261e5a1f..ad58a400cec 100644--- a/tests/integration/providers/test_realtime_transcription_guardrail_session_update.py+++ b/tests/integration/providers/test_realtime_transcription_guardrail_session_update.py@@ -719,6 +719,13 @@ def _observed_all(upstream_url: str) -> tuple[dict[str, JsonValue], ...]:return tuple(map(object_value, upstream.get("/__observations").json()["requests"]))+def _reset_observations(upstream_url: str) -> None:+ with httpx.Client(+ base_url=upstream_url, timeout=5, trust_env=False, verify=not upstream_url.startswith("https://")+ ) as upstream:+ upstream.delete("/__observations").raise_for_status()++def _belonging(observed: tuple[dict[str, JsonValue], ...], scenario_id: str) -> tuple[dict[str, JsonValue], ...]:return tuple(request for request in observed if _belongs(request, scenario_id))@@ -2549,6 +2556,7 @@ def test_worker_kill_then_proxy_restart_keep_transcription_sessions_uninjected(before_the_kill: Final = _observed(gateway.upstream_url, handle.scenario_id)assert set(_sent_types(before_the_kill)) <= {"session.update", "input_audio_buffer.commit"}, before_the_killassert set(map(json.dumps, _session_updates(before_the_kill))) == {json.dumps(GA_TRANSCRIPTION_UPDATE)}+ _reset_observations(gateway.upstream_url)after_kill: Final = _transcribe(_ws_base(owned_url), f"model={model}&{TRANSCRIPTION_QUERY}", key)_assert_transcription_left_alone(after_kill,@@ -2556,6 +2564,7 @@ def test_worker_kill_then_proxy_restart_keep_transcription_sessions_uninjected(CLEAN_TRANSCRIPT,update=GA_TRANSCRIPTION_UPDATE,)+ _reset_observations(gateway.upstream_url)blocked_on_the_survivor: Final = _transcribe_blocked(_ws_base(owned_url), f"model={blocked_model_after_kill}&{TRANSCRIPTION_QUERY}", key)diff --git a/tests/integration/providers/test_request_boundary.py b/tests/integration/providers/test_request_boundary.pyindex 33663cd4c59..fccd858c7c8 100644--- a/tests/integration/providers/test_request_boundary.py+++ b/tests/integration/providers/test_request_boundary.py@@ -9,7 +9,7 @@ from tests.integration._support.client import Gateway, JSON_OBJECT, object_value@pytest.mark.covers("other.provider_wire.internal_parameters_filtered")def test_internal_request_state_does_not_reach_provider(gateway: Gateway) -> None:with gateway.scenario() as scenario, httpx.Client(base_url=gateway.upstream_url, trust_env=False) as upstream:- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()model: Final = scenario.model()key: Final = scenario.key(models=[model], tpm_limit=10000, rpm_limit=100)result: Final = gateway.post(diff --git a/tests/integration/providers/test_xai_batch_output_file_wire.py b/tests/integration/providers/test_xai_batch_output_file_wire.pyindex aa958cd01af..c21663fa53d 100644--- a/tests/integration/providers/test_xai_batch_output_file_wire.py+++ b/tests/integration/providers/test_xai_batch_output_file_wire.py@@ -220,11 +220,10 @@ def test_xai_batch_output_file_is_sized_by_the_batch_job_and_never_downloaded_orraw_batch_id,len(content.content),), listed_output- assert _results_reads(gateway, batch, raw_batch_id) == settled_reads-- file_lookups: Final = tuple(- path for path in _upstream_paths(gateway, batch.upstream.scenario_id) if "/v1/files/batch_" in path- )+ upstream_paths: Final = _upstream_paths(gateway, batch.upstream.scenario_id)+ results_reads: Final = sum(path.endswith(f"/{raw_batch_id}/results") for path in upstream_paths)+ assert results_reads == settled_reads > 0, upstream_paths+ file_lookups: Final = tuple(path for path in upstream_paths if "/v1/files/batch_" in path)assert file_lookups == (), f"xAI batch id was looked up as a file: {file_lookups}"diff --git a/tests/integration/routing/test_end_user_region_routing.py b/tests/integration/routing/test_end_user_region_routing.pyindex d8ba2da042a..ce90280f173 100644--- a/tests/integration/routing/test_end_user_region_routing.py+++ b/tests/integration/routing/test_end_user_region_routing.py@@ -73,7 +73,7 @@ def test_an_end_users_allowed_region_pins_every_call_to_that_regions_deployment(candidate.post("/end_user/new", {"user_id": end_user, "allowed_model_region": region})scenario.cleanups.callback(candidate.post, "/end_user/delete", {"user_ids": [end_user]})key: Final = scenario.key(models=[MODEL])- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()responses: Final = tuple(candidate.request("POST",@@ -134,7 +134,7 @@ def test_an_uncountable_prompt_still_pins_an_end_user_to_their_region(candidate.post("/end_user/new", {"user_id": end_user, "allowed_model_region": PINNED_REGION})scenario.cleanups.callback(candidate.post, "/end_user/delete", {"user_ids": [end_user]})key: Final = scenario.key(models=[UNCOUNTABLE_MODEL])- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()requests: Final = tuple(build(uuid.uuid4().hex, end_user) for _ in range(CALLS))responses: Final = tuple(candidate.request("POST", path, body, key=key) for path, body in requests)assert [response.status_code for response in responses] == [200] * CALLS, [r.text for r in responses]diff --git a/tests/integration/routing/test_key_max_parallel_requests.py b/tests/integration/routing/test_key_max_parallel_requests.pyindex cddc70f1475..e0178da4352 100644--- a/tests/integration/routing/test_key_max_parallel_requests.py+++ b/tests/integration/routing/test_key_max_parallel_requests.py@@ -13,7 +13,7 @@ def test_zero_parallel_slots_refuse_before_the_provider_and_one_slot_serves(gatemodel: Final = scenario.model()blocked: Final = scenario.key(models=[model], max_parallel_requests=0)allowed: Final = scenario.key(models=[model], max_parallel_requests=1)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()refused: Final = gateway.request("POST","/v1/chat/completions",diff --git a/tests/integration/routing/test_observed_routing.py b/tests/integration/routing/test_observed_routing.pyindex 673aa54fb78..ca5f248e0de 100644--- a/tests/integration/routing/test_observed_routing.py+++ b/tests/integration/routing/test_observed_routing.py@@ -47,7 +47,7 @@ def test_retry_counts_and_public_errors_match_actual_provider_attempts(gateway:gateway.post("/config/update", {"router_settings": {"num_retries": retries}})assert object_value(gateway.get("/router/settings")["current_values"])["num_retries"] == retriesupstream.post(f"/__scripts/{provider_model}", json={"statuses": statuses}).raise_for_status()- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -179,7 +179,7 @@ def test_saved_deployment_target_update_changes_wire_and_preserves_control(gatew{"litellm_params": {"model": "openai/" + prefix + "-second"}},)assert response.status_code == 200, response.text- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()for alias in (model, other):assert gateway.chat(alias, text=f"{prefix} generation {generation}")["usage"]["total_tokens"] == 40requests: Final = upstream.get("/__observations").json()["requests"]diff --git a/tests/integration/routing/test_pre_call_response_format_filter.py b/tests/integration/routing/test_pre_call_response_format_filter.pyindex 24a4434fb5a..e1fb9b55541 100644--- a/tests/integration/routing/test_pre_call_response_format_filter.py+++ b/tests/integration/routing/test_pre_call_response_format_filter.py@@ -76,7 +76,7 @@ def _json_mode_chat(group: str, text: str, **extra: JsonValue) -> dict[str, Json}-def _drain(upstream: httpx.Client) -> list[dict[str, JsonValue]]:+def _observed_bodies(upstream: httpx.Client) -> list[dict[str, JsonValue]]:response: Final = upstream.get("/__observations")response.raise_for_status()return [request["body"] for request in response.json()["requests"]]@@ -85,7 +85,7 @@ def _drain(upstream: httpx.Client) -> list[dict[str, JsonValue]]:@pytest.fixturedef upstream(candidate: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=candidate.upstream_url, timeout=5, trust_env=False) as client:- _drain(client)+ client.delete("/__observations").raise_for_status()yield client@@ -98,7 +98,7 @@ def test_json_mode_answers_400_without_an_upstream_call_when_no_deployment_takes)assert response.status_code == 400, response.text- assert _drain(upstream) == []+ assert _observed_bodies(upstream) == []@pytest.mark.parametrize(@@ -121,7 +121,7 @@ def test_json_mode_reaches_a_deployment_that_lacks_it_once_drop_or_allow_is_set()assert response.status_code == 200, response.text- received: Final = _drain(upstream)+ received: Final = _observed_bodies(upstream)assert [body["model"] for body in received] == [LACKS_JSON_MODE]assert received[0].get("response_format") == forwarded_format@@ -135,7 +135,7 @@ def test_json_mode_in_a_mixed_group_always_reaches_the_deployment_that_takes_it()assert [response.status_code for response in responses] == [200] * CALLS, [r.text for r in responses]- received: Final = _drain(upstream)+ received: Final = _observed_bodies(upstream)assert [(body["model"], body.get("response_format")) for body in received] == [(TAKES_JSON_MODE, dict(JSON_MODE))] * CALLS@@ -156,6 +156,6 @@ def test_json_mode_falls_back_to_a_group_that_takes_it()assert response.status_code == 200, response.text- assert [(body["model"], body.get("response_format")) for body in _drain(upstream)] == [+ assert [(body["model"], body.get("response_format")) for body in _observed_bodies(upstream)] == [(TAKES_JSON_MODE, dict(JSON_MODE))]diff --git a/tests/integration/routing/test_redis_recovery.py b/tests/integration/routing/test_redis_recovery.pyindex 9b41d44926f..735299b02f0 100644--- a/tests/integration/routing/test_redis_recovery.py+++ b/tests/integration/routing/test_redis_recovery.py@@ -33,7 +33,7 @@ def test_owned_redis_outage_recovers_requests_and_real_response_cache(gateway: Gwith Redis(host=cache.host, port=cache.port, socket_timeout=1) as client:eventually(client.ping, bool)eventually(lambda: client.pubsub_numsub("litellm_proxy.auth_cache_invalidation")[0][1], lambda count: count >= 1, seconds=8)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()first: Final = candidate.chat(model, key=key, text=identity + generation)second: Final = candidate.chat(model, key=key, text=identity + generation)assert first["id"] == second["id"]@@ -47,7 +47,7 @@ def test_owned_redis_outage_recovers_requests_and_real_response_cache(gateway: G)if generation == "before":cache.stop()- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()during: Final = candidate.chat(model, key=key, text=identity + "during")assert during["usage"]["total_tokens"] == 40assert len(upstream.get("/__observations").json()["requests"]) == 1diff --git a/tests/integration/routing/test_stale_cost_map_boot.py b/tests/integration/routing/test_stale_cost_map_boot.pyindex 13b3d777587..8ae7290edbe 100644--- a/tests/integration/routing/test_stale_cost_map_boot.py+++ b/tests/integration/routing/test_stale_cost_map_boot.py@@ -70,7 +70,7 @@ def test_config_deployment_dropped_by_stale_boot_cost_map_is_restored_after_relolambda served: model in served,seconds=30,)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = candidate.request("POST","/v1/chat/completions",diff --git a/tests/integration/routing/test_team_tag_routing.py b/tests/integration/routing/test_team_tag_routing.pyindex 88e89a37c52..f5f95ff8667 100644--- a/tests/integration/routing/test_team_tag_routing.py+++ b/tests/integration/routing/test_team_tag_routing.py@@ -49,7 +49,7 @@ def test_a_teams_tags_route_every_call_of_its_keys_to_the_matching_deployment(ca):team_id: Final = scenario.team(tags=[tag])key: Final = scenario.key(team_id=team_id)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()responses: Final = tuple(candidate.request("POST",diff --git a/tests/integration/spend/_background_responses.py b/tests/integration/spend/_background_responses.pyindex ac044dedc9c..e5b5022ea4a 100644--- a/tests/integration/spend/_background_responses.py+++ b/tests/integration/spend/_background_responses.py@@ -317,8 +317,7 @@ def calls_to(requests: Sequence[dict[str, JsonValue]], handle: ScenarioHandle) -def upstream_log(gateway: Gateway, handle: ScenarioHandle) -> Iterator[tuple[dict[str, JsonValue], ...]]:- fresh: Final = (calls_to(observed_requests(gateway), handle) for _ in itertools.count())- return itertools.accumulate(fresh, lambda seen, calls: (*seen, *calls))+ return (calls_to(observed_requests(gateway), handle) for _ in itertools.count())def submissions(log: Sequence[dict[str, JsonValue]], handle: ScenarioHandle) -> tuple[JsonValue, ...]:diff --git a/tests/integration/spend/test_background_interaction_settlement.py b/tests/integration/spend/test_background_interaction_settlement.pyindex ca18ba8a96a..c7b70ed5c32 100644--- a/tests/integration/spend/test_background_interaction_settlement.py+++ b/tests/integration/spend/test_background_interaction_settlement.py@@ -394,7 +394,11 @@ def _await_key_spend(replica: Gateway, key: str, expected: float) -> None:eventually(lambda: _key_spend(replica, key), lambda spend: math.isclose(spend, expected, rel_tol=1e-9), seconds=30)-def _drain(rig: Rig) -> list[JsonValue]:+def _reset_observations(rig: Rig) -> None:+ httpx.delete(f"{rig.upstream.url}/__observations", trust_env=False, timeout=15).raise_for_status()+++def _observations(rig: Rig) -> list[JsonValue]:observed: Final = httpx.get(f"{rig.upstream.url}/__observations", trust_env=False, timeout=15)observed.raise_for_status()requests: Final = JSON_OBJECT.validate_json(observed.content)["requests"]@@ -406,7 +410,7 @@ def _calls(rig: Rig, *interaction_ids: str) -> tuple[tuple[str, str], ...]:suffixes: Final = tuple(f"/v1beta/interactions/{interaction_id}" for interaction_id in interaction_ids)return tuple((string_value(object_value(entry)["method"]), string_value(object_value(entry)["api_key"]))- for entry in _drain(rig)+ for entry in _observations(rig)if string_value(object_value(entry)["path"]).endswith(suffixes))@@ -475,7 +479,7 @@ def test_delete_on_another_replica_bills_the_creators_interaction_once(rig: Rig,key: Final = scenario.key()created: Final = _create(rig.creator, model, key, path=path)_state(rig, created, _completed())- _drain(rig)+ _reset_observations(rig)deleted: Final = _delete(rig.settler, created, key, path=path)assert deleted.status_code == 200, deleted.textspend: Final = _assert_billed(_await_spend_row(created), _rates(rig.creator, model))@@ -623,7 +627,7 @@ def test_a_late_restart_retries_a_failed_fetch_within_a_full_poll_window(rig: Ri_registered(created)write_rows(_CREATED_AN_HOUR_AGO, (created,))_state(rig, created, InteractionState(status="completed", usage=_USAGE, get_status=503))- _drain(rig)+ _reset_observations(rig)with owned_proxy_process(rig.gateway, rig.directory, rig.environment(**_LATE_RESUMER_POLL), config=rig.config, workers=2):@@ -668,13 +672,13 @@ def test_cancel_then_delete_on_another_replica_releases_without_a_spend_row(rig:key: Final = scenario.key()created: Final = _create(rig.creator, model, key)_state(rig, created, InteractionState(status="in_progress"))- _drain(rig)+ _reset_observations(rig)cancelled: Final = rig.settler.request("POST", f"/v1beta/interactions/{created}/cancel", {}, key=key)assert cancelled.status_code == 200, cancelled.textassert JSON_OBJECT.validate_json(cancelled.content)["status"] == "cancelled", cancelled.textposted: Final = tuple(string_value(object_value(entry)["path"])- for entry in _drain(rig)+ for entry in _observations(rig)if string_value(object_value(entry)["method"]) == "POST")assert len(posted) == 1 and posted[0].endswith(f"/v1beta/interactions/{created}/cancel"), posted@@ -692,7 +696,7 @@ def test_delete_fails_closed_when_the_settling_replica_cannot_fetch(rig: Rig) ->key: Final = scenario.key()created: Final = _create(rig.creator, model, key)_state(rig, created, InteractionState(status="completed", usage=_USAGE, get_status=500))- _drain(rig)+ _reset_observations(rig)refused: Final = _delete(rig.settler, created, key)assert refused.status_code >= 500, refused.textassert "Scripted interaction fetch failure" in refused.text, refused.text@@ -712,7 +716,7 @@ def test_delete_of_an_interaction_the_vendor_purged_sends_no_delete_and_keeps_thkey: Final = scenario.key()created: Final = _create(rig.creator, model, key)clear_interaction_state(rig.upstream.url, created)- _drain(rig)+ _reset_observations(rig)deleted: Final = _delete(rig.settler, created, key)assert deleted.status_code == 404, deleted.textassert _calls(rig, created) == (("GET", _ENV_KEY),)diff --git a/tests/integration/spend/test_background_response_poll_retirement.py b/tests/integration/spend/test_background_response_poll_retirement.pyindex 3b5864681fd..7fdbd07942c 100644--- a/tests/integration/spend/test_background_response_poll_retirement.py+++ b/tests/integration/spend/test_background_response_poll_retirement.py@@ -172,8 +172,7 @@ def _calls_to(requests: Sequence[dict[str, JsonValue]], handle: ScenarioHandle)def _upstream_log(gateway: Gateway, handle: ScenarioHandle) -> Iterator[tuple[dict[str, JsonValue], ...]]:- fresh: Final = (_calls_to(_observed_requests(gateway), handle) for _ in itertools.count())- return itertools.accumulate(fresh, lambda seen, calls: (*seen, *calls))+ return (_calls_to(_observed_requests(gateway), handle) for _ in itertools.count())def _polls(log: Sequence[dict[str, JsonValue]], handle: ScenarioHandle) -> tuple[dict[str, JsonValue], ...]:diff --git a/tests/integration/spend/test_cache_and_quota.py b/tests/integration/spend/test_cache_and_quota.pyindex 511a812e895..5fc9b7c8c30 100644--- a/tests/integration/spend/test_cache_and_quota.py+++ b/tests/integration/spend/test_cache_and_quota.py@@ -55,7 +55,7 @@ def test_generated_cache_sequences_preserve_content_usage_and_zero_hit_cost(gateraisedef perform_request(self, marker: int) -> None:- self.upstream.get("/__observations").raise_for_status()+ self.upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",@@ -129,7 +129,7 @@ def test_repeated_hits_keep_response_identity_and_create_distinct_zero_cost_rowsmodel: Final = scenario.model(input_cost_per_token=0.001, output_cost_per_token=0.002)key: Final = scenario.key(models=[model])prompt: Final = f"repeated cache {uuid.uuid4().hex}"- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()results: Final = tuple(gateway.post("/v1/chat/completions",@@ -186,7 +186,7 @@ def test_key_budget_at_boundary_blocks_provider_then_explicit_reset_restores(gatseconds=70,)assert float(spent[0]["spend"]) == pytest.approx(0.06)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.request("POST","/v1/chat/completions",@@ -206,7 +206,7 @@ def test_key_budget_at_boundary_blocks_provider_then_explicit_reset_restores(gatlambda values: len(values) == 1 and float(values[0]["spend"]) >= 0.06,seconds=70,)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied_again: Final = gateway.request("POST","/v1/chat/completions",@@ -271,7 +271,7 @@ def test_scheduled_budget_reset_reconnects_after_db_transport_failure_and_unblocseconds=70,)assert float(exhausted[0]["spend"]) == pytest.approx(0.06)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = candidate.request("POST","/v1/chat/completions",@@ -348,7 +348,7 @@ def test_repeated_count_tokens_on_budgeted_key_does_not_reserve_budget_or_block_)key: Final = scenario.key(models=[model], max_budget=0.1)digest: Final = sha256(key.encode()).hexdigest()- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()counts: Final = tuple(gateway.request("POST",@@ -379,6 +379,7 @@ def test_repeated_count_tokens_on_budgeted_key_does_not_reserve_budget_or_block_"api_key": "",}] * 3, counted_requests+ upstream.delete("/__observations").raise_for_status()completion_prompt: Final = f"after counting {uuid.uuid4().hex}"completion: Final = gateway.request("POST",@@ -438,7 +439,7 @@ def test_in_flight_count_tokens_does_not_reserve_key_budget_away_from_a_completigateway.request, "POST", f"/v1beta/models/{counted}:countTokens", {"contents": contents}, key=key)assert counting_reached_provider.wait(timeout=30), "count tokens request never reached the provider"- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()prompt: Final = f"after count tokens {uuid.uuid4().hex}"completion: Final = gateway.request("POST",@@ -476,7 +477,7 @@ def test_different_system_messages_do_not_share_a_cached_response(gateway: Gatewprompt: Final = uuid.uuid4().hexdef completion_id(system: str, expected_calls: int) -> str:- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()response: Final = gateway.request("POST","/v1/chat/completions",diff --git a/tests/integration/spend/test_chaos_burst_spend_once.py b/tests/integration/spend/test_chaos_burst_spend_once.pyindex 77b08b1d559..ab19400da61 100644--- a/tests/integration/spend/test_chaos_burst_spend_once.py+++ b/tests/integration/spend/test_chaos_burst_spend_once.py@@ -25,7 +25,7 @@ def test_burst_with_partial_upstream_failures_logs_each_success_once(gateway: Gascenario.cleanups.callback(remove_script)configured: Final = upstream.post(f"/__scripts/{provider_model}", json={"statuses": statuses})assert configured.status_code == 200, configured.text- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()def attempt(index: int) -> httpx.Response:return gateway.request(diff --git a/tests/integration/spend/test_disable_end_user_cost_tracking.py b/tests/integration/spend/test_disable_end_user_cost_tracking.pyindex 0db72a06703..f5196da2661 100644--- a/tests/integration/spend/test_disable_end_user_cost_tracking.py+++ b/tests/integration/spend/test_disable_end_user_cost_tracking.py@@ -408,7 +408,7 @@ def test_flag_on_keeps_end_user_out_of_spend_rows_and_lens_export_with_cache_twigateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()team: Final = scenario.team()model: Final = _model(scenario, surface)key: Final = scenario.key(models=[model], team_id=team)@@ -455,7 +455,7 @@ def test_flag_on_failed_request_creates_no_customer_and_logs_no_end_user(rig: _Rconfigured: Final = upstream.post(f"/__scripts/{provider_model}", json={"statuses": [status] * 4})assert configured.status_code == 200, configured.textscenario.cleanups.callback(upstream.delete, f"/__scripts/{provider_model}")- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()team: Final = scenario.team()model: Final = scenario.model(model=f"openai/{provider_model}")key: Final = scenario.key(models=[model], team_id=team)@@ -521,7 +521,7 @@ def test_flag_on_header_sent_twice_and_body_user_are_none_attributed(rig: _Rig)gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()team: Final = scenario.team()model: Final = scenario.model(input_cost_per_token=0.001, output_cost_per_token=0.002)key: Final = scenario.key(models=[model], team_id=team)@@ -565,7 +565,7 @@ def test_flag_on_still_refuses_an_end_user_over_budget_at_auth(rig: _Rig) -> Non)assert created.status_code == 200, created.text_forget_customers(scenario, (end_user,))- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.request("POST",diff --git a/tests/integration/spend/test_end_user_budget_enforcement.py b/tests/integration/spend/test_end_user_budget_enforcement.pyindex 29b18f1f261..02c8aee8f5e 100644--- a/tests/integration/spend/test_end_user_budget_enforcement.py+++ b/tests/integration/spend/test_end_user_budget_enforcement.py@@ -275,7 +275,7 @@ def _prove_end_user_budget_lockout(info_path: str = "/customer/info",) -> None:served_content: Final = f"served {end_user_id}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()served: Final = _send(gateway, spelling, deployment, key, end_user_id, served_content)_assert_served(spelling, served)assert _observed(upstream) == [@@ -301,7 +301,7 @@ def _prove_end_user_budget_lockout(else:assert float(str(object_value(budget)["max_budget"])) == float(str(expected_max_budget)), customer_info.text- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()denied: Final = _send(gateway, spelling, deployment, key, end_user_id, f"denied {end_user_id}")assert _observed(upstream) == [], denied.texterror: Final = _denial_error(denied)@@ -533,7 +533,7 @@ def test_customer_budget_refuses_calls_and_writes_daily_spend(gateway: Gateway)gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed_requests(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, max_budget=0.05)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -552,6 +552,7 @@ def test_customer_budget_refuses_calls_and_writes_daily_spend(gateway: Gateway)served: Final = _chat(gateway, model, key, end_user)assert served.status_code == 200, served.textassert _observed_requests(upstream) == [_expected_observation(_sent_body(served, end_user))]+ upstream.delete("/__observations").raise_for_status()charged: Final = eventually(lambda: _end_user_row(end_user),@@ -577,7 +578,7 @@ def test_customer_budget_update_takes_effect_without_restart(gateway: Gateway) -gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed_requests(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, path="/end_user/new", max_budget=1.0)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -586,6 +587,7 @@ def test_customer_budget_update_takes_effect_without_restart(gateway: Gateway) -served: Final = _chat(gateway, model, key, end_user)assert served.status_code == 200, served.textassert _observed_requests(upstream) == [_expected_observation(_sent_body(served, end_user))]+ upstream.delete("/__observations").raise_for_status()updated: Final = gateway.request("POST", "/customer/update", {"user_id": end_user, "max_budget": 0.01})assert updated.status_code == 200, updated.text@@ -613,7 +615,7 @@ def test_streamed_call_is_refused_as_json_once_over_budget(gateway: Gateway) ->gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed_requests(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, max_budget=0.05)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -624,6 +626,7 @@ def test_streamed_call_is_refused_as_json_once_over_budget(gateway: Gateway) ->assert served.headers["content-type"].startswith("text/event-stream")assert 'data: {"id":"chatcmpl-' in served.text and "data: [DONE]" in served.text, served.textassert _observed_requests(upstream) == [_expected_observation(_sent_body(served, end_user))]+ upstream.delete("/__observations").raise_for_status()eventually(lambda: _end_user_row(end_user),lambda rows: len(rows) == 1 and float(str(rows[0]["spend"])) >= 0.05,diff --git a/tests/integration/spend/test_end_user_spend_without_proxy_user.py b/tests/integration/spend/test_end_user_spend_without_proxy_user.pyindex 68beedd087d..94884717092 100644--- a/tests/integration/spend/test_end_user_spend_without_proxy_user.py+++ b/tests/integration/spend/test_end_user_spend_without_proxy_user.py@@ -175,7 +175,7 @@ def test_streamed_end_user_spelling_is_charged_and_budget_enforced(gateway: Gategateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, max_budget=0.05)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -210,6 +210,7 @@ def test_streamed_end_user_spelling_is_charged_and_budget_enforced(gateway: Gateassert spend == pytest.approx(20 * 0.001 + 20 * 0.002)_assert_daily_row(end_user, model)+ upstream.delete("/__observations").raise_for_status()denied: Final = _chat_request(gateway,model,@@ -231,7 +232,7 @@ def test_anthropic_messages_metadata_user_id_is_charged_and_budget_enforced(gategateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, max_budget=0.05)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -337,6 +338,7 @@ def test_anthropic_messages_metadata_user_id_is_charged_and_budget_enforced(gateassert spend == pytest.approx(20 * 0.001 + 20 * 0.002)_assert_daily_row(end_user, model, "anthropic/claude-sonnet-5-5")+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.client.request("POST","/v1/messages",@@ -353,7 +355,7 @@ def test_end_user_id_spelling_is_charged_and_budget_enforced(gateway: Gateway, sgateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(gateway, end_user, max_budget=0.05)scenario.cleanups.callback(gateway.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -373,6 +375,7 @@ def test_end_user_id_spelling_is_charged_and_budget_enforced(gateway: Gateway, sassert spend == pytest.approx(20 * 0.001 + 20 * 0.002)_assert_daily_row(end_user, model)+ upstream.delete("/__observations").raise_for_status()denied: Final = _chat_request(gateway, model, key, spelling, end_user, f"again {uuid.uuid4().hex}")_assert_budget_refusal(denied, end_user)assert _observed(upstream) == []@@ -383,7 +386,7 @@ def test_safety_identifier_on_responses_is_charged_and_budget_enforced(gateway:gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()scenario_id: Final = f"sc-{uuid.uuid4().hex}"handle: Final = register_scenario(scenario_id,@@ -452,6 +455,7 @@ def test_safety_identifier_on_responses_is_charged_and_budget_enforced(gateway:assert spend == pytest.approx(0.06)_assert_daily_row(end_user, model)+ upstream.delete("/__observations").raise_for_status()denied: Final = call()_assert_budget_refusal(denied, end_user)assert _observed(upstream) == []@@ -462,7 +466,7 @@ def test_end_user_header_wins_over_body_user(gateway: Gateway) -> None:gateway.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()header_user: Final = f"integration-end-user-a-{uuid.uuid4().hex}"body_user: Final = f"integration-end-user-b-{uuid.uuid4().hex}"_new_customer(gateway, header_user, max_budget=0.05)@@ -503,6 +507,7 @@ def test_end_user_header_wins_over_body_user(gateway: Gateway) -> None:== [])+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.request("POST","/v1/chat/completions",@@ -542,7 +547,7 @@ def test_configured_end_user_header_is_charged_and_budget_enforced(candidate.scenario() as scenario,httpx.Client(base_url=gateway.upstream_url, timeout=5, trust_env=False) as upstream,):- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()end_user: Final = f"integration-end-user-{uuid.uuid4().hex}"_new_customer(candidate, end_user, max_budget=0.05)scenario.cleanups.callback(candidate.request, "POST", "/customer/delete", {"user_ids": [end_user]})@@ -569,6 +574,7 @@ def test_configured_end_user_header_is_charged_and_budget_enforced(assert _charged_spend(end_user) == pytest.approx(0.06)_assert_daily_row(end_user, model)+ upstream.delete("/__observations").raise_for_status()denied: Final = candidate.request("POST","/v1/chat/completions",diff --git a/tests/integration/spend/test_global_spend_reset.py b/tests/integration/spend/test_global_spend_reset.pyindex fad5c14175a..c400d90e184 100644--- a/tests/integration/spend/test_global_spend_reset.py+++ b/tests/integration/spend/test_global_spend_reset.py@@ -112,7 +112,7 @@ def test_global_spend_reset_zeroes_token_and_team_spend_but_keeps_logs(gateway:assert float(str(_token_spend(key_b)[0]["spend"])) == pytest.approx(0.06), _token_spend(key_b)assert float(str(_team_spend(team_id)[0]["spend"])) == pytest.approx(0.12), _team_spend(team_id)- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()denied: Final = _chat(gateway, model, key_a)assert denied.status_code == 422, denied.textassert object_value(denied.json()["error"])["type"] == "budget_exceeded", denied.text@@ -153,7 +153,7 @@ def test_reset_exhausted_key_is_served_again(gateway: Gateway) -> None:reset: Final = gateway.request("POST", "/global/spend/reset")assert reset.status_code == 200, reset.textcontent: Final = f"restored {uuid.uuid4().hex}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()restored: Final = _chat(gateway, model, key, content)assert restored.status_code == 200, restored.textassert _observed(upstream) == [_upstream_chat(content)], restored.textdiff --git a/tests/integration/spend/test_key_budget_lockout.py b/tests/integration/spend/test_key_budget_lockout.pyindex 74470b80543..a3d1d3d0a78 100644--- a/tests/integration/spend/test_key_budget_lockout.py+++ b/tests/integration/spend/test_key_budget_lockout.py@@ -182,7 +182,7 @@ def test_an_exhausted_key_is_refused_inference_but_can_still_read_its_own_info(glambda rows: len(rows) == 1 and float(str(rows[0]["spend"])) >= 0.06,seconds=70,)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.request("POST","/v1/chat/completions",@@ -234,7 +234,7 @@ def _upstream_chat(content: str) -> dict[str, JsonValue]:def _served_chat(gateway: Gateway, upstream: httpx.Client, model: str, key: str) -> None:content: Final = f"tier served {uuid.uuid4().hex}"- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()served: Final = _bounded_chat(gateway, model, key, content)assert served.status_code == 200, served.textassert float(served.headers["x-litellm-response-cost"]) == 0.06, dict(served.headers)@@ -258,7 +258,7 @@ def test_raising_a_spent_keys_budget_restores_serving(gateway: Gateway) -> None:seconds=70,)eventually(lambda: _bounded_chat(gateway, model, key), lambda response: response.status_code != 200, seconds=30)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = _bounded_chat(gateway, model, key)assert denied.status_code == 422, denied.textassert object_value(denied.json()["error"])["type"] == "budget_exceeded"@@ -427,7 +427,7 @@ def test_raising_a_spent_tier_budget_restores_serving(gateway: Gateway) -> None:lambda rows: len(rows) == 1 and float(str(rows[0]["spend"])) >= 0.06,seconds=70,)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()_denied_with_budget_exceeded(gateway, model, key)assert upstream.get("/__observations").json()["requests"] == []gateway.post("/budget/update", {"budget_id": budget_id, "max_budget": 1.0})@@ -464,7 +464,7 @@ def test_lowering_a_tier_budget_below_spend_blocks_the_key(gateway: Gateway) ->lambda rows: len(rows) == 1 and float(str(rows[0]["spend"])) >= 0.06,seconds=30,)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()probe: Final = gateway.request("POST", "/v1/chat/completions", {"model": model}, key=key)assert probe.status_code == 400, probe.textassert object_value(probe.json()["error"]) == {@@ -480,7 +480,7 @@ def test_lowering_a_tier_budget_below_spend_blocks_the_key(gateway: Gateway) ->)assert len(updated_rows) == 1assert float(str(updated_rows[0]["max_budget"])) == 0.01, updated_rows- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()lowered_probe: Final = eventually(lambda: gateway.request("POST", "/v1/chat/completions", {"model": model}, key=key),lambda response: (@@ -516,7 +516,7 @@ def test_key_linked_to_a_tier_by_update_is_refused_once_streamed_spend_exhausts_"messages": [{"role": "user", "content": content}],"stream": True,}- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()served: Final = gateway.request("POST", "/v1/chat/completions", body, key=key)assert served.status_code == 200, served.textevents: Final = tuple(@@ -541,7 +541,7 @@ def test_key_linked_to_a_tier_by_update_is_refused_once_streamed_spend_exhausts_assert denied.status_code == 422, denied.textassert object_value(denied.json()["error"])["type"] == "budget_exceeded", denied.textassert "Max budget: 0.06" in denied.text, denied.text- _observed(upstream)+ upstream.delete("/__observations").raise_for_status()fresh_denied: Final = gateway.request("POST", "/v1/chat/completions", body, key=key)assert fresh_denied.status_code == 422, fresh_denied.textassert object_value(fresh_denied.json()["error"])["type"] == "budget_exceeded", fresh_denied.textdiff --git a/tests/integration/spend/test_org_budget_cli_session_token.py b/tests/integration/spend/test_org_budget_cli_session_token.pyindex f821e337374..34f6cfab174 100644--- a/tests/integration/spend/test_org_budget_cli_session_token.py+++ b/tests/integration/spend/test_org_budget_cli_session_token.py@@ -39,7 +39,7 @@ def test_cli_session_token_without_org_id_charges_and_caps_the_team_organization)token: Final = _cli_session_token(user_id, team_id)prompt: Final = f"org budget {uuid.uuid4().hex}"- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()first: Final = gateway.request("POST","/v1/chat/completions",@@ -51,6 +51,7 @@ def test_cli_session_token_without_org_id_charges_and_caps_the_team_organizationassert len(reached_upstream) == 1, reached_upstreamassert reached_upstream[0]["body"]["model"] == "gpt-4o-mini", reached_upstreamassert reached_upstream[0]["body"]["messages"] == [{"role": "user", "content": prompt}], reached_upstream+ upstream.delete("/__observations").raise_for_status()logged: Final = eventually(lambda: read_rows('SELECT organization_id, team_id, spend FROM "LiteLLM_SpendLogs" WHERE request_id=%s',diff --git a/tests/integration/spend/test_team_budget_enforcement.py b/tests/integration/spend/test_team_budget_enforcement.pyindex 823aff1e0cc..fce33478672 100644--- a/tests/integration/spend/test_team_budget_enforcement.py+++ b/tests/integration/spend/test_team_budget_enforcement.py@@ -50,7 +50,7 @@ def exhausted(gateway: Gateway) -> Iterator[ExhaustedTeam]:seconds=70,)eventually(lambda: _chat(gateway, model, key), lambda response: response.status_code != 200, seconds=30)- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()yield ExhaustedTeam(scenario, upstream, model, team_id, key)diff --git a/tests/integration/spend/test_team_member_spend.py b/tests/integration/spend/test_team_member_spend.pyindex 343a3be1b49..306138e2bb1 100644--- a/tests/integration/spend/test_team_member_spend.py+++ b/tests/integration/spend/test_team_member_spend.py@@ -130,8 +130,6 @@ class _BulkBudgetUpdateResponse(BaseModel):@pytest.fixturedef upstream(gateway: Gateway) -> Iterator[httpx.Client]:with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:- response: Final = client.get("/__observations")- assert response.status_code == 200, response.textyield client@@ -304,7 +302,7 @@ def test_member_over_budget_is_blocked_when_redis_counter_reads_stale_low(gatewacounted: Final = eventually(lambda: cache.get(counter_key), lambda value: value is not None, seconds=10)assert float(counted) == pytest.approx(0.06), countedcache.set(counter_key, "0.01")- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = gateway.request("POST","/v1/chat/completions",@@ -346,6 +344,7 @@ def test_member_update_lowering_the_budget_below_spend_blocks_the_next_call(assert peer_first.status_code == 200, peer_first.textobserved_before_update: Final = _observed_models(upstream)assert observed_before_update == (provider_model, provider_model), repr(observed_before_update)+ upstream.delete("/__observations").raise_for_status()accrued: Final = eventually(lambda: _budget_state(team, user),lambda values: len(values) == 1 and values[0].spend is not None and values[0].spend >= 0.12,@@ -466,6 +465,7 @@ def test_member_update_temp_budget_increase_readmits_a_blocked_member(assert first.status_code == 200, first.textobserved_before_block: Final = _observed_models(upstream)assert observed_before_block == (provider_model,), repr(observed_before_block)+ upstream.delete("/__observations").raise_for_status()accrued: Final = eventually(lambda: _budget_state(team, user),lambda values: len(values) == 1 and values[0].spend is not None and values[0].spend >= 0.06,@@ -701,6 +701,7 @@ def test_member_update_by_email_sets_models_role_and_forks_the_team_default_budgassert _ErrorResponse.model_validate_json(denied.text).error.type == "team_model_access_denied", denied.textobserved_before_clear: Final = _observed_models(upstream)assert observed_before_clear == (provider_one,), repr(observed_before_clear)+ upstream.delete("/__observations").raise_for_status()cleared_models: Final = _member_update(gateway,@@ -815,6 +816,7 @@ def test_bulk_update_is_a_merge_patch_per_member(gateway: Gateway, upstream: httassert first_chat.status_code == 200, first_chat.textobserved_before_update: Final = _observed_models(upstream)assert observed_before_update == (provider_spend,), repr(observed_before_update)+ upstream.delete("/__observations").raise_for_status()accrued: Final = eventually(lambda: _budget_state(team, user_one),lambda values: len(values) == 1 and values[0].spend is not None and values[0].spend >= 0.06,@@ -889,6 +891,7 @@ def test_bulk_update_is_a_merge_patch_per_member(gateway: Gateway, upstream: htt)observed_after_first_patch: Final = _observed_models(upstream)assert observed_after_first_patch == (provider_one,), repr(observed_after_first_patch)+ upstream.delete("/__observations").raise_for_status()cleared_max: Final = gateway.request("POST",@@ -974,6 +977,7 @@ def test_bulk_update_restores_team_default_when_last_member_limit_is_cleared(assert first_chat.status_code == 200, first_chat.textfirst_observations: Final = _observed_models(upstream)assert first_observations == (provider_model,), repr(first_observations)+ upstream.delete("/__observations").raise_for_status()accrued: Final = eventually(lambda: _budget_state(team, user),lambda values: len(values) == 1 and values[0].spend is not None and values[0].spend >= 0.06,@@ -984,6 +988,7 @@ def test_bulk_update_restores_team_default_when_last_member_limit_is_cleared(assert second_chat.status_code == 200, second_chat.textsecond_observations: Final = _observed_models(upstream)assert second_observations == (provider_model,), repr(second_observations)+ upstream.delete("/__observations").raise_for_status()cleared: Final = gateway.request("POST",f"/management/v1/teams/{team}/members/bulk_update",@@ -1019,11 +1024,3 @@ def test_bulk_update_restores_team_default_when_last_member_limit_is_cleared(assert first_observations + second_observations == (provider_model, provider_model), repr((first_observations, second_observations))--[email protected](autouse=True)-def _drain_unobserved_requests(gateway: Gateway) -> Iterator[None]:- yield- with httpx.Client(base_url=gateway.upstream_url, timeout=15, trust_env=False) as client:- response: Final = client.get("/__observations")- assert response.status_code == 200, response.textdiff --git a/tests/integration/spend/test_user_budget_on_team_keys.py b/tests/integration/spend/test_user_budget_on_team_keys.pyindex f80859555f0..5b28b1aa875 100644--- a/tests/integration/spend/test_user_budget_on_team_keys.py+++ b/tests/integration/spend/test_user_budget_on_team_keys.py@@ -45,7 +45,7 @@ def test_team_key_is_denied_before_provider_once_owner_personal_budget_is_exhausassert read_rows('SELECT max_budget FROM "LiteLLM_VerificationToken" WHERE token=%s', (sha256(key.encode()).hexdigest(),)) == [{"max_budget": None}]- upstream.get("/__observations").raise_for_status()+ upstream.delete("/__observations").raise_for_status()denied: Final = candidate.request("POST","/v1/chat/completions",diff --git a/tests/unit/integration_support/test_upstream.py b/tests/unit/integration_support/test_upstream.pyindex 9e114e3b0b7..a54cda06c65 100644--- a/tests/unit/integration_support/test_upstream.py+++ b/tests/unit/integration_support/test_upstream.py@@ -3,6 +3,7 @@ from collections import dequefrom pathlib import Pathfrom typing import Final+import httpximport pytestfrom starlette.types import Message, Scopefrom starlette.websockets import WebSocket@@ -50,13 +51,36 @@ async def test_realtime_disconnect_after_session_creation_keeps_unexpected_errorelse:await provider.realtime(socket)assert [item["type"] for item in outgoing] == ["websocket.accept", "websocket.send"]- observed: Final = tuple(provider.observations.get_nowait() for _ in range(provider.observations.qsize()))+ observed: Final = provider.observations.snapshot()assert [(item.method, item.body) for item in observed] == [("WEBSOCKET", {"query": [["model", "synthetic"]]}),("WEBSOCKET_FRAME", {"type": "response.create"}),]+async def test_observations_read_without_draining_until_explicitly_reset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]))+ from integration._support.upstream import Provider++ transport: Final = httpx.ASGITransport(app=Provider().app())+ async with httpx.AsyncClient(transport=transport, base_url="http://upstream") as client:+ sent: Final = await client.post(+ "/v1/chat/completions",+ json={"model": "synthetic", "messages": [{"role": "user", "content": "observed-marker"}]},+ )+ assert sent.status_code == 200, sent.text+ first: Final = (await client.get("/__observations")).json()["requests"]+ second: Final = (await client.get("/__observations")).json()["requests"]+ assert [(item["path"], item["body"]["messages"][0]["content"]) for item in first] == [+ ("/v1/chat/completions", "observed-marker")+ ]+ assert second == first+ reset: Final = await client.delete("/__observations")+ assert reset.status_code == 204+ assert (await client.get("/__observations")).json()["requests"] == []++@pytest.mark.asyncio@pytest.mark.parametrize("method,status", (("POST", 200), ("POST", 400), ("DELETE", 200)))async def test_mcp_notification_ordering_preserves_other_responses(