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(e2e): otel trace completeness on /chat/completions (#33132)
yucheng-berri948a43cd64cc
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.ymlindex 0cfbb5b0b66..12f47331dbb 100644--- a/tests/e2e/docker-compose.yml+++ b/tests/e2e/docker-compose.yml@@ -18,6 +18,12 @@ configs:type: redishost: redisport: 6379+ # OTEL v2 trace destination for the logging suite's trace-completeness+ # tests: the arize_phoenix preset is OTLP with a configurable endpoint+ # (PHOENIX_COLLECTOR_HTTP_ENDPOINT below points it at the jaeger service),+ # so gen-AI spans export through a preset-owned provider - the code path+ # where trace splits actually happen - with no cloud credentials needed.+ callbacks: ["arize_phoenix"]router_settings:routing_strategy: simple-shuffle@@ -68,9 +74,14 @@ services:condition: service_healthyredis:condition: service_healthy+ jaeger:+ condition: service_healthyenv_file: .envenvironment:LITELLM_MASTER_KEY: sk-1234+ LITELLM_OTEL_V2: "true"+ PHOENIX_COLLECTOR_HTTP_ENDPOINT: http://jaeger:4318/v1/traces+ PHOENIX_API_KEY: local-jaeger-noauthDATABASE_URL: postgresql://litellm:litellm@db:5432/litellmUI_USERNAME: adminUI_PASSWORD: sk-1234@@ -114,3 +125,15 @@ services:interval: 3stimeout: 3sretries: 20++# throwaway OTEL trace destination (OTLP ingest on 4318 inside the network,+# query API on host 16686 for test read-back; see E2E_OTEL_QUERY_URL)+ jaeger:+ image: jaegertracing/all-in-one:1.62.0+ ports:+ - "16686:16686"+ healthcheck:+ test: ["CMD", "wget", "-qO-", "http://localhost:14269/"]+ interval: 3s+ timeout: 3s+ retries: 20diff --git a/tests/e2e/e2e_config.py b/tests/e2e/e2e_config.pyindex 75bd715a23a..6bfec2b514e 100644--- a/tests/e2e/e2e_config.py+++ b/tests/e2e/e2e_config.py@@ -24,6 +24,13 @@ CONTROL_PLANE_BASE_URL = os.environ.get(UI_USERNAME = os.environ.get("E2E_UI_USERNAME", "admin")UI_PASSWORD = os.environ.get("E2E_UI_PASSWORD", MASTER_KEY)+CHEAP_ANTHROPIC_MODEL = os.environ.get("E2E_CHEAP_ANTHROPIC_MODEL", "claude-haiku-4-5")++# Jaeger query API of the compose stack's OTEL trace destination (the `jaeger`+# service in docker-compose.yml maps it to host 16686). Trace-completeness tests+# read exported spans back through it.+OTEL_QUERY_URL = os.environ.get("E2E_OTEL_QUERY_URL", "http://localhost:16686").rstrip("/")+# Writes on the proxy are eventually consistent (e.g. spend rows flush on# proxy_batch_write_at, ~60s). Read-backs poll to this deadline, never sleep-once.POLL_TIMEOUT = float(os.environ.get("E2E_POLL_TIMEOUT", "120"))diff --git a/tests/e2e/logging/conftest.py b/tests/e2e/logging/conftest.pyindex 567355f23ac..43d279602ef 100644--- a/tests/e2e/logging/conftest.py+++ b/tests/e2e/logging/conftest.py@@ -11,6 +11,7 @@ import osimport pytestfrom logging_client import LangfuseCreds, LoggingClient, build_logging_client, load_langfuse_creds+from otel_client import OtelReader, build_otel_readerdef pytest_configure(config: pytest.Config) -> None:@@ -28,6 +29,12 @@ def client() -> LoggingClient:return build_logging_client()[email protected](scope="session")+def otel_reader() -> OtelReader:+ """Read-back client for the compose stack's Jaeger trace destination."""+ return build_otel_reader()++@pytest.fixturedef datadog_creds() -> None:"""Require Datadog shipping credentials. Hard-fail when absent; never skip."""diff --git a/tests/e2e/logging/otel_client.py b/tests/e2e/logging/otel_client.pynew file mode 100644index 00000000000..f4a0e4fe102--- /dev/null+++ b/tests/e2e/logging/otel_client.py@@ -0,0 +1,138 @@+"""Jaeger read-back for the OTEL trace-completeness tests: typed models over the+Jaeger query API (the destination's own API - completeness is judged on what the+backend actually holds, never on "export succeeded" proxy-side).++Traces are fetched server-side by the ``litellm.call_id`` tag the gen-AI span+carries (the request's x-litellm-call-id response header), so read-back is+immune to the query page filling up with unrelated traffic (background jobs,+other suites sharing the stack). Jaeger returns every span of a matching trace,+so the completeness assertions see the whole tree. A failed query is a hard+failure, never an empty result - an unreachable destination must not read as+"the trace never arrived".++External reads go through ``e2e_http`` (the only module allowed to call+``requests.*``).+"""++from __future__ import annotations++import json+import time+from dataclasses import dataclass++import pytest+from pydantic import BaseModel, ConfigDict, Field++from e2e_config import OTEL_QUERY_URL, POLL_INTERVAL, POLL_TIMEOUT+from e2e_http import URL, NoBody, Success, get++#: OTEL resource service.name the proxy exports under (OTEL_SERVICE_NAME default).+JAEGER_SERVICE = "litellm"+#: Span tag carrying the request's x-litellm-call-id (stamped on the gen-AI span).+CALL_ID_TAG = "litellm.call_id"+++class JaegerTag(BaseModel):+ model_config = ConfigDict(extra="ignore")++ key: str+ value: str | int | float | bool | None = None+++class JaegerReference(BaseModel):+ model_config = ConfigDict(extra="ignore", populate_by_name=True)++ ref_type: str = Field(alias="refType")+ trace_id: str = Field(alias="traceID")+ span_id: str = Field(alias="spanID")+++class JaegerSpan(BaseModel):+ model_config = ConfigDict(extra="ignore", populate_by_name=True)++ span_id: str = Field(alias="spanID")+ operation_name: str = Field(alias="operationName")+ start_time: int = Field(default=0, alias="startTime")+ references: list[JaegerReference] = []+ tags: list[JaegerTag] = []++ @property+ def kind(self) -> str:+ for tag in self.tags:+ if tag.key == "span.kind":+ return str(tag.value)+ return ""+++class JaegerTrace(BaseModel):+ model_config = ConfigDict(extra="ignore", populate_by_name=True)++ trace_id: str = Field(alias="traceID")+ spans: list[JaegerSpan] = []++ def span_names(self) -> list[str]:+ return sorted(span.operation_name for span in self.spans)+++class JaegerTracesPage(BaseModel):+ model_config = ConfigDict(extra="ignore")++ data: list[JaegerTrace] = []+++class _TracesQuery(BaseModel):+ service: str+ tags: str+ limit: int = 20+ lookback: str = "1h"+++def _settled(trace: JaegerTrace, names: set[str], prefixes: set[str]) -> bool:+ present = set(trace.span_names())+ return names.issubset(present) and all(+ any(name.startswith(prefix) for name in present) for prefix in prefixes+ )+++@dataclass(frozen=True, slots=True)+class OtelReader:+ query_url: str++ def traces_for_call(self, call_id: str) -> list[JaegerTrace]:+ """Every trace holding a span tagged with this call id. Jaeger matches+ spans server-side and returns their full traces; more than one hit for+ one call IS the split-trace bug, so this never collapses to one."""+ result = get(+ URL(f"{self.query_url}/api/traces"),+ headers=NoBody(),+ params=_TracesQuery(service=JAEGER_SERVICE, tags=json.dumps({CALL_ID_TAG: call_id})),+ response_type=JaegerTracesPage,+ timeout=30.0,+ )+ match result:+ case Success(data=page):+ return page.data+ case failure:+ pytest.fail(f"Jaeger query API at {self.query_url} failed: {failure}")++ def poll_traces_for_call(+ self, *, call_id: str, settled_names: set[str], settled_prefixes: set[str]+ ) -> list[JaegerTrace]:+ """Poll until exactly one trace holds the call and it carries every span+ name in ``settled_names`` plus at least one name per prefix in+ ``settled_prefixes`` (spans flush in batches, the cost write lands after+ the response), then return the hits. At the deadline the last hits are+ returned as-is so the caller's assertions report the real final state -+ on a split trace this never settles and the orphan comes back."""+ deadline = time.monotonic() + POLL_TIMEOUT+ hits: list[JaegerTrace] = []+ while time.monotonic() < deadline:+ hits = self.traces_for_call(call_id)+ if len(hits) == 1 and _settled(hits[0], settled_names, settled_prefixes):+ return hits+ time.sleep(POLL_INTERVAL)+ return hits+++def build_otel_reader() -> OtelReader:+ return OtelReader(query_url=OTEL_QUERY_URL)diff --git a/tests/e2e/logging/test_otel_trace_e2e.py b/tests/e2e/logging/test_otel_trace_e2e.pynew file mode 100644index 00000000000..d445da3dff0--- /dev/null+++ b/tests/e2e/logging/test_otel_trace_e2e.py@@ -0,0 +1,191 @@+"""Live e2e: OTEL trace completeness on the admin-owned destination (LIT-3787).++Covers logging.otel.success.exports_metric: a successful non-streaming call must+land at the OTEL destination as ONE connected trace - a single root SERVER span+with the auth phase, db lookups, and cost write under it, and the gen-AI CLIENT+span parented into the same tree. The regression this pins: the proxy publishing+the global TracerProvider before callbacks init made server spans export through+a different provider than the preset's gen-AI spans, so the destination received+the gen-AI span alone, dangling (fixed in #30590; verified failing at its parent+commit 1bd603d1ac).++Both halves of the contract are asserted: the recorded state (the proxy reports+the OTEL v2 logger active via /health/readiness/details) and the enforced+behavior (the complete span tree at the destination, read back through the+destination's own query API - never proxy-side "export succeeded" logs).+"""++from __future__ import annotations++import time+from collections.abc import Callable++import pytest+from pydantic import BaseModel, ConfigDict++from e2e_config import CHEAP_ANTHROPIC_MODEL, unique_marker+from e2e_http import NoBody, StreamingResponse, require_successful_call+from lifecycle import ResourceManager+from logging_client import LoggingClient+from otel_client import JaegerTrace, OtelReader++pytestmark = pytest.mark.e2e++MODEL = CHEAP_ANTHROPIC_MODEL+COST_SPAN = "batch_write_to_db _PROXY_track_cost_callback"+DB_SPAN_PREFIX = "postgres "+#: The active OTEL v2 logger's name in /health/readiness/details success_callbacks.+OTEL_V2_LOGGER_NAME = "OpenTelemetryV2"+++class _ReadinessDetails(BaseModel):+ model_config = ConfigDict(extra="ignore")++ success_callbacks: list[str] = []+++def _assert_otel_destination_configured(client: LoggingClient) -> None:+ """Recorded state: the proxy reports the OTEL v2 logger among its active+ callbacks, so a missing/failed destination config fails here, before any+ traffic-based assertion can time out confusingly."""+ result = client.gateway.probe("/health/readiness/details", params=NoBody())+ assert result.status_code == 200, (+ f"/health/readiness/details must answer 200, got {result.status_code}: {result.body[:300]}"+ )+ details = _ReadinessDetails.model_validate_json(result.body)+ assert OTEL_V2_LOGGER_NAME in details.success_callbacks, (+ f"the proxy must report the {OTEL_V2_LOGGER_NAME} callback active "+ f"(LITELLM_OTEL_V2 + arize_phoenix preset in the compose config); got: {details.success_callbacks}"+ )+++def _first_ok(client: LoggingClient, send: Callable[[], StreamingResponse]) -> StreamingResponse:+ """First successful call on a fresh key. A fresh key may briefly 401 until+ the data plane's auth cache picks it up, so retry on 401 to a deadline; a+ 401 is rejected before the LLM call so it exports no gen-AI span and cannot+ contaminate the trace assertions. Any other failure is behavior under test+ and fails hard."""+ deadline = time.monotonic() + client.gateway.poll_timeout+ while True:+ outcome = send()+ if outcome.ok:+ return outcome+ if outcome.status_code != 401 or time.monotonic() >= deadline:+ require_successful_call(outcome)+ time.sleep(client.gateway.poll_interval)+++def _parent_ids(span_id: str, trace: JaegerTrace) -> list[str]:+ span = next(s for s in trace.spans if s.span_id == span_id)+ return [ref.span_id for ref in span.references if ref.ref_type == "CHILD_OF"]+++def _chain_reaches(span_id: str, root_id: str, trace: JaegerTrace) -> bool:+ """Walk parent references (within the trace) from span_id up to root_id."""+ seen: set[str] = set()+ in_trace = {s.span_id for s in trace.spans}+ current = span_id+ while current not in seen:+ if current == root_id:+ return True+ seen.add(current)+ parents = [p for p in _parent_ids(current, trace) if p in in_trace]+ if not parents:+ return False+ current = parents[0]+ return False+++def _assert_complete_trace(hits: list[JaegerTrace], *, route: str, genai_span: str) -> None:+ """The enforced behavior: the destination holds exactly one trace for the+ call, rooted at the SERVER span, with auth/db/cost children and the gen-AI+ span all connected into that one tree - no dangling parent references."""+ assert hits, (+ "no trace for this call arrived at the destination within the deadline "+ "(nothing tagged with its call id was found)"+ )+ assert len(hits) == 1, (+ f"expected exactly ONE trace for the call, got {len(hits)}: "+ f"{[(t.trace_id, t.span_names()) for t in hits]} - more than one trace for "+ "one call is the split-trace bug (gen-AI span exported away from its root)"+ )+ trace = hits[0]+ names = trace.span_names()+ in_trace = {span.span_id for span in trace.spans}++ dangling = [+ span.operation_name+ for span in trace.spans+ if span.references and not any(ref.span_id in in_trace for ref in span.references)+ ]+ assert not dangling, (+ f"span(s) {dangling} reference a parent that never reached the destination "+ f"(orphaned trace); spans present: {names}"+ )++ roots = [span for span in trace.spans if not span.references]+ assert len(roots) == 1, f"expected exactly one root span, got {[s.operation_name for s in roots]}; spans: {names}"+ root = roots[0]+ assert root.operation_name == f"POST {route}", (+ f"the root must be the SERVER span 'POST {route}', got {root.operation_name!r}"+ )+ assert root.kind == "server", f"the root span must have kind=server, got {root.kind!r}"++ assert f"auth {route}" in names, f"auth phase span 'auth {route}' missing; spans: {names}"+ assert any(name.startswith(DB_SPAN_PREFIX) for name in names), (+ f"no db ('{DB_SPAN_PREFIX}*') span in the trace; spans: {names}"+ )+ assert COST_SPAN in names, f"cost write span {COST_SPAN!r} missing; spans: {names}"++ genai = next((span for span in trace.spans if span.operation_name == genai_span), None)+ assert genai is not None, f"gen-AI span {genai_span!r} missing; spans: {names}"+ assert genai.kind == "client", f"gen-AI span must have kind=client, got {genai.kind!r}"+ assert _chain_reaches(genai.span_id, root.span_id, trace), (+ f"gen-AI span {genai_span!r} is in the trace but its parent chain does not "+ f"reach the root SERVER span; spans: {names}"+ )+++def _settled_names(*, route: str, genai_span: str) -> set[str]:+ return {f"POST {route}", f"auth {route}", COST_SPAN, genai_span}+++class TestOtelTraceCompleteness:+ @pytest.mark.covers("logging.otel.success.exports_metric")+ def test_chat_completions_exports_complete_trace(+ self, client: LoggingClient, otel_reader: OtelReader, resources: ResourceManager+ ) -> None:+ """This test verifies that a successful non-streaming+ /chat/completions request produces one complete OTEL trace.++ The trace should have a single server root span for the incoming request, with+ the authentication, database, and cost-recording work beneath it. The span for+ the actual model call must also belong to that same trace, rather than being+ exported separately with a missing parent.++ This matters because a split trace is easy to miss: all of the spans may still+ arrive, but the model call appears without the surrounding request context.+ That makes it difficult to understand where time was spent, connect the model+ cost to the original request, or investigate a slow or failed call.++ /chat/completions is the main OpenAI-compatible route used by most customers,+ so it is important that trace parenting works correctly on this path.+ """+ route = "/chat/completions"+ _assert_otel_destination_configured(client)++ key = client.key_with_alias(f"otel-trace-chat-{unique_marker()}", models=[MODEL])+ resources.defer(lambda: client.delete_key(key))++ marker = unique_marker()+ outcome = _first_ok(+ client, lambda: client.chat_raw(key, MODEL, f"reply with one word {marker}", max_tokens=16)+ )+ assert outcome.call_id is not None, "success response must carry x-litellm-call-id"++ hits = otel_reader.poll_traces_for_call(+ call_id=outcome.call_id,+ settled_names=_settled_names(route=route, genai_span=f"chat {MODEL}"),+ settled_prefixes={DB_SPAN_PREFIX},+ )+ _assert_complete_trace(hits, route=route, genai_span=f"chat {MODEL}")