Skip to content

fix(proxy): preserve routed model for streamed spend logging - #42176

Closed
senthurapandi2000 wants to merge 4 commits into
BerriAI:mainfrom
senthurapandi2000:fix-streaming-alias-cost-42161
Closed

senthurapandi2000 wants to merge 4 commits into
BerriAI:mainfrom
senthurapandi2000:fix-streaming-alias-cost-42161

Conversation

@senthurapandi2000

Copy link
Copy Markdown

Summary

Fixes #42161.

Streaming requests using a client-facing model alias could be logged with the alias instead of the routed deployment model. Since the alias may not have pricing information, spend calculation could incorrectly resolve to 0 even though usage was present.

This change restores the wrapper's routed model before success logging when the assembled streaming response still contains the client-facing alias.

It also preserves the model returned by stream_chunk_builder when the builder legitimately recovers a different routed/fallback model from a later stream chunk.

Changes

  • Preserve the routed model for end-of-stream success logging.
  • Avoid overwriting a routed/fallback model recovered from later chunks.
  • Add regression coverage for:
    • alias model being replaced with the routed model for logging
    • later-chunk routed model being preserved

Testing

python -m pytest -q \
  tests/test_litellm/litellm_core_utils/test_streaming_handler.py::test_finalize_completed_stream_uses_routed_model_for_logging \
  tests/test_litellm/litellm_core_utils/test_streaming_handler.py::test_finalize_completed_stream_preserves_model_recovered_from_later_chunk

@senthurapandi2000
senthurapandi2000 requested a review from a team September 20, 2026 23:41
@CLAassistant

CLAassistant commented Sep 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge, with the streamed logging behavior covered for both alias restoration and later deployment recovery

Summary

This PR corrects model identity used by asynchronous end-of-stream logging so streamed proxy requests using aliases retain the routed deployment model for cost calculation. It also preserves a different deployment model recovered from later chunks.

  • Restores the wrapper’s routed model when stream assembly retains the client-facing alias
  • Preserves a model recovered from later stream chunks, including Azure model-router selections
  • Adds focused asynchronous regression coverage for both outcomes

Reviews (1) · Last reviewed commit: "fix(proxy): preserve routed model for st..."

@codspeed

codspeed Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing senthurapandi2000:fix-streaming-alias-cost-42161 (261ad00) with main (1cac8bd)

Open in CodSpeed

@codecov

codecov Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@eduardopessin

Copy link
Copy Markdown
Contributor

Thanks for turning this around fast. CI is green and the shape is right: put the routed model back before the success dispatch. Three things before this lands.

1. body["model"] is not the name the client sent.

You read the client name from litellm_params -> proxy_server_request -> body -> model. That snapshot is refreshed in common_request_processing.py:2145, after add_litellm_data_to_request has returned, and the key and team alias rewrites live inside that call at litellm_pre_call_utils.py:2484 and :2490. So whenever a key alias or team alias is configured, body["model"] holds the alias target, not what the caller typed.

The proxy stamps chunks using _get_client_requested_model_for_streaming (proxy_server.py:8830), which prefers request_data["_litellm_client_requested_model"], the name captured before that rewrite. So in the alias case your client_requested_model and the stamped name are two different strings, assembled_model != client_requested_model is true, builder_recovered_routed_model is true, and the restore is skipped. Spend goes back to zero.

The repro in the issue uses an alias as model_name in model_list, which never passes through that rewrite, so your test passes while that neighbouring variant still fails. _litellm_client_requested_model is the field to read, falling back to request_data["model"], in the same order as _assembled_model_is_the_name_the_client_asked_for.

2. Please do not fork the predicate.

common_request_processing.py:329 and :351 already implement this decision, with a docstring explaining why its shape is what it is: a stored usage chunk is a copy taken before the proxy restamps, so an aliased stream reaches the builder as a first chunk that disagrees with the rest. Your version asks a different question. Upstream compares the assembled model against chunks[0]["model"]; yours tests membership in chunks[1:]. Two implementations of one rule in two files is the next bug. Lift those two helpers somewhere both call sites can import.

3. The sync path has the same hole.

__next__ at streaming_handler.py:1841 assembles complete_streaming_response and hands _log_copy straight to executor.submit(self.logging_obj.success_handler, ...) at :1886, with no restore at all. Same file, same bug, a couple hundred lines up. A fix that covers only __anext__ leaves every sync SDK caller costed at zero.

One behaviour note for the description: your mutation runs before the deep copy at :2128, so the cached response now carries the routed model rather than the alias. Probably what you want, but it is a change in what gets stored and should be stated.

@eduardopessin

Copy link
Copy Markdown
Contributor

Correcting my point 2 above, and adding a measurement that changes what it asks for.

I told you to lift _assembled_model_came_from_a_later_chunk and compare against chunks[0]["model"]. On its own that is not sufficient advice, and on one real stream shape the comparison is actively misleading.

Measured, litellm 1.101.0, driving a real CustomStreamWrapper. Anthropic emits usage twice: on message_start, which is the first chunk (anthropic/chat/handler.py:1064), and on message_delta, which carries finish_reason (:1164). The wrapper stores usage-bearing chunks as pre-restamp copies (streaming_handler.py:2017) and ordinary chunks by reference, so after the proxy restamps the outgoing objects the stored list reads:

['anthropic/claude-opus-4-20250514', '<alias>', '<alias>', 'anthropic/claude-opus-4-20250514']

chunks[0] keeps the wire name. The content chunks in the middle carry the alias. _get_model_from_chunks returns the first model differing from chunks[0], so the assembled model is the alias, and assembled != chunks[0] is true — came_from_later fires on a stream where nothing was recovered from a later chunk at all.

So that predicate does not distinguish the two cases by itself on this shape. What saves the upstream version is only its second half, _assembled_model_is_the_name_the_client_asked_for. Which means the correctness of the whole thing rests on reading the client name from the right place — my point 1 — rather than on the chunks[0] comparison I pointed you at. The two are not independent; point 2 is load-bearing only if point 1 is fixed first.

End to end on the same harness, restamp applied the way _restamp_streaming_chunk_model applies it:

logged model cost
restamp off anthropic/claude-opus-4-20250514 0.609735
restamp on <alias> BadRequestError

Worth noting the failure mode: when the stamped name has no entry in the price map at all, this is not the silent 0.0 from the issue — completion_cost raises. Same root cause, louder symptom, and a test asserting cost == 0 would not catch it.

One case to put in the tests, since it is the one the current guard gets wrong. With a key alias configured (key.aliases: {claude: some-deployment}), the rewrite at litellm_pre_call_utils.py:2490 runs before the snapshot refresh, so body["model"] is the deployment name while the proxy stamps claude. Replaying your guard against the chunk layout above:

layout your guard reading _litellm_client_requested_model
no alias restore applied, priced applied, priced
key alias skipped, cost 0 applied, priced

Both rows pass through the same code path; only the source of the client name separates them.

@senthurapandi2000

Copy link
Copy Markdown
Author

Thanks for the detailed review and for the additional measurement. I see the issue with reading body["model"] after alias rewriting, and why the client-name check is load-bearing for the chunk predicate. I’ll update this to use _litellm_client_requested_model with the existing fallback semantics, reuse the shared predicate instead of duplicating it, cover the sync next path as well, and add a key-alias regression case matching the real chunk shape. I’ll also call out the cached-response model change in the PR description.

e,
)
if isinstance(e, HTTPException) and hasattr(captured_logging_obj, "model_call_details"):
if isinstance(e, HTTPException) and hasattr(captured_logging_obj, "`model_call_details`"):

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.

Low: Guardrail block marker is never recorded

The backticks make this check false for production logging objects, so a client whose streamed response triggers an HTTPException in a post-call guardrail can have the event logged without the guardrail_blocked audit marker. A MagicMock-based test may miss this because mocks synthesize arbitrary attributes.

Suggested change
if isinstance(e, HTTPException) and hasattr(captured_logging_obj, "`model_call_details`"):
if isinstance(e, HTTPException) and hasattr(captured_logging_obj, "model_call_details"):

@veria-ai

veria-ai Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

PR overview

This PR updates proxy request processing so streamed spend logs preserve the model selected by routing.

One low-severity issue remains: streamed responses blocked by a post-call guardrail may be logged without the expected guardrail-blocked audit marker. This affects audit accuracy under a specific exception path rather than enforcement of the guardrail itself.

Open issues (1)

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

@eduardopessin

Copy link
Copy Markdown
Contributor

Closing the loop here: the alias/streaming diagnosis in #42161 turned out to be wrong, as the issue thread shows. The real cause is provider_response_model carrying a dated slug the price map lacks, and #42467 addresses that in cost_calculator.py. So this PR is fixing a path that is not what bills the turn at zero. Thanks again for jumping on it so quickly, and sorry for the misdirection.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Thanks for digging into this. The same fix landed in #44341 (v1.106.0), and streamed alias requests price correctly on main now, so closing this as superseded

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.

[Bug]: turn billed at 0 when provider_response_model is a slug missing from the price map (e.g. dated Anthropic builds)

3 participants