Skip to content

fix(proxy): return upstream error bodies unchanged in passthrough - #32133

Merged
yuneng-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_passthrough_error_normalisation
Jul 4, 2026
Merged

yuneng-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_passthrough_error_normalisation

Conversation

@shivamrawat1

@shivamrawat1 shivamrawat1 commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Resolves LIT-4200
Issue
Generic config-based passthrough endpoints (pass_through_endpoints in config) do not return upstream error responses as-is. When the upstream returns a 403 with custom JSON like:

{"error": "Permission denied", "error_code": "xxx", "request_id": "xxx", "trace_id": "xxx"}
the LiteLLM proxy returns:

{
  "error": {
    "message": "{\"error\": \"Permission denied\", ...}",
    "type": "None",
    "param": "None",
    "code": "403"
  }
}

Success responses (2xx) pass through correctly. Only upstream 4xx/5xx get reshaped into the proxy's OpenAI-style ProxyException format, for both non-streaming and streaming passthrough

Cause
In pass_through_request() (litellm/proxy/pass_through_endpoints/pass_through_endpoints.py), upstream HTTP errors trigger response.raise_for_status(), which raises httpx.HTTPStatusError. That is caught and re-raised as HTTPException(status_code=..., detail=response.text). The outer except Exception block then converts any HTTPException into ProxyException, and the global openai_exception_handler in proxy_server.py serializes it as {"error": {...}} with the upstream JSON stringified into error.message

This happens in three places: explicit streaming (stream=True), detected streaming (SSE content-type), and non-streaming responses

Fix
Remove raise_for_status() and the HTTPException re-raise for upstream responses in all three passthrough paths. Upstream 4xx/5xx now flow through the same return path as 2xx: Response(content=..., status_code=..., headers=...) for non-streaming and StreamingResponse(..., status_code=...) for streaming, preserving upstream body and status unchanged

Post-call guardrails and managed-id output rewriting are scoped to status_code < 400 so they do not run on upstream error bodies. Internal proxy failures (auth, config, guardrails, network errors before any upstream response) still raise ProxyException as before

Regression tests added in tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py for non-streaming 403, streaming 403, unchanged 200 success, and internal failure still using ProxyException

Follow-up fix
Review feedback flagged two gaps in the initial fix: post_call_failure_hook was skipped entirely for upstream errors, so spend-tracking and alerting callbacks never fired for them, and response_body in the log payload was hardcoded to None for every upstream error, so logging integrations never saw what the upstream actually returned

Added _log_passthrough_upstream_failure, which calls post_call_failure_hook for upstream 4xx/5xx responses without altering the client-facing response, and response_body is now parsed unconditionally so the success-handler log payload reflects upstream error bodies too; guardrails and managed-id rewriting remain scoped to status_code < 400

Added regression tests asserting post_call_failure_hook fires (and does not fire) for upstream error and success responses, and that the logged response_body matches the upstream error JSON

