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): failed request error span carries the full untruncated message and status (LIT-4179) (#33304)
yucheng-berrid6f498ff5cef
diff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.ymlindex 12f47331dbb..e2bb6ca8933 100644--- a/tests/e2e/docker-compose.yml+++ b/tests/e2e/docker-compose.yml@@ -79,6 +79,7 @@ services:env_file: .envenvironment:LITELLM_MASTER_KEY: sk-1234+ STORE_MODEL_IN_DB: "True"LITELLM_OTEL_V2: "true"PHOENIX_COLLECTOR_HTTP_ENDPOINT: http://jaeger:4318/v1/tracesPHOENIX_API_KEY: local-jaeger-noauthdiff --git a/tests/e2e/logging/test_otel_trace_e2e.py b/tests/e2e/logging/test_otel_trace_e2e.pyindex 64df851fd5c..b00fd91be3c 100644--- a/tests/e2e/logging/test_otel_trace_e2e.py+++ b/tests/e2e/logging/test_otel_trace_e2e.py@@ -21,12 +21,13 @@ import timefrom collections.abc import Callableimport pytest-from pydantic import BaseModel, ConfigDict+from pydantic import BaseModel, ConfigDict, ValidationErrorfrom e2e_config import CHEAP_ANTHROPIC_MODEL, CHEAP_OPENAI_MODEL, unique_markerfrom e2e_http import NoBody, StreamingResponse, require_successful_callfrom lifecycle import ResourceManager-from logging_client import LoggingClient+from logging_client import INVALID_UPSTREAM_API_KEY, LoggingClient+from models import LiteLLMParamsBodyfrom otel_client import JaegerSpan, JaegerTrace, OtelReaderpytestmark = pytest.mark.e2e@@ -161,6 +162,69 @@ def _tag(span: JaegerSpan, key: str) -> str | int | float | bool | None:return None+#: The attribute contract a failed call's gen-AI span must carry (LIT-4179), as+#: one reviewable payload. Exact-match values; error.message is additionally+#: proven untruncated by _assert_error_span_contract, which parses the provider+#: error JSON embedded in it - a truncated message stops parsing.+EXPECTED_ERROR_SPAN_ATTRIBUTES: dict[str, str] = {+ "error": "True",+ "error.type": "AuthenticationError",+ "otel.status_code": "ERROR",+ "litellm.provider.error.code": "401",+ "litellm.provider.error.llm_provider": "anthropic",+}+++class _ProviderErrorDetail(BaseModel):+ model_config = ConfigDict(extra="ignore")++ type: str+ message: str+++class _ProviderError(BaseModel):+ """The provider error JSON embedded in error.message; validating it proves+ the attribute survived untruncated (a cut-off message stops parsing)."""++ model_config = ConfigDict(extra="ignore")++ error: _ProviderErrorDetail+++def _assert_error_span_contract(span: JaegerSpan) -> None:+ """The failed call's gen-AI span carries the LIT-4179 error contract: the+ exact attributes in EXPECTED_ERROR_SPAN_ATTRIBUTES, plus an untruncated+ error.message whose embedded provider error JSON still parses and whose+ text also rides the span status description."""+ for key, expected in EXPECTED_ERROR_SPAN_ATTRIBUTES.items():+ actual = _tag(span, key)+ assert str(actual) == expected, f"error span attribute {key!r} must be {expected!r}, got {actual!r}"++ message = _tag(span, "error.message")+ assert isinstance(message, str) and message, "error span must carry a non-empty error.message"+ assert "AnthropicException" in message, (+ f"error.message must carry the upstream provider exception, got: {message[:200]}"+ )+ start, end = message.find("{"), message.rfind("}")+ assert start != -1 and end > start, (+ f"error.message carries no parseable provider error JSON (truncated?): {message[:200]}"+ )+ try:+ provider_error = _ProviderError.model_validate_json(message[start : end + 1])+ except ValidationError:+ pytest.fail(f"the embedded provider error JSON does not parse (truncated?): {message[:300]}")+ assert provider_error.error.message == "invalid x-api-key", (+ f"the embedded provider error must survive untruncated; parsed: {provider_error}"+ )+ assert _tag(span, "otel.status_description") == message, (+ "the span status description must carry the same untruncated message as error.message"+ )+ stack = _tag(span, "litellm.provider.error.stack_trace")+ assert isinstance(stack, str) and stack, (+ "the error span must carry a non-empty litellm.provider.error.stack_trace"+ )++class TestOtelTraceCompleteness:@pytest.mark.covers("logging.otel.success.exports_metric", exercised_on=["chat_completions"])def test_chat_completions_exports_complete_trace(@@ -444,3 +508,62 @@ class TestOtelTraceCompleteness:assert spend_row.call_type == "aresponses", (f"the spend row must be attributed to the responses call type, got {spend_row.call_type!r}")++ @pytest.mark.covers("logging.otel.failure.exports_metric", exercised_on=["chat_completions"])+ def test_failed_chat_completions_error_span_attributes(+ self, client: LoggingClient, otel_reader: OtelReader, resources: ResourceManager+ ) -> None:+ """This test checks that a failed `/chat/completions` request produces a+ single, complete OTEL trace. The model-call span should include all+ expected error attributes, a non-empty stack trace, and the full,+ untruncated `error.message`. The provider error embedded in that+ message must also remain valid JSON. The root server span should+ record the same 401 response returned to the client.++ The test uses a deployment with an invalid upstream API key. This+ allows the request to pass LiteLLM’s proxy authentication and fail at+ the provider, which is necessary to generate a model-call error span.+ There should be no cost-write span because failed requests are not+ billed."""+ route = "/chat/completions"+ _assert_otel_destination_configured(client)++ model_name = f"otel-err-{unique_marker()}"+ model_id = client.create_model(+ model_name,+ LiteLLMParamsBody(model="anthropic/claude-haiku-4-5", api_key=INVALID_UPSTREAM_API_KEY),+ )+ resources.defer(lambda: client.delete_model(model_id))+ key = client.key_with_alias(f"otel-err-{unique_marker()}", models=[model_name])+ resources.defer(lambda: client.delete_key(key))++ deadline = time.monotonic() + client.gateway.poll_timeout+ while True:+ outcome = client.chat_raw(key, model_name, "trigger an upstream auth failure", max_tokens=16)+ assert not outcome.ok, "the call must fail; the deployment's upstream key is invalid"+ if "AnthropicException" in outcome.body or time.monotonic() >= deadline:+ break+ time.sleep(client.gateway.poll_interval)+ assert "AnthropicException" in outcome.body, (+ "never saw the upstream provider failure before the deadline; the key may still be "+ f"propagating - last outcome {outcome.status_code}: {outcome.body[:200]}"+ )+ assert outcome.status_code == 401, (+ f"an upstream auth failure must map to 401, got {outcome.status_code}: {outcome.body[:200]}"+ )+ assert outcome.call_id is not None, "failed responses must still carry x-litellm-call-id"++ genai_span = f"chat {model_name}"+ hits = otel_reader.poll_traces_for_call(+ call_id=outcome.call_id,+ settled_names=_settled_names(route=route, genai_span=genai_span, require_cost_span=False),+ settled_prefixes={DB_SPAN_PREFIX},+ )+ _assert_complete_trace(hits, route=route, genai_span=genai_span, require_cost_span=False)++ root = next(span for span in hits[0].spans if not span.references)+ assert str(_tag(root, "http.status_code")) == "401", (+ f"the SERVER span must record the 401 the client received, got {_tag(root, 'http.status_code')!r}"+ )+ genai = next(span for span in hits[0].spans if span.operation_name == genai_span)+ _assert_error_span_contract(genai)