Repository navigation
fix(proxy): cap upstream error-response bodies at 64 KB - #34392
unfitcoder101 wants to merge 2 commits into
Conversation
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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR changes shared upstream error handling and provider-budget filtering
Confidence Score: 2/5This 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
|
| 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
| 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]" |
There was a problem hiding this comment.
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
| 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") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
PR overviewThis 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 |
|
@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. |
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_textand_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 usingcontinueto skip the whole deployment instead of just the provider check) was never actually merged intolitellm_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.