Skip to content

fix(responses): preserve native stream spend on guardrail rejection (lts/1.108.x backport of #50286) - #51303

Open
mateo-berri wants to merge 6 commits into
lts/1.108.xfrom
litellm_backport_50286_lts_1_108_x
Open

mateo-berri wants to merge 6 commits into
lts/1.108.xfrom
litellm_backport_50286_lts_1_108_x

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

lts-scope: cost

Backport of #50286 to lts/1.108.x

TLDR

Problem this solves:

  • A guardrail blocking a native streamed /v1/responses call after completion
  • The paid success row still logs, beside a second $0 failure row

How it solves it:

  • The parked success log now carries the response's usage and cost
  • On rejection the success log is dropped and the failure row bills that spend

User Flow

Before: the blocked request shows up twice in spend logs, once paid and once at $0

  1. A developer sends POST http://localhost:4000/v1/responses with "stream": true behind a post_call guardrail
  2. The guardrail rejects the finished stream and the client sees the block error
  3. http://localhost:4000/ui/?page=logs shows a paid success row plus a $0 failure row

After: the same request shows up once, as a failure that carries the real tokens and spend

  1. The developer sends the same streamed POST http://localhost:4000/v1/responses
  2. The guardrail rejects it and the client sees the same block error
  3. The logs page shows one failure row with the real token counts and cost

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings

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 617a2d4ac459b939ac515234438a0268d1a435c0 from origin/lts/1.108.x. The fixed tip is 8333a5a3ce42a009c7321af0ece144a44bcbd5a0

Both 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 sides

OPENAI_API_KEY and DATABASE_URL were already present in the environment. LITELLM_MASTER_KEY below is a disposable local proof token. The bundled model cost map lists gpt-5.6 with native Responses streaming support

PostgreSQL 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=true avoids its unrelated existing migration-history baseline refusal, not persistence

sudo service postgresql start
pg_isready
# Initial schema synchronization used for this proof database
cd /home/ubuntu/wt_lts_1_108_x_50286_base
PYTHONPATH="$PWD:$PWD/enterprise" uv run --no-sync prisma db push --schema schema.prisma --skip-generate
# Dedicated Redis was already running with these settings
redis-server --port 6396 --bind 127.0.0.1 --save '' --appendonly no

Observed PostgreSQL readiness

/var/run/postgresql:5432 - accepting connections

Configuration needed to reach the changed path

The stock custom_code YAML initializer does not forward streaming flags to its instance, at litellm/proxy/guardrails/guardrail_hooks/custom_code/__init__.py:45-51

This proof therefore uses the supported custom Python initializer in guardrail_registry.py:871-925 to construct the unchanged built-in CustomCodeGuardrail and supply its streaming configuration through guardrail_config. The unified guardrail explicitly reads that dictionary at unified_guardrail.py:1062-1068. This small local configuration adapter does not replace or override any guardrail implementation, provider call, logging method or database operation

Both 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_error at unified_guardrail.py:496-528

Exact adapter at /home/ubuntu/guardrail_proof_50286.py

from litellm.proxy.guardrails.guardrail_hooks.custom_code.custom_code_guardrail import CustomCodeGuardrail


def configured_custom_code_guardrail(
    guardrail_name,
    event_hook,
    default_on,
    custom_code,
    streaming_end_of_stream_only=True,
    streaming_buffer_until_moderated=True,
    **kwargs,
):
    guardrail = CustomCodeGuardrail(
        guardrail_name=guardrail_name,
        event_hook=event_hook,
        default_on=default_on,
        custom_code=custom_code,
    )
    guardrail.guardrail_config = {
        "streaming_end_of_stream_only": streaming_end_of_stream_only,
        "streaming_buffer_until_moderated": streaming_buffer_until_moderated,
    }
    return guardrail

Exact shared config at /home/ubuntu/50286-config.yaml

model_list:
  - model_name: proof-gpt
    litellm_params:
      model: openai/gpt-5.6
      api_key: os.environ/OPENAI_API_KEY
guardrails:
  - guardrail_name: block-proof-marker
    litellm_params:
      guardrail: guardrail_proof_50286.configured_custom_code_guardrail
      streaming_end_of_stream_only: true
      streaming_buffer_until_moderated: true
      mode: post_call
      default_on: true
      custom_code: |
        def apply_guardrail(inputs, request_data, input_type):
            if input_type == "response":
                for text in inputs.get("texts") or []:
                    if contains(lower(text), "pineapple"):
                        return block("Blocked pineapple at end of stream")
            return allow()
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6396
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  proxy_batch_write_at: 2
  coordination_redis:
    host: 127.0.0.1
    port: 6396
litellm_settings:
  store_prompts_in_spend_logs: true

How the request reaches the changed code

The only production caller of _arm_deferred_stream_dispatch is litellm/proxy/common_request_processing.py:2991, under the post-call-guardrail condition at line 2990. _has_post_call_guardrails at lines 3495-3508 recognizes the configured post-call CustomGuardrail

The arming helper at lines 3909-3997 assigns one callback for CustomStreamWrapper at line 3967, or the native callback for streaming aresponses and anthropic_messages at line 3997. These are the two assignments that arm deferred completion

litellm/responses/streaming_iterator.py:602 reads that callback to set deferred_dispatch_armed. The completed native response then parks its logging dispatch at lines 603-608

The 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_hook catches it at litellm/proxy/utils.py:4651-4656 and calls _discard_deferred_stream_logging_for_failure. The other discard caller is the pipeline streaming exception handler at line 4564

Temporary 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)

  1. Start a fresh baseline proxy with explicit worktree imports

    cd /home/ubuntu/wt_lts_1_108_x_50286_base
    export PYTHONPATH="$PWD:$PWD/enterprise:/home/ubuntu"
    export LITELLM_LOCAL_MODEL_COST_MAP=True
    export LITELLM_MASTER_KEY=sk-50286-local-proof
    export DISABLE_SCHEMA_UPDATE=true
    /home/ubuntu/repos/litellm/.venv/bin/python -m litellm.proxy.proxy_cli \
      --config /home/ubuntu/50286-config.yaml --port 4126 --num_workers 2 --detailed_debug \
      > /home/ubuntu/50286-eos-before-proxy.log 2>&1

    Readiness returned "I'm alive!" from GET http://127.0.0.1:4126/health/liveliness

  2. Request the blocked word from the real provider

    curl -sS -N --max-time 180 \
      -D /home/ubuntu/50286-eos-before-headers.txt \
      http://127.0.0.1:4126/v1/responses \
      -H 'Authorization: Bearer sk-50286-local-proof' \
      -H 'Content-Type: application/json' \
      -H 'x-litellm-call-id: 50286-eos-before-blocked' \
      -d '{"model":"proof-gpt","stream":true,"input":"Reply with exactly one word, pineapple","reasoning":{"effort":"none"},"max_output_tokens":32}' \
      > /home/ubuntu/50286-eos-before.sse

    The SSE ended with response.failed and [DONE]. Buffered model output was never released to the client

    Complete 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]


