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
fix(e2e): assert on the gen-AI span that served the stream, not the span count (#36582)
Yassin Kortama0d499e131c0
diff --git a/tests/e2e/logging/test_otel_trace_e2e.py b/tests/e2e/logging/test_otel_trace_e2e.pyindex b0a4988594e..747fb548e9b 100644--- a/tests/e2e/logging/test_otel_trace_e2e.py+++ b/tests/e2e/logging/test_otel_trace_e2e.py@@ -150,13 +150,41 @@ def _tag(span: JaegerSpan, key: str) -> str | int | float | bool | None:#: chunk (stamped only for streaming; added in #32236).TTFT_TAG = "gen_ai.response.time_to_first_chunk"+#: Jaeger's rendering of a span whose OTEL status is ERROR.+ERROR_STATUS_TAG = "otel.status_code"+++def served_genai_spans(trace: JaegerTrace, genai_span: str) -> list[JaegerSpan]:+ """The gen-AI spans for attempts that actually served the request.++ The proxy opens one gen-AI span per upstream attempt, so a call the router+ retried carries an error span for every failed attempt beside the one that+ answered. Only the served attempt streams chunks, so only it records TTFT+ or a streaming flag; asserting over the raw span list makes every one of+ these tests fail whenever the upstream 429s, 529s, or hands back a stale+ credential on the first try."""+ return [+ span+ for span in trace.spans+ if span.operation_name == genai_span and _tag(span, ERROR_STATUS_TAG) != "ERROR"+ ]+++def one_served_genai_span(trace: JaegerTrace, genai_span: str) -> JaegerSpan:+ served = served_genai_spans(trace, genai_span)+ assert len(served) == 1, (+ f"a streamed call must produce exactly ONE served gen-AI span, got {len(served)}; "+ f"spans: {trace.span_names()}"+ )+ return served[0]+def _assert_real_ttft(hits: list[JaegerTrace], *, genai_span: str) -> None:- """The enforced behavior: the streamed call's single gen-AI span records a- TTFT that is a real measurement - present, numeric, positive, and strictly- less than the span's own total duration. A TTFT of zero, or one at/above- the full span duration, is a clock artifact rather than first-token- latency."""+ """The enforced behavior: the gen-AI span for the attempt that served the+ stream records a TTFT that is a real measurement - present, numeric,+ positive, and strictly less than that span's own total duration. A TTFT of+ zero, or one at/above the span duration, is a clock artifact rather than+ first-token latency."""assert hits, ("no trace for this call arrived at the destination within the deadline ""(nothing tagged with its call id was found)"@@ -166,12 +194,7 @@ def _assert_real_ttft(hits: list[JaegerTrace], *, genai_span: str) -> None:f"{[(t.trace_id, t.span_names()) for t in hits]}")trace = hits[0]- spans = [span for span in trace.spans if span.operation_name == genai_span]- assert len(spans) == 1, (- f"a streamed call must produce exactly ONE gen-AI span, got {len(spans)}; "- f"spans: {trace.span_names()}"- )- span = spans[0]+ span = one_served_genai_span(trace, genai_span)value = _tag(span, TTFT_TAG)assert value is not None, (@@ -412,12 +435,8 @@ class TestOtelTraceCompleteness:)_assert_complete_trace(hits, route=route, genai_span=genai_span)- genai_spans = [span for span in hits[0].spans if span.operation_name == genai_span]- assert len(genai_spans) == 1, (- f"a streamed call must produce exactly ONE gen-AI span, got {len(genai_spans)}; "- f"spans: {hits[0].span_names()}"- )- assert _tag(genai_spans[0], "litellm.request.streaming") is True, (+ served = one_served_genai_span(hits[0], genai_span)+ assert _tag(served, "litellm.request.streaming") is True, ("the gen-AI span must record litellm.request.streaming=true; its absence means ""the stream flag was dropped before the model call")@@ -468,12 +487,8 @@ class TestOtelTraceCompleteness:)_assert_complete_trace(hits, route=route, genai_span=genai_span)- genai_spans = [span for span in hits[0].spans if span.operation_name == genai_span]- assert len(genai_spans) == 1, (- f"a streamed call must produce exactly ONE gen-AI span, got {len(genai_spans)}; "- f"spans: {hits[0].span_names()}"- )- assert _tag(genai_spans[0], "litellm.request.streaming") is True, (+ served = one_served_genai_span(hits[0], genai_span)+ assert _tag(served, "litellm.request.streaming") is True, ("the gen-AI span must record litellm.request.streaming=true; its absence means ""the stream flag was dropped before the model call")@@ -526,11 +541,7 @@ class TestOtelTraceCompleteness:)_assert_complete_trace(hits, route=route, genai_span=genai_span, require_cost_span=False)- genai_spans = [span for span in hits[0].spans if span.operation_name == genai_span]- assert len(genai_spans) == 1, (- f"a streamed call must produce exactly ONE gen-AI span, got {len(genai_spans)}; "- f"spans: {hits[0].span_names()}"- )+ one_served_genai_span(hits[0], genai_span)spend_row = client.poll_proxy_spend_for_key(key)assert spend_row is not None and spend_row.spend is not None and spend_row.spend > 0, (diff --git a/tests/e2e/logging/test_span_selection.py b/tests/e2e/logging/test_span_selection.pynew file mode 100644index 00000000000..6edf42a896a--- /dev/null+++ b/tests/e2e/logging/test_span_selection.py@@ -0,0 +1,83 @@+"""Harness coverage for the gen-AI span selection in `test_otel_trace_e2e`.++Carries no `e2e` marker: this exercises the selection helper itself against+Jaeger-shaped payloads, so it runs whether or not a proxy is up. The live+assertions it protects are expensive to reproduce (they need an upstream that+fails the first attempt), which is exactly why the helper is worth pinning+here.+"""++from __future__ import annotations++import pytest+from otel_client import JaegerTrace+from test_otel_trace_e2e import TTFT_TAG, one_served_genai_span, served_genai_spans++GENAI_SPAN = "chat claude-haiku-4-5"+++def _span(name: str, *, failed: bool = False, ttft: float | None = None) -> dict[str, object]:+ tags: list[dict[str, object]] = []+ if failed:+ tags.append({"key": "otel.status_code", "value": "ERROR"})+ tags.append({"key": "error.type", "value": "AuthenticationError"})+ if ttft is not None:+ tags.append({"key": TTFT_TAG, "value": ttft})+ return {"spanID": f"{name}-{len(tags)}-{failed}-{ttft}", "operationName": name, "tags": tags}+++def _trace(*spans: dict[str, object]) -> JaegerTrace:+ return JaegerTrace.model_validate({"traceID": "t1", "spans": list(spans)})+++def test_served_span_is_the_only_one_when_nothing_was_retried() -> None:+ trace = _trace(_span("POST /chat/completions"), _span(GENAI_SPAN, ttft=0.3))++ assert [span.operation_name for span in served_genai_spans(trace, GENAI_SPAN)] == [GENAI_SPAN]+++def test_retried_attempt_span_is_excluded() -> None:+ """The real shape from a stage trace: the first attempt 401s and records no+ TTFT, the retry serves the stream. The served attempt is the one the TTFT+ assertions must run against."""+ trace = _trace(+ _span(GENAI_SPAN, failed=True),+ _span(GENAI_SPAN, ttft=0.52),+ )++ served = one_served_genai_span(trace, GENAI_SPAN)++ assert [tag.value for tag in served.tags if tag.key == TTFT_TAG] == [0.52]+++def test_several_failed_attempts_still_leave_one_served_span() -> None:+ trace = _trace(+ _span(GENAI_SPAN, failed=True),+ _span(GENAI_SPAN, failed=True),+ _span(GENAI_SPAN, failed=True),+ _span(GENAI_SPAN, ttft=0.1),+ )++ assert len(served_genai_spans(trace, GENAI_SPAN)) == 1+++def test_two_served_spans_still_fail() -> None:+ """The regression the count assertion exists for: one streamed call must+ not be logged as two served gen-AI spans."""+ trace = _trace(_span(GENAI_SPAN, ttft=0.2), _span(GENAI_SPAN, ttft=0.4))++ with pytest.raises(AssertionError, match="exactly ONE served gen-AI span, got 2"):+ one_served_genai_span(trace, GENAI_SPAN)+++def test_all_attempts_failed_is_a_failure_not_a_pass() -> None:+ trace = _trace(_span(GENAI_SPAN, failed=True), _span(GENAI_SPAN, failed=True))++ with pytest.raises(AssertionError, match="exactly ONE served gen-AI span, got 0"):+ one_served_genai_span(trace, GENAI_SPAN)+++def test_other_operations_are_not_counted() -> None:+ trace = _trace(_span("chat gpt-5.5", ttft=0.3), _span(GENAI_SPAN, ttft=0.3))++ assert len(served_genai_spans(trace, GENAI_SPAN)) == 1