Repository navigation
fix(otel): stamp http.response.status_code on all error responses #28405
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yuneng-berri
merged 7 commits into
litellm_internal_staging
from
litellm_otel_http_status_all_errors
May 23, 2026
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
249e54a
fix(otel): stamp http.response.status_code on all error responses
ryan-crabbe-berri 239a1c9
test(otel): exercise httpx.HTTPStatusError through admin path
ryan-crabbe-berri 1a0382f
chore(otel): trim verbose comments in LIT-3193 changes
ryan-crabbe-berri e4035ca
fix(otel): set span.status on management hook parent SERVER span
ryan-crabbe-berri f343868
fix(otel): close SERVER span on body-validation and unhandled errors
ryan-crabbe-berri 560bacb
fix(otel): generic 500 body, log exception details server-side
ryan-crabbe-berri 02863df
fix(otel): stamp http.response.status_code on every SERVER span path
ryan-crabbe-berri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
109 changes: 109 additions & 0 deletions
109
tests/test_litellm/integrations/open_telemetry/_helpers.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| """ | ||
| Helpers for the LIT-3193 OTEL HTTP-attribute matrix. | ||
|
|
||
| Module split from ``conftest.py`` because pytest auto-discovers fixtures but | ||
| forbids ``from .conftest import …`` (no parent package). Fixtures stay in | ||
| ``conftest.py``; pure helpers (assertions, exception factories, attribute | ||
| constants) live here so test modules can ``from ._helpers import …``. | ||
| """ | ||
|
|
||
| from typing import Any, Optional | ||
|
|
||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( | ||
| InMemorySpanExporter, | ||
| ) | ||
| from opentelemetry.trace import StatusCode | ||
|
|
||
| from litellm.integrations.opentelemetry import ( | ||
| HTTP_RESPONSE_STATUS_CODE_ATTRIBUTE, | ||
| HTTP_ROUTE_ATTRIBUTE, | ||
| LITELLM_PROXY_REQUEST_SPAN_NAME, | ||
| URL_PATH_ATTRIBUTE, | ||
| ) | ||
|
|
||
|
|
||
| def get_server_span(exporter: InMemorySpanExporter): | ||
| """Return the (single) finished SERVER span, or None if it never ended.""" | ||
| for s in exporter.get_finished_spans(): | ||
| if s.name == LITELLM_PROXY_REQUEST_SPAN_NAME: | ||
| return s | ||
| return None | ||
|
|
||
|
|
||
| def assert_server_span_attrs( | ||
| exporter: InMemorySpanExporter, | ||
| *, | ||
| expected_status: int, | ||
| expected_url_path: str, | ||
| expected_http_route: Optional[str] = None, | ||
| where: str = "", | ||
| ) -> None: | ||
| """The four required attributes on the SERVER span must all be set.""" | ||
| span = get_server_span(exporter) | ||
| assert span is not None, ( | ||
| f"{where}: SERVER span never finished — exporter saw " | ||
| f"{[s.name for s in exporter.get_finished_spans()]}" | ||
| ) | ||
|
|
||
| actual_status = span.attributes.get(HTTP_RESPONSE_STATUS_CODE_ATTRIBUTE) | ||
| assert actual_status == expected_status, ( | ||
| f"{where}: {HTTP_RESPONSE_STATUS_CODE_ATTRIBUTE} = " | ||
| f"{actual_status!r}, expected {expected_status}" | ||
| ) | ||
| assert isinstance( | ||
| actual_status, int | ||
| ), f"{where}: status code must be int (semconv), got {type(actual_status)}" | ||
|
|
||
| actual_url = span.attributes.get(URL_PATH_ATTRIBUTE) | ||
| assert actual_url == expected_url_path, ( | ||
| f"{where}: {URL_PATH_ATTRIBUTE} = {actual_url!r}, " | ||
| f"expected {expected_url_path!r}" | ||
| ) | ||
|
|
||
| expected_route = expected_http_route or expected_url_path | ||
| actual_route = span.attributes.get(HTTP_ROUTE_ATTRIBUTE) | ||
| assert actual_route == expected_route, ( | ||
| f"{where}: {HTTP_ROUTE_ATTRIBUTE} = {actual_route!r}, " | ||
| f"expected {expected_route!r}" | ||
| ) | ||
|
|
||
| duration_ns = (span.end_time or 0) - (span.start_time or 0) | ||
| assert duration_ns > 0, f"{where}: duration must be > 0, got {duration_ns}ns" | ||
|
|
||
| expected_span_status = StatusCode.ERROR if expected_status >= 400 else StatusCode.OK | ||
| actual_span_status = span.status.status_code | ||
| assert actual_span_status == expected_span_status, ( | ||
| f"{where}: span.status = {actual_span_status!r}, " | ||
| f"expected {expected_span_status!r}" | ||
| ) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Synthetic exceptions covering the matrix triggers | ||
| # --------------------------------------------------------------------------- | ||
| class HttpStatusException(Exception): | ||
| """Generic exception with .status_code; mirrors what proxy code reads.""" | ||
|
|
||
| def __init__(self, status_code: int, message: str = "boom"): | ||
| super().__init__(message) | ||
| self.status_code = status_code | ||
| self.code = status_code | ||
|
|
||
|
|
||
| def make_httpx_status_error(status_code: int, body: str = "upstream error"): | ||
| """Real httpx.HTTPStatusError — what providers emit on 4xx/5xx upstream.""" | ||
| import httpx | ||
|
|
||
| request = httpx.Request("POST", "https://upstream.example/v1/x") | ||
| response = httpx.Response( | ||
| status_code=status_code, content=body.encode("utf-8"), request=request | ||
| ) | ||
| return httpx.HTTPStatusError( | ||
| f"HTTP {status_code}", request=request, response=response | ||
| ) | ||
|
|
||
|
|
||
| def make_fastapi_http_exception(status_code: int, detail: Any = "boom"): | ||
| from fastapi import HTTPException | ||
|
|
||
| return HTTPException(status_code=status_code, detail=detail) |
93 changes: 93 additions & 0 deletions
93
tests/test_litellm/integrations/open_telemetry/conftest.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """ | ||
| Shared fixtures for the LIT-3193 OTEL HTTP-attribute matrix. | ||
|
|
||
| The matrix needs every error response — across unified inference, passthrough, | ||
| and admin endpoints — to carry ``http.response.status_code``, ``url.path``, | ||
| ``http.route``, and a non-zero duration on the SERVER (root) span. These | ||
| fixtures hook a real ``OpenTelemetry`` callback into ``litellm.callbacks`` so | ||
| the tests drive the actual handler / wrapper code under test, not the OTEL | ||
| emitter in isolation. | ||
|
|
||
| See ``LIT-3193_test_matrix.md`` (same directory) for the cell list. | ||
| """ | ||
|
|
||
| import os | ||
| import sys | ||
| from datetime import datetime | ||
| from typing import Optional, Tuple | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import SimpleSpanProcessor | ||
| from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( | ||
| InMemorySpanExporter, | ||
| ) | ||
|
|
||
| sys.path.insert(0, os.path.abspath("../../..")) | ||
|
|
||
| import litellm | ||
| from litellm.integrations.opentelemetry import OpenTelemetry | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # OTEL + exporter | ||
| # --------------------------------------------------------------------------- | ||
| @pytest.fixture | ||
| def otel_with_exporter() -> Tuple[OpenTelemetry, InMemorySpanExporter]: | ||
| """Real OpenTelemetry callback with every span captured in-memory.""" | ||
| exporter = InMemorySpanExporter() | ||
| provider = TracerProvider() | ||
| provider.add_span_processor(SimpleSpanProcessor(exporter)) | ||
|
|
||
| otel = OpenTelemetry() | ||
| otel.tracer = provider.get_tracer("lit-3193-tests") | ||
| otel.message_logging = True | ||
| return otel, exporter | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def server_span_factory(otel_with_exporter): | ||
| """Factory mirroring user_api_key_auth: SERVER span + url.path + http.route.""" | ||
| otel, _exporter = otel_with_exporter | ||
|
|
||
| def _make(url_path: str, http_route: Optional[str] = None): | ||
| span = otel.create_litellm_proxy_request_started_span( | ||
| start_time=datetime.now(), headers={} | ||
| ) | ||
| otel.set_proxy_request_route_attributes( | ||
| span, url_path=url_path, http_route=http_route or url_path | ||
| ) | ||
| return span | ||
|
|
||
| return _make | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def user_api_key_dict_factory(): | ||
| """UserAPIKeyAuth-shaped mock; the only attr the failure hooks read is | ||
| parent_otel_span (plus team_id/team_alias for stamping).""" | ||
|
|
||
| def _make(parent_span): | ||
| d = MagicMock() | ||
| d.parent_otel_span = parent_span | ||
| d.team_id = "team-lit-3193" | ||
| d.team_alias = "lit-3193-team" | ||
| d.request_route = None | ||
| return d | ||
|
|
||
| return _make | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def register_otel_callback(otel_with_exporter, monkeypatch): | ||
| """Make ProxyLogging.post_call_failure_hook iterate our OTEL instance.""" | ||
| otel, _ = otel_with_exporter | ||
| saved = list(litellm.callbacks) | ||
| monkeypatch.setattr(litellm, "callbacks", [otel]) | ||
| yield otel | ||
| litellm.callbacks = saved | ||
|
|
||
|
|
||
| # Helpers (assertions, exception factories) live in ``_helpers.py`` — pytest | ||
| # auto-discovers fixtures here but forbids ``from .conftest import …``. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.