</details>

Observed server ordering proves completion happened before the guardrail rejected

```text
50286_PROOF terminal_completed armed=True
00:59:02 - LiteLLM Proxy:DEBUG: unified_guardrail.py:1394 - Processing final streaming response with all 10 chunks for guardrail block-proof-marker
50286_PROOF discard_candidate=coroutine error=HTTPException
  1. After the spend writer ran, query PostgreSQL and the spend API using the commands below

    Observed one row, with status success, spend 0.000172, 13 input tokens, 6 output tokens and 19 total tokens

    The 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)

  1. Start a fresh fixed proxy on a different port with otherwise identical configuration

    cd /home/ubuntu/wt_lts_1_108_x_50286
    export PYTHONPATH="$PWD:$PWD/enterprise:/home/ubuntu"
    export LITELLM_LOCAL_MODEL_COST_MAP=True
    export LITELLM_MASTER_KEY=sk-50286-local-proof
    export DISABLE_SCHEMA_UPDATE=true
    /home/ubuntu/repos/litellm/.venv/bin/python -m litellm.proxy.proxy_cli \
      --config /home/ubuntu/50286-config.yaml --port 4127 --num_workers 2 --detailed_debug \
      > /home/ubuntu/50286-eos-after-proxy.log 2>&1

    Readiness returned "I'm alive!" from GET http://127.0.0.1:4127/health/liveliness

  2. Send the same blocked request

    curl -sS -N --max-time 180 \
      -D /home/ubuntu/50286-eos-after-headers.txt \
      http://127.0.0.1:4127/v1/responses \
      -H 'Authorization: Bearer sk-50286-local-proof' \
      -H 'Content-Type: application/json' \
      -H 'x-litellm-call-id: 50286-eos-after-blocked' \
      -d '{"model":"proof-gpt","stream":true,"input":"Reply with exactly one word, pineapple","reasoning":{"effort":"none"},"max_output_tokens":32}' \
      > /home/ubuntu/50286-eos-after.sse

    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]


</details>

The server log confirms the completed response was parked before rejection and the fixed discard helper closed that dispatch with its real spend

```text
50286_PROOF terminal_completed armed=True
00:59:05 - LiteLLM Proxy:DEBUG: unified_guardrail.py:1394 - Processing final streaming response with all 10 chunks for guardrail block-proof-marker
50286_PROOF discard_candidate=BilledRoundsDispatch error=HTTPException
50286_PROOF parked_dispatch_closed cost=0.000172 tokens=19
  1. Send an unblocked request through the same After proxy

    curl -sS -N --max-time 180 \
      -D /home/ubuntu/50286-eos-happy-headers.txt \
      http://127.0.0.1:4127/v1/responses \
      -H 'Authorization: Bearer sk-50286-local-proof' \
      -H 'Content-Type: application/json' \
      -H 'x-litellm-call-id: 50286-eos-after-happy' \
      -d '{"model":"proof-gpt","stream":true,"input":"Reply with exactly one word, hello","reasoning":{"effort":"none"},"max_output_tokens":32}' \
      > /home/ubuntu/50286-eos-happy.sse

    The stream returned hello, response.completed and [DONE]. The terminal response reported 13 input tokens, 5 output tokens, 18 total tokens and cost: 0.000152. Full output is saved at /home/ubuntu/50286-eos-happy.sse

  2. Wait 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

    psql "$DATABASE_URL" -c 'SELECT litellm_call_id, status, spend, prompt_tokens, completion_tokens, total_tokens FROM "LiteLLM_SpendLogs" WHERE litellm_call_id LIKE '\''50286-eos-%'\'' ORDER BY litellm_call_id;'
    curl -sS 'http://127.0.0.1:4126/spend/logs?request_id=50286-eos-before-blocked' \
      -H 'Authorization: Bearer sk-50286-local-proof' > /home/ubuntu/50286-eos-before-spend-api.json
    curl -sS 'http://127.0.0.1:4127/spend/logs?request_id=50286-eos-after-blocked' \
      -H 'Authorization: Bearer sk-50286-local-proof' > /home/ubuntu/50286-eos-after-spend-api.json
    curl -sS 'http://127.0.0.1:4127/spend/logs?request_id=50286-eos-after-happy' \
      -H 'Authorization: Bearer sk-50286-local-proof' > /home/ubuntu/50286-eos-happy-spend-api.json

    Observed PostgreSQL output

      litellm_call_id      | status  |  spend   | prompt_tokens | completion_tokens | total_tokens 
    