Second follow-up fix
Further review caught two more issues from the first follow-up: the success handler (both the non-streaming path and chunk_processor's end-of-stream logging) has no status-code awareness, so it kept firing for upstream 4xx/5xx too, meaning the same request got logged as both a failure and a success and corrupted SpendLogs/cost tracking; separately, post_call_failure_hook was passed the raw httpx.HTTPStatusError, and ProxyLogging's alerting only excludes HTTPException/ProxyException from its "High" severity llm_exceptions alert, so a routine upstream 403 would page ops the same as a real LLM API outage

Gated the success handler in both the non-streaming path and chunk_processor to status_code < 400, and now report upstream failures to post_call_failure_hook as an HTTPException (matching how auth/rate-limit errors are already excluded from alerting) instead of the raw httpx error. response_body is now threaded into the failure-hook payload for the non-streaming path instead of the success handler's, since the success handler no longer runs for errors

Added regression tests proving the success handler is not called for upstream errors (streaming and non-streaming) and is still called for real successes, that a failing post_call_failure_hook callback can't break the passthrough response, and a chunk_processor-level test proving end-of-stream success logging is skipped for a 4xx/5xx

Proof:
Direct call to passthrough:
Screenshot 2026-07-04 at 11 22 04 AM

Passthrough via LiteLLM
Before:
Screenshot 2026-07-04 at 11 24 00 AM

After:
Screenshot 2026-07-04 at 11 21 07 AM


Note

Medium Risk
Changes proxy passthrough response semantics and spend/alert hooks on a widely used path; mitigated by extensive regression tests and unchanged behavior for 2xx and internal proxy failures.

Overview
Generic config passthrough no longer turns upstream 4xx/5xx into LiteLLM ProxyException / OpenAI-style {"error": {...}} bodies. raise_for_status() and client-facing HTTPException re-raises were removed so streaming and non-streaming responses keep the upstream status, headers, and body.

Upstream failures still run post_call_failure_hook via _log_passthrough_upstream_failure, with a shared _build_passthrough_failure_request_payload shape. Failures are reported as HTTPException (not raw httpx.HTTPStatusError) so routine upstream errors don’t trigger high-severity ops alerts. Callback errors are swallowed so the passthrough response is never broken.

Post-call guardrails, managed-id output rewrite, and success spend logging (non-streaming handler and chunk_processor end-of-stream) run only when status_code < 400, avoiding double failure+success SpendLogs entries. Non-streaming failure hooks include parsed response_body from the upstream error JSON.

Regression tests cover unchanged 403 bodies (stream/non-stream), success path, internal ProxyException, failure-hook resilience, and streaming success logging skipped on 4xx/5xx.

Reviewed by Cursor Bugbot for commit cbfba17. Bugbot is set up for automated code reviews on this repo. Configure here.

Generic pass-through endpoints called raise_for_status() on upstream 4xx/5xx
responses and re-raised as HTTPException, which the outer handler reshaped
into a ProxyException with the upstream body stringified into error.message.
Success responses were already forwarded as-is, so failures were the only
case where passthrough wasn't actually transparent. Removes the
raise_for_status() calls for both streaming and non-streaming passthrough so
upstream status, body, and headers reach the client unchanged, while keeping
guardrails/managed-id rewriting scoped to successful responses and leaving
internal proxy failures (auth, config, network errors before any upstream
response) on the existing ProxyException path.

Co-authored-by: Cursor <cursoragent@cursor.com>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


Shivam Rawat seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes generic config-based passthrough endpoints incorrectly reshaping upstream 4xx/5xx responses into LiteLLM's ProxyException format instead of forwarding them byte-for-byte to the client. It also ensures post_call_failure_hook (spend tracking, alerting) still fires for upstream errors and that no request is double-logged as both a failure and a success.

  • Core fix: Removes raise_for_status() in all three passthrough paths (explicit streaming, detected streaming, non-streaming) and replaces each with _log_passthrough_upstream_failure(), which fires post_call_failure_hook via a synthetic HTTPException (to avoid false-positive high-severity alerts) without altering the client-facing response.
  • Double-logging prevention: Gates the success handler in both the non-streaming path and chunk_processor's finally block on status_code < 400; also gates guardrails and managed-id rewriting on status_code < 400 so only genuine successes go through those paths.
  • Test coverage: Five new regression tests covering non-streaming 403, streaming 403, swallowed failure-hook exceptions, unchanged 2xx, and internal-failure ProxyException; four existing streaming tests updated to set status_code = 200 so the new gate doesn't suppress their success-logging assertions.

Confidence Score: 5/5

Safe to merge — all three passthrough code paths are updated consistently, the failure/success accounting is correctly gated, and the new tests verify both the error and success paths end-to-end.

The fix is well-scoped: each of the three passthrough paths receives the same treatment, post_call_failure_hook still fires for upstream errors via a synthetic HTTPException, and success logging is gated at every exit point (pass_through_request non-streaming, pass_through_request detected-streaming, and chunk_processor finally). Existing tests were updated with minimal, correct changes (adding status_code = 200 to mocks) and all new tests use mocks with no real network calls.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/pass_through_endpoints/pass_through_endpoints.py Core fix: removes raise_for_status() in all three passthrough paths and replaces it with _log_passthrough_upstream_failure(), which fires post_call_failure_hook without altering the client-facing response. Guardrails, managed-id rewriting, and success logging are gated on status_code < 400 to prevent double-logging.
litellm/proxy/pass_through_endpoints/streaming_handler.py Adds response.status_code < 400 guard in chunk_processor's finally block so end-of-stream success logging is skipped for upstream error responses that were already logged as failures by the caller.
tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py Adds five new regression tests covering: non-streaming 403 passthrough, streaming 403 passthrough, swallowed failure-hook exceptions, unchanged 2xx behavior, and internal-failure ProxyException path. All use mocks with no real network calls.
tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py Adds chunk_processor test asserting that success logging is not scheduled for a 4xx upstream response, matching the new status_code gate added in streaming_handler.py.
tests/pass_through_unit_tests/test_unit_test_streaming.py Adds response.status_code = 200 to the mock so the new status_code < 400 gate in chunk_processor's finally block doesn't suppress the success logging path that these tests already exercise.
tests/pass_through_unit_tests/test_vertex_ai_anthropic_streaming_cost_injection.py Sets response.status_code = 200 on four existing AsyncMock fixtures so the new gate in chunk_processor still lets those success-path tests exercise logging correctly.

Reviews (3): Last reviewed commit: "test(proxy): set status_code on chunk_pr..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.87500% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...y/pass_through_endpoints/pass_through_endpoints.py 96.77% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…h upstream errors

Follow-up to 8c98780: returning upstream 4xx/5xx bodies unchanged also
skipped post_call_failure_hook entirely, so spend-tracking and alerting
callbacks never fired for upstream errors, and response_body was hardcoded
to None in the log payload so the actual upstream error body never reached
logging integrations. Adds a small helper that calls post_call_failure_hook
for upstream errors without altering the client-facing response, and parses
response_body unconditionally for logging while still scoping guardrails
and managed-id rewriting to status_code < 400.

Co-authored-by: Cursor <cursoragent@cursor.com>
@shivamrawat1

Copy link
Copy Markdown
Contributor Author

@greptile review again with new commit

@yucheng-berri

Copy link
Copy Markdown
Contributor

bugbot run

@yucheng-berri

yucheng-berri commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

pass_through_endpoints.py:1330 — upstream errors are logged as both failure and success. [LOG-1]

This PR correctly adds _log_passthrough_upstream_failure(...) for 4xx/5xx responses, firing post_call_failure_hook. But the existing unconditional success enqueue still runs afterward:

GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue(pass_through_async_success_handler(...))

success_handler.py has no status_code awareness, so every upstream 4xx/5xx is now recorded as both a failure and a success. Before this PR, raise_for_status() threw before the success path, so double-logging could not happen.

This corrupts SpendLogs/cost analytics for the exact error cases being fixed. The new 403 test even asserts mock_success_handler.assert_called_once(), encoding the bug as expected behavior.

@yucheng-berri

yucheng-berri commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

_log_passthrough_upstream_failure has untested exception-swallowing behavior. [TEST-1]

The helper catches and suppresses exceptions from the failure hook, but that fallback path appears uncovered — likely the three Codecov-flagged lines.

There is also a streaming-specific risk: on the explicit stream=True path, a failure-hook callback could read/consume the upstream response body before chunk_processor streams it to the client. No test proves that streamed output remains byte-identical after the hook runs.

This matches Greptile’s latent edge-case concern.

is it legit?

…tream errors

Two bugs from the upstream-error fixes: the success handler has no
status-code awareness, so removing raise_for_status() left it firing for
every upstream 4xx/5xx too, meaning the new failure hook and the existing
success handler both logged the same request (corrupting SpendLogs/cost
tracking). Separately, the failure hook was passed the raw
httpx.HTTPStatusError, which ProxyLogging's alerting only excludes
HTTPException/ProxyException from, so a normal upstream 403 would trigger a
"High" severity llm_exceptions alert. Gates the success handler (both
non-streaming and end-of-stream) to status_code < 400, and reports upstream
failures to post_call_failure_hook as an HTTPException instead of the raw
httpx error, matching how auth/rate-limit errors are already excluded from
alerting.

Co-authored-by: Cursor <cursoragent@cursor.com>
@shivamrawat1

Copy link
Copy Markdown
Contributor Author

[LOG-1] Yes, legit. Fixed in 44a0f57: gated the non-streaming ## LOG SUCCESS enqueue and chunk_processor's end-of-stream success logging to response.status_code < 400, so a 4xx/5xx now only logs via _log_passthrough_upstream_failure, never both. Added regression tests asserting the success handler is not called for upstream errors (streaming and non-streaming) and is still called exactly once for real successes, plus a chunk_processor-level unit test with a 403 response.

@shivamrawat1

Copy link
Copy Markdown
Contributor Author

[TEST-1] Yes on the coverage gap, not on the streaming-consumption risk as written.

Added test_pass_through_request_upstream_error_failure_hook_exception_is_swallowed in 44a0f57, which makes post_call_failure_hook raise and asserts the client still gets the unchanged 403 body, covering the exception-swallow branch.

On the streaming concern: _log_passthrough_upstream_failure never hands the raw httpx.Response to any callback. It only passes a synthetic HTTPException (status_code/detail only) and a plain request_data dict, so a failure-hook callback has no path to the response object to read its body. response.raise_for_status() itself only inspects status_code/headers (checked against the httpx source), so it never touches the body either. The existing streaming regression test (test_pass_through_request_streaming_upstream_error_returned_unchanged) already asserts the streamed bytes match the upstream content exactly after the hook runs, so byte-identical output is covered.

chunk_processor now reads response.status_code to gate end-of-stream
success logging. These mocks used AsyncMock(spec=httpx.Response), which
spec's against the class and doesn't expose status_code since it's an
instance attribute, not a class attribute, so accessing it raised
AttributeError. Sets status_code=200 explicitly on the success-path mocks.

Co-authored-by: Cursor <cursoragent@cursor.com>
@shivamrawat1

Copy link
Copy Markdown
Contributor Author

@greptile review again

@shivamrawat1

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit cbfba17. Configure here.

@yuneng-berri
yuneng-berri merged commit a3a3201 into litellm_internal_staging Jul 4, 2026
78 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_passthrough_error_normalisation branch July 4, 2026 20:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants