Repository navigation
fix(responses): keep unconfirmed OpenAI disconnect tokens out of spend - #53782
SoulmatelynchVFX wants to merge 2 commits into
Conversation
PR overviewThe 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 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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)} |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
| source: Final = ( | ||
| (UsageObservation.UNKNOWN if usage is None else UsageObservation.ESTIMATED) | ||
| if openai and reported is None |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
|
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 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 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 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 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. |
Details
TLDR
User flow
A client receives a partial answer from
/v1/responsesand 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.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.
usage_observation=estimated, spend0.00.0059at the fixture ratesThe completed request used synthetic rates of
0.001per uncached input token,0.0001per cached input token, and0.002per 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.