Skip to content

fix(headroom): resolve CCR retrieval on streaming /chat/completions - #35017

Merged
mateo-berri merged 11 commits into
litellm_internal_stagingfrom
litellm_lit_4913_headroom_streaming_ccr
Aug 29, 2026
Merged

mateo-berri merged 11 commits into
litellm_internal_stagingfrom
litellm_lit_4913_headroom_streaming_ccr

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Streaming CCR requests never ran the agentic loop
  • Clients got a raw headroom_retrieve tool call, empty answer

How it solves it:

  • Guardrail converts a CCR stream request to non-stream
  • Loop resolves retrieval, answer is fake-streamed back

User Flow

Before: a developer streaming chat completions through a proxy with Headroom compression on gets a tool call for a tool their app never declared, and no answer

  1. They send POST https://litellm-domain/v1/chat/completions with a long document, a follow-up question and "stream": true, declaring no tools
  2. The SSE frames carry only tool_calls deltas naming headroom_retrieve, every delta.content empty
  3. The stream ends with "finish_reason": "tool_calls" and data: [DONE], so the app shows the user nothing
  4. Their only workaround is to implement headroom_retrieve themselves, against an internal endpoint they were never told about

After: the same request streams back the answer, and the retrieve call never reaches the client

  1. They send the same POST https://litellm-domain/v1/chat/completions with "stream": true
  2. The SSE frames carry delta.content with the answer built from the compressed-away text
  3. The stream ends with "finish_reason": "stop" and data: [DONE]
  4. No frame mentions headroom_retrieve, so the app needs no knowledge of it

Relevant issues

Linear ticket

Resolves LIT-4913

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live run against a local proxy (2 uvicorn workers, random high port) hitting the real Anthropic API (anthropic/claude-sonnet-5, real spend). Only the Headroom compression vendor is stubbed locally, since Headroom is a self-hosted sidecar and no vendor credentials exist here: POST /v1/compress swaps a long user message for [compressed document; retrieve the full text with hash=...] and GET /v1/retrieve/{hash} returns the original text. The guardrail, the agentic loop and the streaming path are the real code

Shared setup, identical for both sides; only the checked-out commit differs

model_list:
  - model_name: claude
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
guardrails:
  - guardrail_name: headroom
    litellm_params:
      guardrail: headroom
      mode: pre_call
      default_on: true
      api_base: http://127.0.0.1:<stub port>
      api_key: stub-key
general_settings:
  master_key: sk-1234

payload.json is a 1906 char user message burying "the internal codename for the 2026 launch is BLUE HERON, and the launch window opens on March 14" in filler, an assistant ack, then a short user question asking for the codename and date. The client declares no tools; the guardrail injects headroom_retrieve itself. BLUE HERON and March 14 are inside the text compression replaced with a hash before the model ever saw it, so they can only appear in the answer if retrieval really ran server-side and fed a follow-up call

Three cases per side, same order: the streaming CCR chat completion above, a short non-CCR streaming request as a control (payload_short.json, "Say the word pineapple and nothing else."), and the same CCR conversation as a streaming /v1/messages request (payload_messages.json), the surface #36245 already fixed, as a regression control

Before (352789257d, merge base)

  1. Start the proxy on the merge base and send the streaming request
curl -s -N -X POST http://127.0.0.1:36083/v1/chat/completions \
  -H 'Authorization: Bearer sk-1234' -H 'content-type: application/json' \
  -d @payload.json > before.sse
  1. The internal retrieve call is streamed to the client and no answer arrives
