Skip to content

fix(proxy): keep extra chunk fields on the streaming fast path - #44867

Closed
Aasif-Simpplr wants to merge 2 commits into
BerriAI:mainfrom
Aasif-Simpplr:fix-streaming-fast-path-extras
Closed

Aasif-Simpplr wants to merge 2 commits into
BerriAI:mainfrom
Aasif-Simpplr:fix-streaming-fast-path-extras

Conversation

@Aasif-Simpplr

@Aasif-Simpplr Aasif-Simpplr commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Fields a callback sets on a streamed chunk get dropped
  • Only plain text chunks and the final stop chunk lose them
  • So clients see the field on some chunks and not others

How it solves it:

  • The fast chunk serializer now bails when the chunk carries extras
  • service_tier is still served on the fast path, as today
  • Two regression tests cover the bail and the end-to-end serialization

User Flow

Before: a team that tags every streamed chunk with routing metadata from an async_post_call_streaming_iterator_hook sees the tag vanish on some chunks

  1. They add a callback that sets an extra field (e.g. gateway_metadata) on each chunk it yields
  2. They send POST http://localhost:4000/v1/chat/completions with "stream": true
  3. Chunks that carry reasoning_content include the field, but the plain text chunk and the finish_reason: "stop" chunk come back without it

After: every chunk carries the field the callback set

  1. They add the same callback
  2. They send the same POST http://localhost:4000/v1/chat/completions with "stream": true
  3. Every chunk, including the plain text and the stop chunk, includes the field

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, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • 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

Real Baseten calls (baseten/zai-org/GLM-5.3-Flash) through a local proxy. The proxy loads a callback that tags every chunk it yields:

# proof_callbacks.py
from litellm.integrations.custom_logger import CustomLogger


class TagChunks(CustomLogger):
    async def async_post_call_streaming_iterator_hook(self, user_api_key_dict, response, request_data):
        async for chunk in response:
            chunk.gateway_metadata = {"served_by": "proof-callback"}
            yield chunk


proxy_handler_instance = TagChunks()
# config.yaml
model_list:
  - model_name: glm
    litellm_params:
      model: baseten/zai-org/GLM-5.3-Flash
      api_key: os.environ/BASETEN_API_KEY
litellm_settings:
  callbacks: proof_callbacks.proxy_handler_instance

Request used on both sides:

curl -sN localhost:4011/v1/chat/completions -H 'Content-Type: application/json' -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -d '{"model":"glm","stream":true,"max_tokens":200,"messages":[{"role":"user","content":"Say hello in one word"}]}'

Before (10444df)

  1. PYTHONPATH=<checkout>:. python -m litellm.proxy.proxy_cli --config config.yaml --port 4011
  2. Run the request above. 6 chunks come back and 4 carry gateway_metadata, the ones with reasoning_content. The plain text and stop chunks lose it:
data: {"object":"chat.completion.chunk","model":"glm","choices":[{"index":0,"delta":{"content":"Hello!"}}]}
data: {"object":"chat.completion.chunk","model":"glm","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]

After (7d33d5b)

  1. PYTHONPATH=<checkout>:. python -m litellm.proxy.proxy_cli --config config.yaml --port 4011
  2. Run the request above. 6 chunks come back and all 6 carry gateway_metadata, including the plain text and stop chunks:
data: {"model":"glm","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello! 👋"}}],"gateway_metadata":{"served_by":"proof-callback"}}
data: {"model":"glm","object":"chat.completion.chunk","choices":[{"finish_reason":"stop","index":0,"delta":{}}],"gateway_metadata":{"served_by":"proof-callback"}}
data: [DONE]

Chunks whose only extra is a None value (the citations=None the stream wrapper sets on every OpenAI-style chunk) still take the fast path. With litellm.completion(model="gpt-4o", mock_response="hello there world", stream=True) and the fast serializer called on each chunk, cccfe19 used the fast path on 1 of 7 chunks and 7d33d5b uses it on all 7, while a chunk with a real extra still falls back

Type

🐛 Bug Fix

Caveats (if any)

Low

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

_fast_serialize_simple_model_response_stream writes a fixed set of fields, so a field set on the chunk outside its schema (model_extra), for example by an async_post_call_streaming_iterator_hook, was silently dropped from plain text chunks. Fall back to the canonical serializer when the chunk carries an extra the fast payload does not write; service_tier is still served on the fast path.
@greptile-apps

greptile-apps Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes data loss in streaming response serialization.

The PR appears safe to merge.

Summary

The proxy’s streaming fast path now falls back to canonical serialization when a chunk has extra fields other than service_tier. Two unit tests check the bail condition and preservation of an added field.

Reviews (1) · Last reviewed commit: "fix(proxy): keep extra chunk fields on t..."

@codspeed

codspeed Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing Aasif-Simpplr:fix-streaming-fast-path-extras (7d33d5b) with main (7b439d9)

Open in CodSpeed

@codecov

codecov Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@VANDRANKI VANDRANKI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Community review. This does not clear the merge gate. I ran this against the PR head with a local checkout (python 3.13, litellm main plus this PR).

The bug is real. On main, setting an extra attribute on a ModelResponseStream (chunk.gw = {"a": 1}) makes _fast_serialize_simple_model_response_stream return bytes without gw, while model_dump_json(exclude_none=True, exclude_unset=True) keeps it. With the PR the fast path returns None for that chunk and _serialize_streaming_chunk emits "gw":{"a":1}. A service_tier extra still takes the fast path and is written. Choice-level and delta-level attribute assignments are dropped by both serializers, so those do not diverge.

Problem: the new guard bails on far more than hook-added fields. model_extra contains {'citations': None} on chunks coming out of CustomStreamWrapper for OpenAI-style streams, because streaming_handler.py (~line 985) always does setattr(model_response, "citations", getattr(original_chunk, "citations", None)). I ran litellm.completion(model="gpt-4o", mock_response="hello there world", stream=True) and called the fast serializer on each chunk:

  • main: every chunk returned bytes (fast path used)
  • PR head: every chunk except the last returned None (the last chunk has an empty model_extra)

So the fast path is effectively disabled for normal OpenAI-compatible streaming, which is the case it exists for. Output is still correct, since the slow path drops None values, but this is a throughput regression on the hot path. I did not benchmark it, I only counted which chunks take the fast path.

Suggested change, ignoring None-valued extras because exclude_none=True drops them anyway:

if model_extra and any(k != "service_tier" and v is not None for k, v in model_extra.items()):
    return None

I applied exactly that locally: the mock stream chunks take the fast path again, and the gw chunk still returns None.

The test test_fast_serialize_simple_model_response_stream_with_extra_field_returns_none passes in my repro, but there is no test with citations=None (or another None extra) asserting the fast path is still used. I think that test is what would catch this. I did not run the repo's pytest suite, because its proxy conftest needs prisma, which I did not install. I ran the equivalent calls in a script instead.

The stream wrapper sets citations=None on every OpenAI-style chunk, so the
previous guard sent almost every chunk to the slow path. exclude_none drops
None extras on the slow path too, so only non-None extras need it.
@Aasif-Simpplr

Copy link
Copy Markdown
Contributor Author

@VANDRANKI thanks, good catch. Confirmed and fixed in 7d33d5b with the change you suggested: the guard now ignores None-valued extras, since exclude_none drops them on the slow path too.

Your repro (litellm.completion(model="gpt-4o", mock_response="hello there world", stream=True), fast serializer called on each chunk):

chunks on the fast path chunk with gw={"a": 1}
PR head before (cccfe19) 1 / 7 bails (kept on slow path)
PR head now (7d33d5b) 7 / 7 bails (kept on slow path)

Added test_fast_serialize_simple_model_response_stream_with_none_extra_uses_fast_path, which sets citations = None and asserts the fast path is used and citations is not written. It fails on cccfe19 and passes now. make lint is green against upstream/main, and test_streaming_helpers.py is 99 passed.

I'll refresh the live Baseten proof in the description for the new head.

@bradrlaw

Copy link
Copy Markdown

Another real-world case for this fix, from llama.cpp.

llama.cpp's server adds a non-standard timings object (prompt and decode speed) to the final chunk, and Open WebUI reads it for its per-message speed stats. With LiteLLM 1.90.0 in front of the backend, whether timings reaches the client depends on whether the chunk also has system_fingerprint:

  • Backend sends system_fingerprint (llama.cpp always does): timings is kept, because the chunk falls back to the full serializer.
  • Backend does not (we hit this with the Strata engine): the chunk takes _fast_serialize_simple_model_response_stream and timings is dropped. The SDK path (litellm.completion(..., stream=True)) still returns it, and so does chunk.model_dump_json(exclude_none=True, exclude_unset=True), so the loss is in the proxy's fast-path serializer.

Adding "system_fingerprint": "x" to the backend's chunk makes timings appear again, which confirms the guard is the cause. Bailing out when the chunk carries extra fields, as this PR does, would fix it without needing the backend to send a fingerprint.

Environment: LiteLLM proxy 1.90.0, Open WebUI -> LiteLLM -> llama-swap -> llama.cpp b11819 / Strata.

@mateo-berri

Copy link
Copy Markdown
Contributor

Closing as superseded by #49398, which removed the streaming fast path so every chunk keeps its extra fields. Thanks for the fix

@mateo-berri mateo-berri closed this Nov 2, 2026
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