Repository navigation
fix(cost): backport usage.seconds billing and the unsized FLAC guard to lts/1.108.x - #50860
Conversation
Line port of the usage.seconds billing slice onto lts/1.108.x: normalized_audio_duration_seconds and _get_transcription_usage_duration from #35600 (ecb8ef5), and the provider-seconds-first _transcription_duration_for_cost from #50727 (dfb1aac), with their unit tests. The rest of #35600 stays on main.
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
PR overviewNo security issues were found in this pull request. Reviews
|
|
bugbot run |
[Medium impact] The changes affect transcription cost and duration measurement workflows. The billing changes appear sound, but the new test must meet the repository's explicit testing requirements before merging Findings
SummaryThis backport prefers valid provider-reported transcription seconds and rejects libsndfile's unknown frame count before calculating duration. It adds unit and integration coverage for the billing changes The new mocked pricing test needs to follow the repository's test and typing requirements kerry-berri explicitly acknowledges that unsized audio without provider usage bills zero, existing incorrect spend is not repaired, zero-cost responses omit the cost header, AWS unknown-duration jobs use the maximum charge with unit-only coverage, and
Reviews (1) · Last reviewed commit: "test(transcription): annotate the new pa..." · Reviewed by Greptile |
| @patch( # test-quality-ok: isolates duration selection from the model pricing table | ||
| "litellm.cost_calculator.openai_cost_per_second" | ||
| ) | ||
| def test_completion_cost_prefers_provider_usage_duration_over_measured_duration(self, mock_cost_fn): |
There was a problem hiding this comment.
This test replaces openai_cost_per_second and checks its arguments instead of the bill. The test guide forbids replacing LiteLLM's own code. The new parameters and locals also lack required types and Final annotations. Assert the real bill and satisfy these repository requirements before merging
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
You're right, #50727 already carries this test, and the constructor difference is immaterial. I retract the real-price objection. Missing annotations remain a separate concern.
There was a problem hiding this comment.
The locals match main's merged test line for line, and the type gates pass at this tip, so this pick stays as main has it.
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 0633730. Configure here.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
TLDR
Backport of the transcription billing fix to
lts/1.108.x. The main side is #35600, #50727 (theusage.secondsslice, hand-ported as one commit) and #50842 (the unsized FLAC guard, picked as its four commits). #50842 has merged on main.Problem this solves:
jsonandtextresponsesHow it solves it:
usage.secondsfirst when it is a valid positive numberUser Flow
Before: a developer who transcribes a FLAC that was encoded to a pipe is billed about $43 billion for one request, and the key stops working
ffmpeg -i normal.flac -f flac - > piped.flac, which writes a FLAC with no sample count in its headermodel=gpt-transcribe,response_format=jsonandpiped.flac, and get 200 with the transcriptx-litellm-response-cost: 43234556422.75676and the key's spend jumps to the same amount against its $500 budgetBudget has been exceeded! ... Current cost: 43234556422.76061, Max budget: 500.0After: the same request bills the 11 seconds OpenAI reports, and the key keeps working
ffmpeg -i normal.flac -f flac - > piped.flac, which writes a FLAC with no sample count in its headermodel=gpt-transcribe,response_format=jsonandpiped.flac, and get 200 with the transcriptx-litellm-response-cost: 0.0008249999999999999(11 s x $0.000075) and the key's spend rises by that amount. Withresponse_format=textthere is nousage, so that request bills $0 and carries no cost headernormal.flacreturns 200 and bills $0.000825Linear ticket
Resolves LIT-10595
Backport checklist
lts/1.108.x, base2a56160037(v1.108.4 + 11). No LiteLLM version bump on the LTS line,enterprise/andlitellm-proxy-extras/untouched so no subpackage bump76539f9156fix(cost): bill transcriptions by the seconds the provider reports, hand-ported slice of feat(realtime)!: support latest OpenAI audio models #35600 and fix(cost)!: bill transcriptions by the seconds the provider reports #50727, clean70f388a8abfix(transcription): treat libsndfile's unknown frame count as no duration, cherry-pick of e6a0534, adapted to the line: the line'stests/unit/litellm_core_utils/test_audio_utils.pylacks main'sfrom typing import Final, somake check(ruff on the test tree) reported F821 on the newstreaminfo: Final. The import was added inside this pick3f50c8734erefactor(transcription): inline the unknown frame count check, cherry-pick of b6d25f2, clean0e5241c504fix(transcription): read the frame count once to keep the type gate flat, cherry-pick of 54dcd92, clean0633730678test(transcription): annotate the new passthrough test's locals as Final, cherry-pick of eb0f251, cleanLITELLM_LOCAL_MODEL_COST_MAP=True PYTHONPATH="$PWD:$PWD/enterprise". No pass-to-fail transition against the line tipBASE_REF=origin/lts/1.108.x make check: PASS at the tip (the first run at the pre-fix tip failed only on the F821 above)ruff check --select F821,F811on the changedlitellm/files clean, scopedruff format --checkclean, AST importer scan found no dropped module-level nameuv.lockvs main's: nothing to bump. Every finding (pillow 12.3.0, dnspython 2.8.0, filelock 3.20.3, tornado 6.5.10) is at the same version on main, and the one line-only finding, diskcache 5.6.3 GHSA-w8v5-vhqr-4h9v, has no fixed releaseFinalimport) reproduced by running ruff on the test tree and fixed inside its pick, 0 dissent. Identifiers resolve on the line, picked tests pass, no line-only caller of_transcription_duration_for_cost,calculate_request_durationormedia_file_secondsbreaks (main.pyguardsNone, the Azure speech handler doesor 0.0, the Transcribe handler already routesNoneto its max-job-cost path)python tests/integration/run.py cost --workers 2with the three whisper caseswhisper-next-transcriptions-per-second,whisper-next-transcriptions-unsized-flac-no-usage,whisper-verbose-next-transcriptions-duration: 3 passedPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Both legs ran against a live proxy with real OpenAI
gpt-transcribeandwhisper-1calls, Postgres, one dedicated Redis on port 6390 and two workers. Each leg had its own empty database. The line prints"workers" flag is ignored when reloading is enabledand starts one worker with--reload, so both proxies ran without--reloadand each logged twoStarted server processlines.Proxy command, run from a checkout of each commit, port 4111 for Before and 4112 for After. Env vars set were
OPENAI_API_KEY,LITELLM_MASTER_KEY,DATABASE_URLandSTORE_MODEL_IN_DB=True.qa_config.yamlnormal.flacis 11.000 s of real speech (OpenAIgpt-4o-mini-ttswav,ffmpeg -ar 16000 -ac 1),piped.flacisffmpeg -i normal.flac -f flac - > piped.flac. soundfile readsnormal.flacas 176000 frames at 16 kHz andpiped.flacas 9223372036854775807 frames. Rates from this line's cost map:gpt-transcribe$0.000075/s,whisper-1$0.0001/s, so 11 s is $0.000825 and $0.0011.Key A (
max_budget: 500) runs cases 1, 2, 6a, 6b, 7, 3, 5a in that order. Key B (fresh,max_budget: 500) runs 4 then 5b, so the text case is not masked by key A already being over budget on Before. Each row reads status,x-litellm-response-cost, theLiteLLM_SpendLogsrow'sspend, and the key'sspendfrom/key/info.verbose_jsonis not compatible withgpt-transcribe, no header, failure row 0, 0.00385cases.sh, run asLITELLM_MASTER_KEY=... ./cases.sh <port> <database_url> <label>Before (2a56160)
./cases.sh 4111 postgresql://postgres:postgres@localhost:5432/lts_qa_before beforeoutput
After (0633730)
./cases.sh 4112 postgresql://postgres:postgres@localhost:5432/lts_qa_after afteroutput
The After proxy ran the
litellm/tree of63d2f813a7, which is byte-identical to the tip's (git diff --stat 63d2f813a7 0633730678is one import line intests/unit/litellm_core_utils/test_audio_utils.py).Type
Bug Fix
Caveats (if any)
Medium
usagenow logs $0, where the real cost is about $0.001 (carried from fix(transcription): stop billing a FLAC with no sample count as 576 trillion seconds #50842)Low
x-litellm-response-cost: 0. Observed live: the header is absent, becauseproxy_server.pyalready passeshidden_params.get("response_cost") or ""into the header builder here. Same user-visible result as maingpt-transcriberejectsresponse_format=verbose_jsonupstream (400), so that case could not be billed on either legFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/46b12279387447c08b2cc007358bb400
Open in Devin Desktop: https://app.devin.ai/desktop/session/46b12279387447c08b2cc007358bb400?variant=devin
Requested by: @kerry-berri
Note
Medium Risk
Changes spend-tracking and budget enforcement for transcription and Transcribe passthrough; incorrect duration logic could under- or over-charge, though the fix tightens validation and adds regression tests.
Overview
Fixes transcription spend that could treat pipe-encoded FLAC (no sample count in the header) as billions of seconds when libsndfile reports
2**63 - 1frames, blowing API key budgets.Transcription billing now resolves billable seconds via
_transcription_duration_for_cost: prefer validated providerusage.type=duration/usage.seconds, then measured duration from_hidden_paramsor responseduration, else 0. Malformed seconds (negative, NaN, inf, overflow) are dropped throughnormalized_audio_duration_seconds.Duration probing in
calculate_request_durationand Amazon Transcribe passthroughmedia_file_secondsreturns no duration when frame count is at or aboveLIBSNDFILE_UNKNOWN_FRAME_COUNT, so cost/logging does not infer length from unknown headers.Integration and unit tests cover unsized FLAC ($0 spend), provider-reported seconds over measured length, and the passthrough path.
Reviewed by Cursor Bugbot for commit 0633730. Bugbot is set up for automated code reviews on this repo. Configure here.