Repository navigation
fix(responses): preserve native stream spend on guardrail rejection (lts/1.108.x backport of #50286) - #51303
fix(responses): preserve native stream spend on guardrail rejection (lts/1.108.x backport of #50286)#51303mateo-berri wants to merge 6 commits into
Conversation
…50286) Adapted for lts/1.108.x using its existing response_cost_calculator Carry the minimal #47445 prerequisite pieces, BilledRoundsSpend, BilledRoundsDispatch, record_billed_rounds_for_failure and the proxy deferred dispatch and discard cases. Exclude MCP multi-round billing and UncachedPrice machinery (cherry picked from commit faf4ce3) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
PR overviewThis backport preserves native One issue remains open: rejected streams record provider costs but do not update per-model budget counters. An authenticated caller can repeatedly trigger these rejections to exceed Open issues (1)
Fixed/addressed: 0 · PR risk: 6/10 Reviews |
| case ModelResponse(): | ||
| logging_obj.record_assembled_response_for_failure(assembled) | ||
| case BilledRoundsDispatch(): | ||
| assembled.dispatch.close() |
There was a problem hiding this comment.
High: Rejected streams no longer charge per-model budgets
PROXY_VirtualKeyModelMaxBudgetLimiter charges only in async_log_success_event and inherits a no-op failure callback, so closing this coroutine leaves its counters unchanged even though the failure row records provider cost. An authenticated caller can repeatedly trigger end-of-stream guardrail rejections on native /v1/responses to exceed model_max_budget while other budgets have headroom; apply the recovered spend to the budget counters on the failure path without emitting another success log.
There was a problem hiding this comment.
Main has the same per-model budget gap, and the existing assembled-response discard on this line already behaves this way. Keeping this backport scoped to parity
|
bugbot run |
[Medium impact] This PR appears safe to merge SummaryPreserves native streamed
Reviews (1) · Last reviewed commit: "fix(responses): preserve native stream s..." · Reviewed by Greptile |
There was a problem hiding this comment.
✅ 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 8333a5a. Configure here.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…rt_50286_lts_1_108_x Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> # Conflicts: # litellm/litellm_core_utils/litellm_logging.py
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…_x' into litellm_backport_50286_lts_1_108_x
…rt_50286_lts_1_108_x Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> # Conflicts: # litellm/litellm_core_utils/litellm_logging.py
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
lts-scope: cost
Backport of #50286 to
lts/1.108.xTLDR
Problem this solves:
/v1/responsescall after completionHow it solves it:
User Flow
Before: the blocked request shows up twice in spend logs, once paid and once at $0
"stream": truebehind a post_call guardrailAfter: the same request shows up once, as a failure that carries the real tokens and spend
Pre-Submission checklist
Screenshots / Proof of Fix
The corrected live run showed the fix working on native streamed Responses requests
The rejected Before request persisted as a paid success. The rejected After request persisted as one failure with the real usage and spend. An unblocked After request persisted as a normal paid success
Only this corrected end-of-stream run is included below. It used real OpenAI GPT-5.6 requests, the built-in custom-code guardrail, real PostgreSQL and dedicated Redis. No provider or database mocks were used
Shared setup
The baseline is
617a2d4ac459b939ac515234438a0268d1a435c0fromorigin/lts/1.108.x. The fixed tip is8333a5a3ce42a009c7321af0ece144a44bcbd5a0Both proxies used two workers, the same PostgreSQL database and dedicated Redis at
127.0.0.1:6396. Before worker PIDs were 34434 and 34435. After worker PIDs were 34562 and 34563. Reload was omitted to keep two actual serving workers, matching both sidesOPENAI_API_KEYandDATABASE_URLwere already present in the environment.LITELLM_MASTER_KEYbelow is a disposable local proof token. The bundled model cost map listsgpt-5.6with native Responses streaming supportPostgreSQL was started with the command below and returned accepting connections. This database had already been synchronized to the baseline schema for the proof setup.
DISABLE_SCHEMA_UPDATE=trueavoids its unrelated existing migration-history baseline refusal, not persistenceObserved PostgreSQL readiness
Configuration needed to reach the changed path
The stock
custom_codeYAML initializer does not forward streaming flags to its instance, atlitellm/proxy/guardrails/guardrail_hooks/custom_code/__init__.py:45-51This proof therefore uses the supported custom Python initializer in
guardrail_registry.py:871-925to construct the unchanged built-inCustomCodeGuardrailand supply its streaming configuration throughguardrail_config. The unified guardrail explicitly reads that dictionary atunified_guardrail.py:1062-1068. This small local configuration adapter does not replace or override any guardrail implementation, provider call, logging method or database operationBoth flags matter. End-only scanning waits for the provider's terminal event. Buffering holds all output until moderation passes, so a rejection raises to the proxy failure handler rather than being consumed as an in-stream error by
emit_streaming_http_erroratunified_guardrail.py:496-528Exact adapter at
/home/ubuntu/guardrail_proof_50286.pyExact shared config at
/home/ubuntu/50286-config.yamlHow the request reaches the changed code
The only production caller of
_arm_deferred_stream_dispatchislitellm/proxy/common_request_processing.py:2991, under the post-call-guardrail condition at line 2990._has_post_call_guardrailsat lines 3495-3508 recognizes the configured post-callCustomGuardrailThe arming helper at lines 3909-3997 assigns one callback for
CustomStreamWrapperat line 3967, or the native callback for streamingaresponsesandanthropic_messagesat line 3997. These are the two assignments that arm deferred completionlitellm/responses/streaming_iterator.py:602reads that callback to setdeferred_dispatch_armed. The completed native response then parks its logging dispatch at lines 603-608The final guardrail scan runs after exhausting the provider iterator, at
unified_guardrail.py:1392-1442. With all output buffered, its rejection re-raises from line 528.ProxyLogging.async_post_call_streaming_iterator_hookcatches it atlitellm/proxy/utils.py:4651-4656and calls_discard_deferred_stream_logging_for_failure. The other discard caller is the pipeline streaming exception handler at line 4564Temporary local-only print statements recorded the completed-response callback being armed, the type offered to the discard helper, and the fixed helper closing the parked coroutine with its cost and tokens. These prints were removed after the run. No committed behavior changed during verification
Before (617a2d4)
Start a fresh baseline proxy with explicit worktree imports
Readiness returned
"I'm alive!"fromGET http://127.0.0.1:4126/health/livelinessRequest the blocked word from the real provider
The SSE ended with
response.failedand[DONE]. Buffered model output was never released to the clientComplete blocked SSE
event: response.failed
data: {"type":"response.failed","response":{"id":"resp_321a8ab1b8504b53ba22bf63fe8a1ca3","created_at":1794445142,"error":{"code":"invalid_request_error","message":"400: {'error': 'Blocked pineapple at end of stream', 'guardrail': 'block-proof-marker', 'detection_info': {}, 'guardrail_name': 'block-proof-marker', 'guardrail_mode': 'post_call'}"},"object":"response","output":[],"status":"failed"},"sequence_number":0}
data: [DONE]
After the spend writer ran, query PostgreSQL and the spend API using the commands below
Observed one row, with status
success, spend0.000172, 13 input tokens, 6 output tokens and 19 total tokensThe defect is a blocked request logged as a paid success. No second persisted zero-cost failure row was observed, and the reason is not established by this proof
After (8333a5a)
Start a fresh fixed proxy on a different port with otherwise identical configuration
Readiness returned
"I'm alive!"fromGET http://127.0.0.1:4127/health/livelinessSend the same blocked request
The SSE again ended in the guardrail rejection
Complete blocked SSE
event: response.failed
data: {"type":"response.failed","response":{"id":"resp_d54bbdf6340a444e942866a2dcfad4cc","created_at":1794445145,"error":{"code":"invalid_request_error","message":"400: {'error': 'Blocked pineapple at end of stream', 'guardrail': 'block-proof-marker', 'detection_info': {}, 'guardrail_name': 'block-proof-marker', 'guardrail_mode': 'post_call'}"},"object":"response","output":[],"status":"failed"},"sequence_number":0}
data: [DONE]
Send an unblocked request through the same After proxy
The stream returned
hello,response.completedand[DONE]. The terminal response reported 13 input tokens, 5 output tokens, 18 total tokens andcost: 0.000152. Full output is saved at/home/ubuntu/50286-eos-happy.sseWait for the spend writer, then query all three requests
The writer logged transactions at 00:59:05 for the blocked After request and 00:59:11 for the happy request. The final query below ran after both flushes
Observed PostgreSQL output
--------------------------+---------+----------+---------------+-------------------+--------------
50286-eos-after-blocked | failure | 0.000172 | 13 | 6 | 19
50286-eos-after-happy | success | 0.000152 | 13 | 5 | 18
50286-eos-before-blocked | success | 0.000172 | 13 | 6 | 19
(3 rows)
Cleanup
Both proxy supervisors were stopped with
kill -TERM 34301 34353. All four serving workers exited, and the port check below returned only the header with no listenersss -ltn '( sport = :4126 or sport = :4127 )'Temporary debug prints were removed from both worktrees. The After worktree is clean at
8333a5a3ce. The baseline retains only the previously copied unit regression test, which the proxy does not import. No commit or push was made for this proofThe local adapter and configuration remain outside both repositories so this run can be repeated. PostgreSQL and dedicated Redis remain running
Type
🐛 Bug Fix
Caveats (if any)
Low
Pick table
96b6f18368dbd83be2eb1afb5577ea998af3251a8333a5a3ce42a009c7321af0ece144a44bcbd5a00ae5111a2ce14ad3bdcb34218f698995319926e88333a5a3ce42a009c7321af0ece144a44bcbd5a0The three MCP test-only commits of #50286 are recorded as main_only_commits in the pair block, since this line ships no MCP multi-round billing code. Pair record updated 2026-11-22T16:45:00Z
Details
Link to Devin session: https://app.devin.ai/sessions/f4d954f6c916421299ae625f95a74ed4
Open in Devin Desktop: https://app.devin.ai/desktop/session/f4d954f6c916421299ae625f95a74ed4?variant=devin
Requested by: @mateo-berri
Note
Medium Risk
Touches proxy streaming failure paths and spend logging for native Responses streams, which affects billing accuracy but not auth or core request handling.
Overview
Fixes double or mis-attributed spend logs when a post-call guardrail rejects a finished native
/v1/responsesstream: the parked “success” dispatch now carries precomputed usage and cost (BilledRoundsSpend/BilledRoundsDispatch), and on failure the proxy drops that success log, closes the parked coroutine, and records the spend on the failure row instead of a $0 failure beside a paid success.Responses streaming wraps deferred completion args with billed rounds when the assembled response is a
ResponsesAPIResponse. Deferred stream completion in the proxy recognizesBilledRoundsDispatchand enqueues its dispatch like other native streams. A unit test asserts guardrail-rejected native streams produce one failure row with real tokens and cost.Reviewed by Cursor Bugbot for commit 8333a5a. Bugbot is set up for automated code reviews on this repo. Configure here.