Skip to content

fix(responses): keep unconfirmed OpenAI disconnect tokens out of spend - #53782

Open
SoulmatelynchVFX wants to merge 2 commits into
BerriAI:mainfrom
SoulmatelynchVFX:codex/openai-responses-disconnect-cost
Open

SoulmatelynchVFX wants to merge 2 commits into
BerriAI:mainfrom
SoulmatelynchVFX:codex/openai-responses-disconnect-cost

Conversation

@SoulmatelynchVFX

@SoulmatelynchVFX SoulmatelynchVFX commented Nov 23, 2026 •

Copy link
Copy Markdown
Details

TLDR

  • Keep local token estimates on native OpenAI Responses disconnects.
  • Record only confirmed charges on that spend row.
  • Keep known charges when the tokenizer fails.

User flow

A client receives a partial answer from /v1/responses and disconnects before OpenAI sends usage. The proxy records the partial result and marks locally counted tokens as estimated. If the tokenizer fails, it records unknown usage and keeps any separately confirmed charge. When OpenAI reports usage, the cache split still determines token cost.

Relevant issues

Fixes #52589

#53394 covers provider-reported usage on bridged streams. This change covers the native OpenAI stream when the terminal usage is missing.

Validation

Before the fix, the tokenizer-error case returned no spend row. The same regression now checks that the row keeps the known charge and marks usage as unknown. The other cases cover estimated usage, cached provider usage, and completed and provider-incomplete events.

At 7fc6d47e, the native Windows build completed offline and 47 focused tests passed. Ruff and the diff check passed on the same commit.

uv run pytest -q tests/unit/responses/test_responses_streaming_iterator.py

Local HTTP acceptance (Windows)

Ran the LiteLLM proxy against a loopback server that simulated OpenAI Responses. Both requests returned HTTP 200 and each produced one spend row.

Scenario Observed spend row
Close the HTTP stream after the first output delta, before any upstream usage arrives 10 estimated tokens, usage_observation=estimated, spend 0.0
Read the stream to completion with 10 input tokens, 9 of them cached, and 2 output tokens 12 tokens, spend 0.0059 at the fixture rates

The completed request used synthetic rates of 0.001 per uncached input token, 0.0001 per cached input token, and 0.002 per output token. The check captured the rows generated by the proxy callback. Live OpenAI billing and database persistence are pending.

Caveats

The spend log records confirmed charges. The provider can still charge for a request the client canceled.

This draft has local regression coverage. Live validation against OpenAI is pending.

@SoulmatelynchVFX
SoulmatelynchVFX marked this pull request as ready for review November 23, 2026 10:22
@veria-ai

veria-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The PR changes spend accounting for disconnected OpenAI response streams to exclude token usage that has not been confirmed by an authoritative usage event.

An open issue allows a key holder to consume streamed output and disconnect before terminal usage arrives, causing the request to be recorded at zero cost and its budget reservation to be cleared. Repeating this can bypass key or team spend budgets. No issues have been addressed yet; budget enforcement still needs to retain an estimated or pending debit until usage is reconciled.

Open issues (1)

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

Reviews

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T11:12:27.090281Z 46b46ec New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.