--------------------------+---------+----------+---------------+-------------------+--------------
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)


Each spend API response contained exactly one row. Selected fields matched PostgreSQL

```text
before [{'litellm_call_id': '50286-eos-before-blocked', 'status': 'success', 'spend': 0.000172, 'prompt_tokens': 13, 'completion_tokens': 6, 'total_tokens': 19}]
after [{'litellm_call_id': '50286-eos-after-blocked', 'status': 'failure', 'spend': 0.000172, 'prompt_tokens': 13, 'completion_tokens': 6, 'total_tokens': 19}]
happy [{'litellm_call_id': '50286-eos-after-happy', 'status': 'success', 'spend': 0.000152, 'prompt_tokens': 13, 'completion_tokens': 5, 'total_tokens': 18}]

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 listeners

ss -ltn '( sport = :4126 or sport = :4127 )'
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess

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 proof

The 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

main commit LTS commit note
96b6f18368dbd83be2eb1afb5577ea998af3251a 8333a5a3ce42a009c7321af0ece144a44bcbd5a0 native stream part picked with cherry-pick -x, its MCP stream_round_billing hunk has no module on lts/1.108.x
0ae5111a2ce14ad3bdcb34218f698995319926e8 8333a5a3ce42a009c7321af0ece144a44bcbd5a0 typed _deferred_logging_dispatch, adapted to response_cost_calculator

The 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/responses stream: 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 recognizes BilledRoundsDispatch and 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.

…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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@veria-ai

veria-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This backport preserves native /v1/responses streaming spend in failure records when an end-of-stream guardrail rejects the response.

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 model_max_budget while other budgets still have headroom. No issues have been addressed yet.

Open issues (1)

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

Reviews

Comment thread litellm/proxy/utils.py
case ModelResponse():
logging_obj.record_assembled_response_for_failure(assembled)
case BilledRoundsDispatch():
assembled.dispatch.close()

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] This PR appears safe to merge

Summary

Preserves native streamed /v1/responses spend when a post-call guardrail rejects the finished response

  • Rejected Responses streams keep their provider spend on the failure record.

Reviews (1) · Last reviewed commit: "fix(responses): preserve native stream s..." · Reviewed by Greptile

@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 8333a5a. Configure here.

@codecov

codecov Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.10526% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/responses/streaming_iterator.py 75.00% 3 Missing ⚠️

📢 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
mateo-berri and others added 4 commits November 23, 2026 18:29
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…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>

This branch has not been deployed

No deployments
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.

1 participant