Skip to content

fix(proxy): cap upstream error-response bodies at 64 KB - #34392

Open
unfitcoder101 wants to merge 2 commits into
BerriAI:mainfrom
unfitcoder101:fix/cap-upstream-error-body-size-clean
Open

unfitcoder101 wants to merge 2 commits into
BerriAI:mainfrom
unfitcoder101:fix/cap-upstream-error-body-size-clean

Conversation

@unfitcoder101

Copy link
Copy Markdown

Replaces #34040 — that branch had accidentally accumulated commits from an unrelated Cloudflare PR due to a branch mixup on my end, which was tripping the strict-rule lint budget on an unrelated file. This is a clean rebuild off current litellm_internal_staging with just the actual fix.

Problem

Upstream error-response bodies were read without a size cap, risking event-loop stalls on huge responses.

Fix

Added a 64 KB cap (_MAX_ERROR_BODY_BYTES) in _safe_get_response_text and _safe_aread_response, truncating with a clear marker when exceeded.

Bonus fix

While rebasing onto current upstream, hit a real merge conflict in router_strategy/budget_limiter.py — turns out the fix from #34044 (duration-only provider budget config incorrectly using continue to skip the whole deployment instead of just the provider check) was never actually merged into litellm_internal_staging. Kept the correct version, so this PR also fixes that still-open bug as a side effect.

Tests

3 new tests covering exact boundary, large-body truncation, and small-body passthrough — all passing.

A ~114 MB HTTP 400 from an upstream backend caused the proxy to read
the full body, run regex masking over 100+ MB on the event loop, and
propagate it through the fallback chain — stalling asyncio, exhausting
RSS, and timing out health checks.

Fix: introduce _MAX_ERROR_BODY_BYTES = 64 KB and truncate at three
ingestion sites before masking or propagation:
- _safe_get_response_text (sync text read)
- _safe_aread_response (async body read)
- _safe_read_response (sync body read, both timeout and direct paths)
- _handle_error in llm_http_handler.py (now uses _safe_get_response_text)

Truncated bodies include a marker: "... [truncated, original size
exceeded 65536 bytes]" so operators know truncation occurred.

Fixes BerriAI#34031
Cosmetic-only fix for the ruff format CI check (line wrapping /
blank-line conventions). No logic changes.
@codecov

codecov Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/custom_httpx/http_handler.py 84.21% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing unfitcoder101:fix/cap-upstream-error-body-size-clean (986725b) with litellm_internal_staging (3bba363)

Open in CodSpeed

@unfitcoder101
unfitcoder101 marked this pull request as ready for review July 23, 2026 16:26
@greptile-apps

greptile-apps Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR changes shared upstream error handling and provider-budget filtering

  • Adds a 64 KB truncation marker to sync, async, and decoded error-response helpers
  • Routes generic LLM HTTP errors through the shared response-text helper
  • Preserves deployment and tag budget checks when a provider config has duration but no maximum budget
  • Adds boundary and passthrough tests for decoded response text

Confidence Score: 2/5

This PR should not merge until error bodies are bounded while reading, because the current implementation still fully consumes oversized upstream responses

The shared helpers truncate only after response.text, response.read(), or response.aread() has materialized the complete body, leaving the memory and request-stall failure that the change is intended to prevent; the added tests exercise only already-materialized text and do not guard the transport-read boundary

litellm/llms/custom_httpx/http_handler.py, tests/test_litellm/test_error_body_cap.py

Important Files Changed

Filename Overview
litellm/llms/custom_httpx/http_handler.py Adds post-read truncation, but all three helpers still fully consume the upstream body before enforcing the limit
litellm/llms/custom_httpx/llm_http_handler.py Reuses the shared safe-text helper for generic provider error mapping
litellm/router_strategy/budget_limiter.py Avoids skipping deployment and tag checks when provider configuration contains only a duration
tests/test_litellm/test_error_body_cap.py Covers decoded-text output boundaries but does not verify bounded transport reads for sync or async streaming responses

Reviews (1): Last reviewed commit: "style: apply ruff format to error-body-c..." | Re-trigger Greptile

Comment on lines +389 to +392
text = response.text
if len(text.encode("utf-8", errors="replace")) > _MAX_ERROR_BODY_BYTES:
text = text.encode("utf-8", errors="replace")[:_MAX_ERROR_BODY_BYTES].decode("utf-8", errors="replace")
text += f" ... [truncated, original size exceeded {_MAX_ERROR_BODY_BYTES} bytes]"

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.

P1 Body cap occurs after buffering

When an upstream returns a large error body, response.text, response.read(), and response.aread() materialize the complete response before it is sliced, so oversized responses still consume unbounded memory and stall request handling; timed-out synchronous reads also continue occupying executor workers.

Knowledge Base Used: LLM Provider Adapters

Comment on lines +18 to +23
mock_response = MagicMock()
mock_response.text = "x" * (200 * 1024) # 200 KB
result = _safe_get_response_text(mock_response)
assert len(result.encode("utf-8")) <= _MAX_ERROR_BODY_BYTES + 200 # allow for truncation message
assert "truncated" in result
print(f"✓ Large body truncated to ~{_MAX_ERROR_BODY_BYTES} bytes")

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.

P2 Test misses bounded reads

This test supplies an already-materialized .text value and only checks the truncated output, so it passes even when the helper reads the entire upstream response before applying the cap. Add transport-level sync and async streaming cases that fail when more than the configured limit is consumed.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

if timeout is not None:
return await asyncio.wait_for(response.aread(), timeout=timeout)
return await response.aread()
body = await asyncio.wait_for(response.aread(), timeout=timeout)

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.

Medium: Error-body limit is enforced too late

response.aread() buffers and decodes the entire body before the size check; the sync helper does the same with read(), while non-streaming requests are already buffered by send(..., stream=False). An attacker-controlled upstream can therefore still exhaust proxy memory or stall the event loop with a large or highly compressed error response. Read errors in streaming mode, stop once the decoded limit is reached, close the response, and ensure MaskedHTTPStatusError does not retain the original full response.content.

@veria-ai

veria-ai Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

PR overview

This pull request updates the proxy’s HTTP handling to cap upstream error-response bodies at 64 KB in both asynchronous and synchronous request paths.

The intended limit is currently applied only after the complete response body has been buffered and decoded, so it does not prevent memory exhaustion or event-loop stalls from a large or highly compressed attacker-controlled upstream response. The response must instead be read incrementally, stopped at the decoded limit, and closed without retaining the original full content. This issue remains open.

Open issues (1)

Fixed/addressed: 0 · PR risk: 6/10

@unfitcoder101

Copy link
Copy Markdown
Author

@krrish-berri Rebuilt this clean off current staging after the branch mixup on #34040 — should be ready for another pass whenever you get a chance.

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:33
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:33
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 15:33

This branch has not been deployed

No deployments
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.

2 participants