billable_response: Final = (
priced_result.model_copy(
update={"usage": ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(None)}

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: Disconnecting a stream bypasses spend budgets

For OpenAI streams without usage in response.created, a key holder can read generated output and disconnect before the terminal usage event, causing this branch to price the consumed tokens at zero. _bill_partial_streamed_spend_on_disconnect dispatches that cost as success, and the spend callback reconciles the budget reservation to zero, allowing repeated requests without reducing the key/team token-spend budget. Keep an estimated or pending debit for budget enforcement until authoritative usage is reconciled, even if confirmed spend excludes estimates.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7fc6d47eed

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1196 to +1198
source: Final = (
(UsageObservation.UNKNOWN if usage is None else UsageObservation.ESTIMATED)
if openai and reported is None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Provide live before/after proof for disconnect billing

The commit explicitly leaves live OpenAI billing and persistence pending. Supply the required before/after proxy proof, including cached and continued requests.

AGENTS.md reference: AGENTS.md:L53-L53

Useful? React with 👍 / 👎.

raise ValueError("Tokenizer failed")

if tokenizer_fails:
monkeypatch.setattr(litellm, "token_counter", fail_to_count_tokens)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Test tokenizer errors without replacing LiteLLM code

tests/unit/AGENTS.md prohibits internal doubles. Replacing litellm.token_counter bypasses production tokenization in this regression. Exercise a real failing tokenizer input instead.

AGENTS.md reference: tests/unit/AGENTS.md:L27-L27

Useful? React with 👍 / 👎.

Keep admission-time reservations in place when a disconnected Responses stream has no provider-reported usage. Continue recording separately confirmed charges and exercise the real tokenizer failure path.
@Neomundi-Labs

Copy link
Copy Markdown

On litellm 1.111.0, the version PyPI serves right now, we ran 24 calls across four code paths and two models, against one provider, to find out whether a caller can establish where a token count came from. Fifteen of the twenty-four were traceable to the provider. Six of those fifteen were streaming calls, and that part surprised us, because we had predicted the opposite: on that provider the surface emits a usage block inside the stream even without stream_options, and litellm keeps it in its chunks, so a bare synchronous stream was traceable three times out of three. The nine that were not traceable were all on acompletion(..., stream=True), nine times out of nine.

We have stopped naming one mechanism for it, because what we saw against a real provider and what a loopback bench shows are not the same thing. What does reproduce without a key is the consequence. Driving two streamed calls through a loopback server that speaks the chat-completions shape, where the only difference is whether the server sends a terminal usage chunk, the caller gets back a usage block in both cases, with the same keys, with a cost attached, and with no field saying which is which. The one observable difference is that prompt_tokens_details is null when the server sent nothing, and an absence has other causes since a provider can report usage without a cache split.

Worth separating two things that are easy to run together. On the loopback bench we know one of the two counts was derived locally, because we control the server. On a real provider we established something weaker: the origin is not recoverable from what the caller holds. We did not establish that those nine counts were estimates, and we are not saying they are wrong.

That is why the usage_observation marker in this PR reads as the right shape to us. Carrying it in hidden_params and inside the usage object, so it shows up in usage.model_dump() and in additional_usage_values, is what makes it usable by whoever reads the spend row afterwards. The same marker on the chat completions streaming path would close the gap we measured, and that is a separate change rather than a request on this PR.

On the budget bypass veria-ai flagged above, what we have learned on our own accounting is that the number you would defend on an invoice and the number enforcement holds have to be two fields rather than one. Zeroing the priced row is right for the invoice. Enforcement still needs something to hold until authoritative usage arrives, and this PR already computes exactly the information that would let it hold an estimate and know that it is an estimate. Worth noting that record_partial_usage_for_failure in litellm_logging.py accepts an observation keyword and that its body stores only combined_usage_object and response_cost, while _accounting_usage_observed is popped further down when the attempt is stashed, so on main at 530a445 the provenance that gets computed is dropped before anything can use it. If an estimated debit is how this gets resolved, that looks like where it would live. We may be reading it wrong, the file is large and we read it rather than ran it.

One thing on the live proof. The loopback run in the description already covers the disconnect shape, so what is missing is the cache split and the continued turn rather than the disconnect itself. Driving the same three turn conversation twice through the proxy, once with the history resent and once with the provider continuation id, reading billed and cached tokens on every turn, is what AGENTS.md asks for and it would close that gap without needing a new harness.

Disclosure, we work on NeoMundi, which publishes a small provenance wrapper for LiteLLM among other things. Nothing above needs it. The measurement reproduces with litellm alone and the code reading is just the file at the commit named.

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.

Responses disconnects price local token estimates as uncached provider usage

2 participants