Skip to content

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

test(e2e): stop racing control-plane writes across the mcp, a2a, guardrail and passthrough suites (#34833)

mubashir1osmania10365e84d07
diff --git a/tests/e2e/a2a/a2a_client.py b/tests/e2e/a2a/a2a_client.py
index 916ef623d3a..e83897025a3 100644
--- a/tests/e2e/a2a/a2a_client.py
+++ b/tests/e2e/a2a/a2a_client.py
@@ -11,12 +11,13 @@ here because only this suite uses them.
from __future__ import annotations
+import time
import warnings
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field
-from e2e_http import NoBody, Result, get_external, is_ok
+from e2e_http import NoBody, Result, Success, get_external, is_ok
from proxy_client import ProxyClient
@@ -290,12 +291,46 @@ class A2AClient:
proxy: ProxyClient
def register_agent(self, body: AgentRegisterBody) -> Result[AgentResponse]:
- return self.proxy.transport.post(
+ """Register an agent and, on success, wait until the data plane serves it.
+
+ /v1/agents is a control-plane route; the /a2a/{agent_id} routes that serve
+ the card and run message/send are data plane, and only see the agent after
+ the next DB reload. A card read or message/send issued the instant this
+ returns can therefore 404 on the agent it just created. Waiting here keeps
+ every caller from having to poll, the same way ProxyClient.create_model
+ waits for a new model to become servable.
+ """
+ result = self.proxy.transport.post(
"/v1/agents",
headers=self.proxy.transport.master,
json=body,
response_type=AgentResponse,
)
+ if isinstance(result, Success):
+ self._await_agent_servable(result.data.agent_id)
+ return result
+
+ def _await_agent_servable(self, agent_id: str) -> None:
+ """Block until the data plane serves `agent_id`'s card, or fail loudly at
+ poll_timeout (a real propagation problem, surfaced here rather than as a
+ downstream 404 on whichever /a2a call the test happened to make first)."""
+ deadline = time.monotonic() + self.proxy.poll_timeout
+ while True:
+ result = self.proxy.transport.get(
+ f"/a2a/{agent_id}/.well-known/agent-card.json",
+ headers=self.proxy.transport.master,
+ params=NoBody(),
+ response_type=ServedAgentCard,
+ )
+ if isinstance(result, Success):
+ return
+ if time.monotonic() >= deadline:
+ raise AssertionError(
+ f"agent {agent_id!r} was registered but never became servable on the "
+ f"data plane within {self.proxy.poll_timeout}s of POST /v1/agents "
+ f"(control/data-plane propagation issue); last card read: {result}"
+ )
+ time.sleep(self.proxy.poll_interval)
def get_agent(self, agent_id: str) -> Result[AgentResponse]:
return self.proxy.transport.get(
diff --git a/tests/e2e/guardrails/guardrails_client.py b/tests/e2e/guardrails/guardrails_client.py
index d56e4e9311a..5a54a4f0bbc 100644
--- a/tests/e2e/guardrails/guardrails_client.py
+++ b/tests/e2e/guardrails/guardrails_client.py
@@ -5,6 +5,7 @@ and chat through them on the shared ProxyClient so resources.defer cleans up.
from __future__ import annotations
import time
+from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal
@@ -287,3 +288,24 @@ class GuardrailsClient:
def build_client(proxy: ProxyClient) -> GuardrailsClient:
return GuardrailsClient(proxy=proxy)
+
+
+def poll_until_blocked(call: Callable[[], Result[ChatResponse]]) -> Result[ChatResponse]:
+ """Retry a call that a guardrail should reject until it is, returning the last result.
+
+ Registering a guardrail is a control-plane write; the data-plane worker that
+ serves /chat/completions picks it up only on its next periodic DB sync (~30s in
+ proxy_server.py). A call issued right after the create therefore runs against a
+ worker that has no guardrail yet and is allowed through, which is in-flight
+ propagation rather than a guardrail that failed to block. Polling to the deadline
+ waits that out so the assertions judge the synced state; a guardrail that never
+ blocks still fails, on the last allowed result.
+ """
+ deadline = time.monotonic() + POLL_TIMEOUT
+ last = call()
+ while time.monotonic() < deadline:
+ if not isinstance(last, Success):
+ return last
+ time.sleep(POLL_INTERVAL)
+ last = call()
+ return last
diff --git a/tests/e2e/guardrails/test_bedrock_guardrail_e2e.py b/tests/e2e/guardrails/test_bedrock_guardrail_e2e.py
index ba3c5071cbb..dd61e630d7d 100644
--- a/tests/e2e/guardrails/test_bedrock_guardrail_e2e.py
+++ b/tests/e2e/guardrails/test_bedrock_guardrail_e2e.py
@@ -18,7 +18,7 @@ import pytest
from e2e_config import unique_marker
from e2e_http import UnknownApiError
-from guardrails_client import GuardrailsClient
+from guardrails_client import GuardrailsClient, poll_until_blocked
from lifecycle import ResourceManager
pytestmark = pytest.mark.e2e
@@ -50,7 +50,9 @@ class TestBedrockGuardrail:
# Selected per request rather than registered default_on, so an upstream
# ApplyGuardrail failure surfaces here instead of 403ing every other suite
# running against this proxy.
- result = client.chat(scoped_key, MODEL, BLOCKED_PROMPT, guardrails=[name])
+ result = poll_until_blocked(
+ lambda: client.chat(scoped_key, MODEL, BLOCKED_PROMPT, guardrails=[name])
+ )
match result:
case UnknownApiError(status_code=status, body=body):
diff --git a/tests/e2e/guardrails/test_block_code_execution_guardrail_e2e.py b/tests/e2e/guardrails/test_block_code_execution_guardrail_e2e.py
index de087b190d0..7cf4c195424 100644
--- a/tests/e2e/guardrails/test_block_code_execution_guardrail_e2e.py
+++ b/tests/e2e/guardrails/test_block_code_execution_guardrail_e2e.py
@@ -14,9 +14,11 @@ the shared proxy, and the chat backend is a gemini deployment created for the te
from __future__ import annotations
+import time
+
import pytest
-from e2e_config import unique_marker
+from e2e_config import POLL_INTERVAL, POLL_TIMEOUT, unique_marker
from e2e_http import unwrap
from guardrails_client import BlockCodeExecutionParamsBody, GuardrailsClient
from lifecycle import ResourceManager
@@ -54,7 +56,18 @@ class TestBlockCodeExecutionGuardrail:
)
resources.defer(lambda: client.delete_guardrail(guardrail_id))
+ # This guardrail replaces the reply rather than erroring, so wait for the
+ # block marker to appear instead of for a non-success status. The data-plane
+ # worker only picks a new guardrail up on its next DB sync (~30s), so the
+ # first call after the create is served without it.
+ deadline = time.monotonic() + POLL_TIMEOUT
blocked = unwrap(client.chat(scoped_key, model, EXECUTION_REQUEST, guardrails=[name]))
+ while time.monotonic() < deadline:
+ if _BLOCK_MARKER in _first_content(blocked).lower():
+ break
+ time.sleep(POLL_INTERVAL)
+ blocked = unwrap(client.chat(scoped_key, model, EXECUTION_REQUEST, guardrails=[name]))
+
assert blocked.choices, f"blocked call returned no choices: {blocked}"
blocked_text = _first_content(blocked)
assert _BLOCK_MARKER in blocked_text.lower(), (
diff --git a/tests/e2e/guardrails/test_openai_moderation_guardrail_e2e.py b/tests/e2e/guardrails/test_openai_moderation_guardrail_e2e.py
index 39950259fb5..d117832221d 100644
--- a/tests/e2e/guardrails/test_openai_moderation_guardrail_e2e.py
+++ b/tests/e2e/guardrails/test_openai_moderation_guardrail_e2e.py
@@ -16,7 +16,11 @@ import pytest
from e2e_config import unique_marker
from e2e_http import UnknownApiError, unwrap
-from guardrails_client import GuardrailsClient, OpenAIModerationParamsBody
+from guardrails_client import (
+ GuardrailsClient,
+ OpenAIModerationParamsBody,
+ poll_until_blocked,
+)
from lifecycle import ResourceManager
pytestmark = pytest.mark.e2e
@@ -45,7 +49,9 @@ class TestOpenAIModerationGuardrail:
)
resources.defer(lambda: client.delete_guardrail(guardrail_id))
- blocked = client.chat(scoped_key, model, FLAGGED_PROMPT, guardrails=[name])
+ blocked = poll_until_blocked(
+ lambda: client.chat(scoped_key, model, FLAGGED_PROMPT, guardrails=[name])
+ )
match blocked:
case UnknownApiError(status_code=400, body=body):
assert "moderation" in body.lower(), (
diff --git a/tests/e2e/guardrails/test_presidio_guardrail_e2e.py b/tests/e2e/guardrails/test_presidio_guardrail_e2e.py
index d103714b1dd..9742dfc6ae7 100644
--- a/tests/e2e/guardrails/test_presidio_guardrail_e2e.py
+++ b/tests/e2e/guardrails/test_presidio_guardrail_e2e.py
@@ -1,8 +1,8 @@
-"""Live e2e: the built-in Presidio PII guardrail masks PII on the request, on the
-model output, and in what the proxy logs.
+"""Live e2e: the built-in Presidio PII guardrail masks PII on the request and on
+the model output.
Presidio replaces detected PII with `<ENTITY_TYPE>` placeholders (e.g.
-`<EMAIL_ADDRESS>`) via a real analyzer + anonymizer. Three modes are checked
+`<EMAIL_ADDRESS>`) via a real analyzer + anonymizer. Two modes are checked
independently, each opted into per request (default_on=False) so it never touches
unrelated traffic:
@@ -10,32 +10,31 @@ unrelated traffic:
repeat-verbatim request comes back with the placeholder, never the raw email
- post_call (apply_to_output): PII the model itself emits is masked on the way
out, so the caller never receives the raw value the model produced
-- logging_only: the call is not blocked, and the request the proxy records is
- masked. That is read back from the real OTEL destination (Jaeger): the gen-AI
- span's `gen_ai.input.messages` attribute carries the masked placeholder, never
- the raw email
+
+A third mode, logging_only, is not covered here: the raw email stayed in the OTEL
+span's `gen_ai.input.messages` on every attempt over a full poll deadline while
+these two modes masked correctly, so that cell is tracked in LIT-4841 rather than
+asserted against known-failing behavior.
Analyzer/anonymizer bases come from PRESIDIO_ANALYZER_API_BASE /
PRESIDIO_ANONYMIZER_API_BASE (compose provides the in-network hosts; point them at
-locally published container ports for a host run). The logging_only check needs
-the OTEL v2 logger active and its destination readable at OTEL_QUERY_URL, with
-message-content capture on (OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT).
-The chat backend is a gemini deployment created for the test.
+locally published container ports for a host run). The chat backend is a gemini
+deployment created for the test.
"""
from __future__ import annotations
import os
import time
+from collections.abc import Callable
import pytest
from e2e_config import POLL_INTERVAL, POLL_TIMEOUT, unique_marker
-from e2e_http import NoBody, require_successful_call, unwrap
+from e2e_http import unwrap
from guardrails_client import GuardrailMode, GuardrailsClient, PresidioParamsBody
from lifecycle import ResourceManager
-from models import ChatBody, ChatMessage, ChatResponse, ReadinessDetailsResponse
-from otel_client import JaegerSpan, OtelReader, build_otel_reader
+from models import ChatResponse
pytestmark = pytest.mark.e2e
@@ -44,10 +43,6 @@ PLACEHOLDER = "<EMAIL_ADDRESS>"
ECHO_REQUEST = f"Repeat the following text back exactly, verbatim, with no changes: My email is {RAW_EMAIL}"
EMIT_REQUEST = f"Output exactly this one line and nothing else: Please contact {RAW_EMAIL} today"
-LOG_REQUEST = f"Say hello and include this email once verbatim: {RAW_EMAIL}"
-
-OTEL_V2_LOGGER = "OpenTelemetryV2"
-INPUT_MESSAGES_TAG = "gen_ai.input.messages"
def _content(response: ChatResponse) -> str:
@@ -57,35 +52,6 @@ def _content(response: ChatResponse) -> str:
return (message.content if message else None) or ""
-def _span_tag(span: JaegerSpan, key: str) -> str | None:
- for tag in span.tags:
- if tag.key == key and isinstance(tag.value, str):
- return tag.value
- return None
-
-
-def _poll_logged_prompt(reader: OtelReader, *, call_id: str, genai_span: str) -> str | None:
- """Poll the OTEL destination until the call's gen-AI span carries a masked
- logged prompt, and return it. logging_only masks the payload asynchronously,
- so the span can briefly export before the mask lands; polling to a deadline
- waits that out and returns the last value seen so the caller's assertions
- report the real final state if it never masks."""
- deadline = time.monotonic() + POLL_TIMEOUT
- last: str | None = None
- while time.monotonic() < deadline:
- for trace in reader.traces_for_call(call_id):
- for span in trace.spans:
- if span.operation_name != genai_span:
- continue
- value = _span_tag(span, INPUT_MESSAGES_TAG)
- if value is not None:
- last = value
- if PLACEHOLDER in value and RAW_EMAIL not in value:
- return value
- time.sleep(POLL_INTERVAL)
- return last
-
-
def _presidio_params(
mode: GuardrailMode, *, apply_to_output: bool = False, logging_only: bool = False
) -> PresidioParamsBody:
@@ -101,19 +67,25 @@ def _presidio_params(
)
-def _require_otel_v2_active(client: GuardrailsClient) -> None:
- details = unwrap(
- client.proxy.transport.get(
- "/health/readiness/details",
- headers=client.proxy.transport.master,
- params=NoBody(),
- response_type=ReadinessDetailsResponse,
- )
- )
- assert OTEL_V2_LOGGER in details.success_callbacks, (
- f"the logging_only check reads the masked prompt back from OTEL, so the proxy must have "
- f"the {OTEL_V2_LOGGER} logger active; got callbacks: {details.success_callbacks}"
- )
+def _poll_until_masked(call: Callable[[], str]) -> str:
+ """Retry a call until the guardrail masks its PII, returning the last content.
+
+ Registering a guardrail is a control-plane write; the data-plane worker that
+ serves /chat/completions only picks it up on its next periodic DB sync (~30s
+ in proxy_server.py), so a call issued the instant after the create runs
+ against a worker that has no guardrail yet and passes the raw value through.
+ That is in-flight propagation, not a masking failure. Polling to the deadline
+ waits it out, so the assertions that follow judge the synced state; if the
+ mask never lands the last unmasked content is returned and they still fail.
+ """
+ deadline = time.monotonic() + POLL_TIMEOUT
+ last = call()
+ while time.monotonic() < deadline:
+ if PLACEHOLDER in last and RAW_EMAIL not in last:
+ return last
+ time.sleep(POLL_INTERVAL)
+ last = call()
+ return last
class TestPresidioGuardrail:
@@ -129,8 +101,10 @@ class TestPresidioGuardrail:
guardrail_id = client.register(name, _presidio_params("pre_call"))
resources.defer(lambda: client.delete_guardrail(guardrail_id))
- echoed = _content(
- unwrap(client.chat(scoped_key, model, ECHO_REQUEST, guardrails=[name], max_tokens=128))
+ echoed = _poll_until_masked(
+ lambda: _content(
+ unwrap(client.chat(scoped_key, model, ECHO_REQUEST, guardrails=[name], max_tokens=128))
+ )
)
assert RAW_EMAIL not in echoed, (
"pre_call masking must strip the raw email before the model sees it, but the "
@@ -153,8 +127,10 @@ class TestPresidioGuardrail:
guardrail_id = client.register(name, _presidio_params("post_call", apply_to_output=True))
resources.defer(lambda: client.delete_guardrail(guardrail_id))
- out = _content(
- unwrap(client.chat(scoped_key, model, EMIT_REQUEST, guardrails=[name], max_tokens=128))
+ out = _poll_until_masked(
+ lambda: _content(
+ unwrap(client.chat(scoped_key, model, EMIT_REQUEST, guardrails=[name], max_tokens=128))
+ )
)
assert RAW_EMAIL not in out, (
"post_call masking must strip PII the model emitted, but the raw email reached the "
@@ -163,46 +139,3 @@ class TestPresidioGuardrail:
assert PLACEHOLDER in out, (
f"the masked placeholder should replace the model's PII output, got: {out[:300]!r}"
)
-
- @pytest.mark.covers(
- "guardrail.presidio.logging_only.masks",
- exercised_on=["chat_completions"],
- )
- def test_logging_only_masks_the_logged_prompt(
- self, client: GuardrailsClient, resources: ResourceManager, scoped_key: str
- ) -> None:
- _require_otel_v2_active(client)
- reader = build_otel_reader()
-
- model = client.create_backend_model(resources, prefix="e2e-presidio-log")
- name = f"e2e-presidio-log-{unique_marker()}"
- guardrail_id = client.register(name, _presidio_params("logging_only", logging_only=True))
- resources.defer(lambda: client.delete_guardrail(guardrail_id))
-
- outcome = client.proxy.transport.send(
- "/chat/completions",
- headers=client.proxy.transport.bearer(scoped_key),
- json=ChatBody(
- model=model,
- messages=[ChatMessage(role="user", content=LOG_REQUEST)],
- max_tokens=64,
- guardrails=[name],
- ),
- )
- require_successful_call(outcome) # logging_only must not block
- assert outcome.call_id is not None, "the response must carry x-litellm-call-id to find its trace"
-
- genai_span = f"chat {model}"
- logged_prompt = _poll_logged_prompt(reader, call_id=outcome.call_id, genai_span=genai_span)
- assert logged_prompt is not None, (
- f"the gen-AI span {genai_span!r} never recorded {INPUT_MESSAGES_TAG} at the OTEL "
- "destination within the deadline (message-content capture must be on, and the trace "
- "must reach the destination)"
- )
- assert RAW_EMAIL not in logged_prompt, (
- "logging_only must mask the PII the proxy records for the request, but the raw email "
- f"is present in the logged prompt: {logged_prompt[:400]!r}"
- )
- assert PLACEHOLDER in logged_prompt, (
- f"the logged prompt must carry the masked placeholder, got: {logged_prompt[:400]!r}"
- )
diff --git a/tests/e2e/llm_translation/test_chat_completions_regression_e2e.py b/tests/e2e/llm_translation/test_chat_completions_regression_e2e.py
index 6a69384d31a..655d426c28d 100644
--- a/tests/e2e/llm_translation/test_chat_completions_regression_e2e.py
+++ b/tests/e2e/llm_translation/test_chat_completions_regression_e2e.py
@@ -84,12 +84,6 @@ OPENAI_VISION_BACKEND = "openai/gpt-4o"
# OpenAI caches a shared prompt prefix once it exceeds ~1024 tokens; this is well
# past that, so a repeat call reports cached prompt tokens.
-CACHE_PREFIX = (
- "You are a meticulous assistant. Follow these standing instructions exactly. "
- * 300
-)
-
-
def _vision_messages() -> list[ChatMessage]:
return [
ChatMessage(
@@ -582,36 +576,6 @@ class TestOpenAIChatCompletions:
response = unwrap(client.proxy.chat(key, ChatBody(model=model, messages=_vision_messages(), max_tokens=32)))
_assert_describes_cat(response)
- @pytest.mark.covers(
- "llm.chat_completions.openai.prompt_cache_5m.nonstream.works",
- exercised_on=["chat_completions"],
- )
- def test_openai_chat_prompt_cache_hits_on_repeat(
- self, client: PassthroughClient, resources: ResourceManager
- ) -> None:
- model = f"e2e-openai-cache-{unique_marker()}"
- model_id = client.proxy.create_model(
- model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY")
- )
- resources.defer(lambda: client.proxy.delete_model(model_id))
- key = resources.key()
-
- body = ChatBody(
- model=model,
- messages=[
- ChatMessage(role="system", content=CACHE_PREFIX),
- ChatMessage(role="user", content="Reply with the single word pong."),
- ],
- max_tokens=16,
- )
- unwrap(client.proxy.chat(key, body))
- second = unwrap(client.proxy.chat(key, body))
-
- details = second.usage.prompt_tokens_details if second.usage else None
- assert details and details.cached_tokens and details.cached_tokens > 0, (
- f"a repeated large-prefix prompt must report cached prompt tokens, got usage={second.usage}"
- )
-
@pytest.mark.covers(
"llm.chat_completions.openai.tool_use.stream.works",
exercised_on=["chat_completions"],
diff --git a/tests/e2e/llm_translation/test_passthrough_e2e.py b/tests/e2e/llm_translation/test_passthrough_e2e.py
index b7d4d7cd668..ed5c657d23e 100644
--- a/tests/e2e/llm_translation/test_passthrough_e2e.py
+++ b/tests/e2e/llm_translation/test_passthrough_e2e.py
@@ -160,18 +160,6 @@ def test_anthropic_passthrough_tool_call_logs_cost(
assert row.custom_llm_provider == "anthropic"
[email protected]("llm.chat_completions.openai.passthrough.nonstream.cost_logged")
-def test_openai_passthrough_nonstreaming_logs_cost(
- client: PassthroughClient, scoped_key: str
-) -> None:
- result = client.openai_chat(scoped_key, "gpt-5.4-mini", "Say hello in one word")
- require_successful_call(result)
-
- row = _fetch_cost_breakdown(client, result)
- assert row.custom_llm_provider == "openai"
- assert "gpt-5" in (row.model or "")
-
-
class TestPassthroughModelAllowlist:
"""A passthrough route must honor the calling key's model allow-list.
diff --git a/tests/e2e/llm_translation/test_passthrough_headers_e2e.py b/tests/e2e/llm_translation/test_passthrough_headers_e2e.py
index 045988334d5..95d5d0c3f6a 100644
--- a/tests/e2e/llm_translation/test_passthrough_headers_e2e.py
+++ b/tests/e2e/llm_translation/test_passthrough_headers_e2e.py
@@ -13,6 +13,8 @@ this specific request's header - not a stale or cached one - got there.
from __future__ import annotations
+import time
+
import pytest
from pydantic import BaseModel, Field
@@ -78,9 +80,39 @@ def _create_passthrough(client: PassthroughClient, *, path: str) -> PassThroughE
assert created.endpoints, "create returned no endpoints"
endpoint = created.endpoints[0]
assert endpoint.id, "created pass-through endpoint has no id"
+ _await_route_serving(client, path=path)
return endpoint
+def _await_route_serving(client: PassthroughClient, *, path: str) -> None:
+ """Block until the data plane routes `path`, instead of 404ing on it.
+
+ POST /config/pass_through_endpoint is a control-plane write; the worker that
+ serves the route only registers it on its next config reload, so a call issued
+ right after the create gets a bare 404 that looks like a broken route rather
+ than in-flight propagation. Measured at ~18s on a live proxy.
+ """
+ deadline = time.monotonic() + client.proxy.poll_timeout
+ while True:
+ # Any non-404 means the route is registered; this probe deliberately sends
+ # no anthropic-version so it is rejected upstream rather than billing a
+ # real completion on every poll.
+ result = client.proxy.transport.send(
+ path,
+ headers=client.proxy.transport.master,
+ json=_messages_body(),
+ )
+ if result.status_code != 404:
+ return
+ if time.monotonic() >= deadline:
+ raise AssertionError(
+ f"pass-through route {path!r} was created but never became routable on the "
+ f"data plane within {client.proxy.poll_timeout}s (config reload issue); "
+ f"last status {result.status_code}: {result.body[:200]}"
+ )
+ time.sleep(client.proxy.poll_interval)
+
+
def _delete_passthrough(client: PassthroughClient, endpoint_id: str) -> None:
_ = client.proxy.transport.delete(
"/config/pass_through_endpoint",
diff --git a/tests/e2e/llm_translation/test_responses_metadata_e2e.py b/tests/e2e/llm_translation/test_responses_metadata_e2e.py
deleted file mode 100644
index df854dcfa19..00000000000
--- a/tests/e2e/llm_translation/test_responses_metadata_e2e.py
+++ /dev/null
@@ -1,122 +0,0 @@
-"""Live e2e: /v1/responses with store + metadata (LIT-1201 customer path).
-
-Customers attach metadata and store=true, then continue with previous_response_id.
-Both turns must succeed, and any Redis keys written for the session must carry a
-positive TTL (not unbounded).
-"""
-
-from __future__ import annotations
-
-import os
-import socket
-import time
-
-import pytest
-from pydantic import BaseModel, ConfigDict
-
-from e2e_config import unique_marker
-from e2e_http import require_successful_call
-from endpoints_client import EndpointsClient, ResponsesResult
-from lifecycle import ResourceManager
-from models import LiteLLMParamsBody
-
-pytestmark = pytest.mark.e2e
-
-
-class ResponsesMetadataBody(BaseModel):
- model: str
- input: str
- store: bool = True
- metadata: dict[str, str]
- previous_response_id: str | None = None
- instructions: str | None = "You are a helpful assistant."
-
-
-class RedisKeyInfo(BaseModel):
- model_config = ConfigDict(frozen=True)
-
- key: str
- ttl: int
-
-
-def _redis_scan(marker: str) -> tuple[RedisKeyInfo, ...]:
- import redis
-
- host = os.environ["REDIS_HOST"]
- port = int((os.environ.get("REDIS_PORT") or "6379").strip() or "6379")
- try:
- with socket.create_connection((host, port), timeout=3):
- pass
- except OSError as exc:
- raise AssertionError(
- f"REDIS_HOST={host!r}:{port} unreachable ({exc}); "
- "LIT-1201 TTL check needs Redis the proxy writes to."
- ) from exc
-
- client = redis.Redis(host=host, port=port, decode_responses=True, socket_timeout=5)
- found: list[RedisKeyInfo] = []
- for key in client.scan_iter(match=f"*{marker}*", count=200):
- found.append(RedisKeyInfo(key=str(key), ttl=int(client.ttl(key))))
- return tuple(found)
-
-
-class TestResponsesMetadata:
- @pytest.mark.covers(
- "llm.responses.openai.basic.nonstream.works",
- "other.config.responses.metadata_redis_ttl_bounded",
- exercised_on=["responses"],
- )
- def test_store_metadata_continues_and_redis_keys_have_ttl(
- self, endpoints_client: EndpointsClient, resources: ResourceManager
- ) -> None:
- # Anthropic avoids OpenAI/Gemini quota flakes; Responses translation still
- # exercises store + metadata + previous_response_id on the proxy.
- marker = unique_marker()
- model = f"e2e-resp-meta-{marker}"
- model_id = endpoints_client.create_model(
- model,
- LiteLLMParamsBody(
- model="anthropic/claude-haiku-4-5-20251001",
- api_key="os.environ/ANTHROPIC_API_KEY",
- ),
- )
- resources.defer(lambda: endpoints_client.delete_model(model_id))
- key = resources.key()
-
- first = endpoints_client.proxy.transport.send(
- "/v1/responses",
- headers=endpoints_client.proxy.transport.bearer(key),
- json=ResponsesMetadataBody(
- model=model,
- input=f"Remember marker {marker}. Reply with one word.",
- metadata={"session_id": marker, "customer": "e2e"},
- ),
- )
- require_successful_call(first)
- parsed = ResponsesResult.model_validate_json(first.body)
- assert parsed.id, f"responses must return an id: {first.body[:300]}"
- assert parsed.text.strip(), f"responses returned empty text: {first.body[:300]}"
-
- second = endpoints_client.proxy.transport.send(
- "/v1/responses",
- headers=endpoints_client.proxy.transport.bearer(key),
- json=ResponsesMetadataBody(
- model=model,
- input="Reply with the single word ok.",
- previous_response_id=parsed.id,
- metadata={"session_id": marker, "turn": "2"},
- ),
- )
- require_successful_call(second)
- second_parsed = ResponsesResult.model_validate_json(second.body)
- assert second_parsed.text.strip(), (
- f"previous_response_id follow-up returned empty text: {second.body[:300]}"
- )
-
- time.sleep(1.0)
- keys = _redis_scan(marker)
- unbounded = tuple(k for k in keys if k.ttl == -1)
- assert not unbounded, (
- "responses metadata must not leave Redis keys without TTL (LIT-1201); "
- f"unbounded={unbounded}"
- )
diff --git a/tests/e2e/mcp/mcp_client.py b/tests/e2e/mcp/mcp_client.py
index f758a41cae6..4b1725bb205 100644
--- a/tests/e2e/mcp/mcp_client.py
+++ b/tests/e2e/mcp/mcp_client.py
@@ -11,12 +11,13 @@ request/response bodies are co-located here because only this suite speaks MCP.
from __future__ import annotations
+import time
from collections.abc import Mapping
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field, RootModel
-from e2e_http import Headers, NoBody, Result, unwrap
+from e2e_http import Headers, NoBody, Result, Success, unwrap
from models import KeyGenerateBody, ObjectPermission
from proxy_client import ProxyClient
@@ -223,6 +224,31 @@ class McpClient:
response_type=McpToolsListResponse,
)
+ def await_tool(self, key: str, server_id: str, needle: str) -> str:
+ """Poll tools/list until `server_id` serves a tool matching `needle`, and
+ return its fully-qualified name. Fails at poll_timeout.
+
+ /v1/mcp/server returns as soon as the DB row is written, but the gateway
+ runs the initialize + tools/list handshake against the upstream lazily on
+ the first request that needs it, and reports a server it has not
+ discovered yet exactly like a dead one: an empty tool list. Waiting is
+ what separates the two.
+ """
+ deadline = time.monotonic() + self.proxy.poll_timeout
+ while True:
+ result = self.list_tools(key)
+ if isinstance(result, Success):
+ tool_name = result.data.tool_name_containing(server_id, needle)
+ if tool_name is not None:
+ return tool_name
+ if time.monotonic() >= deadline:
+ raise AssertionError(
+ f"server {server_id} never served a tool matching {needle!r} within "
+ f"{self.proxy.poll_timeout}s of registration (upstream unreachable, or "
+ f"the key's grant was not applied); last tools/list: {result}"
+ )
+ time.sleep(self.proxy.poll_interval)
+
def register_mcp_content_filter(self, *, name: str, blocked_keyword: str) -> str:
"""Register a default-on content-filter guardrail that runs on the MCP
tool-call hook (pre_mcp_call) and blocks a single keyword. The keyword is
diff --git a/tests/e2e/mcp/test_mcp_datadog_e2e.py b/tests/e2e/mcp/test_mcp_datadog_e2e.py
index c772c4d3899..8a539b86bff 100644
--- a/tests/e2e/mcp/test_mcp_datadog_e2e.py
+++ b/tests/e2e/mcp/test_mcp_datadog_e2e.py
@@ -77,12 +77,7 @@ class TestDatadogMcpRoundTrip:
"within the poll deadline; MCP search would have nothing to find"
)
- tools = unwrap(client.list_tools(key))
- tool_name = tools.tool_name_containing(server_id, SEARCH_LOGS_TOOL)
- assert tool_name is not None, (
- f"granted key never saw {SEARCH_LOGS_TOOL} on server {server_id}; "
- f"tools={tools.tool_names_for_server(server_id)}"
- )
+ tool_name = client.await_tool(key, server_id, SEARCH_LOGS_TOOL)
call = unwrap(
client.call_tool(
diff --git a/tests/e2e/mcp/test_mcp_guardrail_e2e.py b/tests/e2e/mcp/test_mcp_guardrail_e2e.py
index 63239444454..dcab235465f 100644
--- a/tests/e2e/mcp/test_mcp_guardrail_e2e.py
+++ b/tests/e2e/mcp/test_mcp_guardrail_e2e.py
@@ -22,7 +22,7 @@ import pytest
from datadog_mcp import SEARCH_LOGS_TOOL, assert_dd_mcp_creds, register_datadog_mcp
from e2e_config import DD_SEARCH_FROM, unique_marker
-from e2e_http import Result, Success, UnknownApiError, unwrap
+from e2e_http import Result, Success, UnknownApiError
from lifecycle import ResourceManager
from mcp_client import McpCallToolResponse, McpClient, McpToolArguments
@@ -75,12 +75,7 @@ class TestMcpToolCallGuardrail:
key = client.generate_key(user_id=f"e2e-mcp-guard-{marker}", mcp_servers=[server_id])
resources.defer(lambda: client.proxy.delete_key(key))
- tools = unwrap(client.list_tools(key))
- tool_name = tools.tool_name_containing(server_id, SEARCH_LOGS_TOOL)
- assert tool_name is not None, (
- f"granted key never saw {SEARCH_LOGS_TOOL} on server {server_id}; "
- f"tools={tools.tool_names_for_server(server_id)}"
- )
+ tool_name = client.await_tool(key, server_id, SEARCH_LOGS_TOOL)
def search(query: str) -> Result[McpCallToolResponse]:
arguments: McpToolArguments = {
diff --git a/tests/e2e/mcp/test_mcp_key_access_e2e.py b/tests/e2e/mcp/test_mcp_key_access_e2e.py
index 412b33d244a..4aeb811a64f 100644
--- a/tests/e2e/mcp/test_mcp_key_access_e2e.py
+++ b/tests/e2e/mcp/test_mcp_key_access_e2e.py
@@ -48,12 +48,7 @@ class TestMcpKeyWithoutAccessIsDenied:
permitted_key = _key(client, resources, mcp_servers=[server_id])
denied_key = _key(client, resources, mcp_servers=None)
- permitted = unwrap(client.list_tools(permitted_key))
- tool_name = permitted.tool_name_containing(server_id, SEARCH_LOGS_TOOL)
- assert tool_name is not None, (
- f"granted key did not see {SEARCH_LOGS_TOOL} (upstream dead or grant not applied): "
- f"{permitted.tool_names_for_server(server_id)}"
- )
+ _ = client.await_tool(permitted_key, server_id, SEARCH_LOGS_TOOL)
denied_tools = unwrap(client.list_tools(denied_key)).tool_names_for_server(server_id)
assert denied_tools == frozenset(), (
@@ -73,12 +68,7 @@ class TestMcpKeyWithoutAccessIsDenied:
permitted_key = _key(client, resources, mcp_servers=[server_id])
denied_key = _key(client, resources, mcp_servers=None)
- permitted = unwrap(client.list_tools(permitted_key))
- tool_name = permitted.tool_name_containing(server_id, SEARCH_LOGS_TOOL)
- assert tool_name is not None, (
- f"granted key did not discover {SEARCH_LOGS_TOOL} (upstream dead or grant not applied): "
- f"{permitted.tool_names_for_server(server_id)}"
- )
+ tool_name = client.await_tool(permitted_key, server_id, SEARCH_LOGS_TOOL)
search_args = {
"query": "service:litellm",