Repository navigation
fix(proxy): return upstream error bodies unchanged in passthrough - #32133
yuneng-berri merged 4 commits into
Conversation
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>
|
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 SummaryThis PR fixes generic config-based passthrough endpoints incorrectly reshaping upstream 4xx/5xx responses into LiteLLM's
Confidence Score: 5/5Safe 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.
|
| 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 Report❌ Patch coverage is
📢 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>
|
@greptile review again with new commit |
|
bugbot run |
|
This PR correctly adds
This corrupts SpendLogs/cost analytics for the exact error cases being fixed. The new 403 test even asserts |
|
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 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>
|
[LOG-1] Yes, legit. Fixed in 44a0f57: gated the non-streaming |
|
[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>
|
@greptile review again |
|
bugbot run |
There was a problem hiding this comment.
✅ 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.
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:
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:
Passthrough via LiteLLM

Before:
After:

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-facingHTTPExceptionre-raises were removed so streaming and non-streaming responses keep the upstream status, headers, and body.Upstream failures still run
post_call_failure_hookvia_log_passthrough_upstream_failure, with a shared_build_passthrough_failure_request_payloadshape. Failures are reported asHTTPException(not rawhttpx.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_processorend-of-stream) run only whenstatus_code < 400, avoiding double failure+success SpendLogs entries. Non-streaming failure hooks include parsedresponse_bodyfrom 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.