data: {"id":"chatcmpl-b9529eb0-...","model":"claude","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"","tool_calls":[{"id":"toolu_014w2XVS662bhNJeqzTJDMax","function":{"arguments":"","name":"headroom_retrieve"},"type":"function","index":0,"caller":{"type":"direct"}}]}}]}
...
data: {"id":"chatcmpl-b9529eb0-...","choices":[{"index":0,"delta":{"content":"","tool_calls":[{"function":{"arguments":"h window\"}"},"type":"function","index":0}]}}]}
data: {"id":"chatcmpl-b9529eb0-...","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}
data: [DONE]
  1. Count what the client got
grep -c headroom_retrieve before.sse   # 1
grep -c tool_calls before.sse          # 16
grep -c 'BLUE HERON' before.sse        # 0
grep -o '"finish_reason":"[^"]*"' before.sse   # "finish_reason":"tool_calls"
  1. The two controls pass on the same boot: the short non-CCR stream answers pineapple with finish_reason: stop, and streaming /v1/messages resolves retrieval server-side (BLUE HERON in the reply, stop_reason: end_turn, no headroom_retrieve frame)

After (4d4cf40334, PR tip)

  1. Restart the proxy on the PR tip and send the byte-identical request
curl -s -N -X POST http://127.0.0.1:23551/v1/chat/completions \
  -H 'Authorization: Bearer sk-1234' -H 'content-type: application/json' \
  -d @payload.json > after.sse
  1. Retrieval is resolved server-side and the answer is streamed back
data: {"id":"chatcmpl-3bd4a3da-...","created":1788030498,"model":"claude","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"provider_specific_fields":{"citations":null,"thinking_blocks":null},"content":"The internal codename for the 2026 launch is **BLUE HERON**, and the launch window opens on **March 14**.","role":"assistant"}}]}
data: {"id":"chatcmpl-3bd4a3da-...","object":"chat.completion.chunk","created":1788030498,"model":"claude","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
  1. Count the same things
grep -c headroom_retrieve after.sse    # 0
grep -c tool_calls after.sse           # 0
grep -c 'BLUE HERON' after.sse         # 1
grep -o '"finish_reason":"[^"]*"' after.sse    # "finish_reason":"stop"
  1. Both controls still pass (pineapple / finish_reason: stop; /v1/messages answers with BLUE HERON and stop_reason: end_turn), and the stub vendor log confirms the retrieval happened inside the proxy for both CCR cases
127.0.0.1 - "POST /v1/compress HTTP/1.1" 200 -
127.0.0.1 - "GET /v1/retrieve/9835f94416d9f1356f9ab2f6?query=internal+codename+2026+launch+window HTTP/1.1" 200 -

An earlier screen recording of the same before/after comparison, captured at cd9c410ae2 (before) and fa5a4f06ed (after), is in the Slack thread; the run above supersedes it

The response is still data:-prefixed chat.completion.chunk frames ending in data: [DONE], so the fake-stream wrapper did not degrade the reply into a non-streaming body

Notes from this run:

  • Fake stream delivers the whole answer as one content chunk
  • Caused by this PR's design; frames still parse as SSE
  • Deployment-level litellm_params.guardrails config resolves streaming CCR too, verified live

Commit 2affd800ec since this run only adds a unit test for the deployment-level streaming case (no runtime code), so the proof above still holds at the tip

Type

🐛 Bug Fix

Changes

The Headroom guardrail doesn't drive retrieval itself; it injects headroom_retrieve in apply_guardrail and resolves the call through the chat-completions agentic loop hooks. That dispatch in litellm/main.py only fires for a ModelResponse, and a streaming call returns a CustomStreamWrapper, so streaming requests walked straight past it and handed the client the raw tool call

The guardrail now converts an eligible streaming request to non-streaming in async_pre_call_deployment_hook, the same trick the websearch and code-interpreter interceptions use. The override delegates to the base CustomGuardrail hook first, so deployment-level guardrail configs (litellm_params.guardrails: [headroom]) still get compressed, then converts on top of whatever the base returned:

base_result = await super().async_pre_call_deployment_hook(kwargs, call_type)
effective = base_result if base_result is not None else kwargs
if call_type not in (CallTypes.completion, CallTypes.acompletion):  return base_result
if not effective.get("stream"):                                     return base_result
if not has_headroom_retrieve_tool(effective.get("tools")):          return base_result
return {**effective, "stream": False, HEADROOM_CONVERTED_STREAM_KEY: True}

The conversion is narrow on purpose: only chat completions, only when the retrieve tool is actually on the request, so nothing changes for requests that never engaged CCR. /v1/messages already resolves the loop through AgenticAnthropicStreamingIterator, and streaming /v1/responses is deliberately left for a follow-up

chat_completion_agentic_loop.py then honors _headroom_interception_converted_stream alongside the code-interpreter flag when deciding to fake-stream the resolved response. That re-wrap also changed shape: it used to hand back a bare ModelResponseStream chunk, which is not an async iterable, so a caller that asked for stream=True could not iterate it. It now returns a CustomStreamWrapper over a MockResponseIterator, which is what every other fake-stream path in the codebase returns; this fixes the code-interpreter chat-completions path in the same stroke

The new flag is registered in agentic_loop_internal_litellm_params and in the proxy's untrusted-control-field list so it can't leak into a provider body or be forged by a client

The test gap the ticket called out is closed: test_streaming_chat_completion_resolves_ccr_retrieval_end_to_end drives a real litellm.acompletion(..., stream=True) through the registered guardrail, fakes the OpenAI HTTP boundary with respx (retrieve tool call first, final answer on the follow-up) plus the Headroom retrieve endpoint, and asserts the streamed text is the follow-up answer with no headroom_retrieve chunk. It fails on the pre-fix code. A parametrized test pins the deployment hook to CCR chat completions only, and a second one proves a deployment-level guardrail config still compresses through the base hook

Caveats (if any)

Medium

  • Streaming /v1/responses still leaks the retrieve call: scoped out here, tracked in LIT-6481 (the hook converts chat-completion call types only, and the responses handler honors only the code-interpreter and websearch converted-stream keys). Workaround: non-streaming /v1/responses or the /v1/chat/completions surface

Low

  • Live proof stubs the Headroom vendor, no vendor credentials here

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/38a43b70ce84466dbbc1ca792732653c
Open in Devin Desktop: https://app.devin.ai/desktop/session/38a43b70ce84466dbbc1ca792732653c?variant=devin
Requested by: @shivamrawat1


Note

Medium Risk
Changes request routing (stream→non-stream→fake stream) and agentic-loop behavior on a hot proxy path; scope is narrow (CCR chat completions with retrieve tool only) and includes regression tests.

Overview
Streaming Headroom CCR on /v1/chat/completions used to skip the agentic loop (streaming returns a CustomStreamWrapper, not a ModelResponse), so clients saw raw headroom_retrieve tool calls and no answer.

The Headroom guardrail now converts eligible streaming chat-completion requests to non-streaming in async_pre_call_deployment_hook when headroom_retrieve is on the request—mirroring websearch/code-interpreter interception. It calls the parent deployment hook first so deployment-level guardrail configs still compress, then sets stream: false and _headroom_interception_converted_stream.

chat_completion_agentic_loop treats that flag (and the existing code-interpreter converted-stream flag) when re-wrapping the resolved response for callers who asked for stream=true. Fake streaming now returns a CustomStreamWrapper over MockResponseIterator instead of a bare chunk object, so iteration works for Headroom and fixes the same pattern for code-interpreter chat completions.

The new internal key is registered so it cannot be forged by clients or forwarded to providers. Tests cover hook gating, deployment-level compression + conversion, and end-to-end litellm.acompletion(..., stream=True) with retrieval resolved server-side.

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

Streaming chat completions returned a CustomStreamWrapper, so the agentic loop dispatch in main.py (guarded on ModelResponse) never ran and the headroom_retrieve tool call was streamed straight to a client that never declared the tool. The guardrail now converts a CCR stream request to a non-streaming call in its deployment hook and the loop fake-streams the resolved answer back.
@shivamrawat1 shivamrawat1 self-assigned this Jul 29, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Jul 29, 2026 •

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 all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ shivamrawat1
✅ mateo-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR resolves Headroom retrieval for streaming chat completions.

  • Converts eligible Headroom chat-completion streams into non-streaming model calls before the agentic retrieval loop.
  • Wraps the final resolved response in an iterable synthetic stream.
  • Registers and sanitizes the internal Headroom stream-conversion flag.
  • Adds hook-gating, deployment-level compression, stream-wrapper, and end-to-end retrieval coverage.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/chat_completion_agentic_loop.py Extends converted-stream detection to Headroom and returns resolved responses through the standard iterable fake-stream wrapper.
litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py Converts eligible streaming chat-completion requests after Headroom has injected its retrieval tool.
litellm/proxy/litellm_pre_call_utils.py Prevents clients from supplying the server-controlled Headroom conversion field.
litellm/types/integrations/custom_logger.py Defines the Headroom interception key and ensures it is excluded from agentic follow-up provider parameters.
litellm/types/utils.py Registers the conversion key as an internal LiteLLM parameter so it is not forwarded to providers.
tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py Adds deployment-hook and end-to-end coverage for resolving Headroom retrieval before producing a synthetic stream.
tests/test_litellm/proxy/test_litellm_pre_call_utils.py Covers sanitization of the newly introduced internal control field.

Reviews (5): Last reviewed commit: "test(headroom): cover stream conversion ..." | Re-trigger Greptile

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.80952% with 11 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...litellm_core_utils/chat_completion_agentic_loop.py 59.25% 11 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit_4913_headroom_streaming_ccr (2affd80) with litellm_internal_staging (002d006)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (c453920) during the generation of this report, so 002d006 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@gustblima

gustblima commented Aug 11, 2026 •

Copy link
Copy Markdown

What are we waiting for to merge this one? It's affecting the main usability of headroom, without that, it's useless.

shivamrawat1 and others added 6 commits August 27, 2026 21:54
…streaming_ccr

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… snapshot

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…udget

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…n test

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…tream wrapper

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@shivamrawat1

Copy link
Copy Markdown
Contributor

@greptile

@shivamrawat1

Copy link
Copy Markdown
Contributor

@BugBot

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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 2affd80. Configure here.

@mateo-berri mateo-berri 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.

LGTM

@mateo-berri
mateo-berri merged commit e0ed0a4 into litellm_internal_staging Aug 29, 2026
80 of 81 checks passed
@mateo-berri
mateo-berri deleted the litellm_lit_4913_headroom_streaming_ccr branch August 29, 2026 20:01
devin-ai-integration Bot added a commit that referenced this pull request Sep 15, 2026
Deployment hooks such as Headroom downgrade stream=True to a non-streaming provider call and the agentic loop then hands back a CustomStreamWrapper (or MockResponsesAPIStreamingIterator for Responses). wrapper_async still saw kwargs["stream"] is False, so it took the non-streaming success path with a lazy stream object: no standard_logging_object was built, the proxy cost callback raised failed_tracking_spend, and the wrapper's own end-of-stream dispatch was deduped away. Treat a lazy stream result as streaming for logging regardless of the downgraded kwarg. Regression in v1.99.0 via #35017

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
devin-ai-integration Bot added a commit that referenced this pull request Sep 15, 2026
Deployment hooks such as Headroom downgrade stream=True to a non-streaming provider call and the agentic loop then hands back a CustomStreamWrapper (or MockResponsesAPIStreamingIterator for Responses). wrapper_async still saw kwargs["stream"] is False, so it took the non-streaming success path with a lazy stream object: no standard_logging_object was built, the proxy cost callback raised failed_tracking_spend, and the wrapper's own end-of-stream dispatch was deduped away. Treat a lazy stream result as streaming for logging regardless of the downgraded kwarg. Regression in v1.99.0 via #35017

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
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