Repository navigation
fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata - #47639
Conversation
…e surrogates in multipart metadata
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Cursor Bugbot: Medium Risk at Pushes do not re-run this check. Comment |
|
bugbot run |
Merging this PR will not alter performance
|
…ot grow reportArgumentType
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 bd402ba. Configure here.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
Main CircleCI job integration-providers fails test_a_base_model_in_the_request_body_only_ever_loosens since this merged, because the body base_model is now stripped. Pipeline 91444 https://app.circleci.com/pipelines/github/BerriAI/litellm/91444 |
…e surrogates in multipart metadata (BerriAI#47639) * fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata * fix(proxy): type the parsed multipart metadata so basedpyright does not grow reportArgumentType --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Backport of BerriAI#47639 to stable/1.106.x Cherry-picked from 2a26895 (main)
…havior (#48665) * test(integration): update stale expectations to intended provider behavior Each expectation moved because a merged PR changed behavior on purpose. - chatgpt string input is wrapped as one user message (#41522) - Gemini 2.5 tool media sits beside function_response (#48428) - sampling knobs move to Gemini 3.5 Flash, which keeps them (#47645) - a body base_model is stripped without allow_client_pricing_override (#47639) - ai_decide answers without usage return usage null (#48261) - azure_ai forwards mapped client anthropic-beta values (#48033) - the OpenCode scripted upstream mints a fresh id per request * test(e2e-ui): type the guardrail name before deleting it GuardrailDeleteModal requires the exact name before Delete enables since #45893. All three guardrail delete flows now go through one helper. * test(observability): accept any sampled traceresponse flags and expect a 400 for a non-object body OpenTelemetry 1.45 (#48055) sets the W3C random trace id flag on new traces, so the gateway's traceresponse now ends in -03. The producer copies the server span's own trace flags, so the tests now accept any two-digit flags with the sampled bit set instead of pinning -01 #48438 made a non-object JSON body a 400 "Invalid JSON payload: expected an object" on purpose, so the [1] body case is renamed non_object_body and expects that 400 * test(observability): stop waiting on OpenTelemetry's export log line in the langtrace outage test The outage test waited for "Exception while exporting Span batch" in the proxy log, which is OpenTelemetry's wording and no longer appears with 1.45. The test keeps asserting what the gateway guarantees, callers unaffected during the outage, a live gateway, and every span after recovery delivered once with no outage span duplicated * test(guardrails): count the Responses disconnect spend rows #47611 added Since #47611 a streamed /v1/responses disconnect writes its own spend row, so the concurrent disconnect test saw 20 rows where it counted 10 by model group. It now reads each row's call type and expects ten acompletion rows with the outage verdict and ten aresponses rows with success. /v1/messages disconnects still write no row on main, so they are left out of the count rather than pinned as absent The responses-httpx case of the single disconnect test no longer needs its LIT-8603 skip and passes * test(observability): size K4's timeout from the harness boot budget K4 boots three two-worker proxies in a row. On CircleCI each boot takes 43 to 58 seconds, so a passing run took 179.97s against its fixed 180s cap and 6 of 30 runs hit pytest-timeout. The cap and the restart gate wait now come from readiness_seconds and graceful_stop_seconds, like other multi-boot tests
…e surrogates in multipart metadata (#47639) * fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata * fix(proxy): type the parsed multipart metadata so basedpyright does not grow reportArgumentType --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit 2a26895)
…e surrogates in multipart metadata (BerriAI#47639) * fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata * fix(proxy): type the parsed multipart metadata so basedpyright does not grow reportArgumentType --------- Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Backport of BerriAI#47639 to stable/1.105.x. Cherry-picked from 2a26895 (main).
…hat rc/1.108.0 needs rc/1.108.0 carries OpenTelemetry 1.45.1 (BerriAI#48055), BerriAI#47611 and the BerriAI#47639 base_model strip, so the OTel traceresponse header, langtrace outage, guardrail concurrent-disconnect and Bedrock lookaround tests expected the old behavior. This takes BerriAI#48665's hunks for those four files only, without the unhandled to non_object_body rename, which depends on BerriAI#48438 that rc does not have (cherry picked from commit 21ab2cb, four test files only)
A caller could put
base_modelin a chat request body and have their spend row priced at that cheaper model, on success rows and on the billed failure rows the proxy writes for timeouts and client disconnects. The proxy now dropsbase_modelfrom the request like the other pricing fields unless the key or team hasallow_client_pricing_override. A multipart request whosemetadataform field carries a lone surrogate escape ("\ud800") now gets the same 400 the JSON body path already returns, instead of a value that lost its spend-log row, tag spend and daily tag rollup. The spend-log writer also treats a PrismaUnicodeEncodeErroras a poison row it drops and logs, never a transient error to retry and requeueDetails
TLDR
Problem this solves:
base_modelpriced the caller's own spend rows at a cheaper modelmetadataadmitted"\ud800", losing that request's spend row and tag spendHow it solves it:
base_modeljoins the client pricing fields stripped at the request boundarymetadatais checked for lone surrogates and rejected with 400UnicodeEncodeErrorUser Flow
Before: a developer on a key priced for gpt-4o pays gpt-4o-mini rates by adding one field
"model": "gpt-4o", "base_model": "gpt-4o-mini"After: the same request is billed at the model that served it
"base_model": "gpt-4o-mini"in the bodyallow_client_pricing_override: truein its metadata keeps the fieldAffected release
The billed failure row part is a regression since #47437. The success row part dates back to #7263
Pre-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 moreScreenshots / Proof of Fix
Setup for both runs: proxy started from this checkout with
python litellm/proxy/proxy_cli.py --config config.yaml --port 4010 --detailed_debug,SPEND_LOG_QUEUE_POLL_INTERVAL=1, local Postgres 16 asdatabase_url, real OpenAIgpt-4o,gpt-4o-miniandwhisper-1deployments, master key as$K. Rows read withpsql "$DATABASE_URL" -c 'select request_id, spend, prompt_tokens, completion_tokens, request_tags from "LiteLLM_SpendLogs" order by "startTime"'Before (6e385f2)
Body base_model lowers a success row
curl localhost:4010/v1/chat/completions -H "Authorization: Bearer $K" -d '{"model":"gpt-4o","messages":[{"role":"user","content":"Say exactly: base_model_absent"}],"max_tokens":8}'then the same with"base_model":"gpt-4o-mini"addedchatcmpl-EbAwCIJK... | 7.500000000000001e-05 | 14 | 4(no base_model, gpt-4o rates) andchatcmpl-EbAwDfGP... | 7.499999999999999e-06 | 18 | 8(base_model set, 18 x 1.5e-7 + 8 x 6e-7, the gpt-4o-mini rates)Body base_model lowers a client disconnect row
curl -m 1 localhost:4010/v1/chat/completions -H "Authorization: Bearer $K" -d '{"model":"gpt-4o","messages":[{"role":"user","content":"Write 400 words about rivers"}],"stream":true,"max_tokens":600,"base_model":"gpt-4o-mini"}'(curl hangs up after 1s)chatcmpl-EbAwEIOA... | 1.95e-06 | 13 | 0, which is 13 x 1.5e-7, the gpt-4o-mini input rateLone surrogate in multipart metadata
curl localhost:4010/v1/audio/transcriptions -H "Authorization: Bearer $K" -F model=whisper-1 -F file=@tone.wav -F 'metadata={"tags":["poison-\ud800-tag"]}'Spend tracking - dropping spend log row Postgres rejected. request_id=1ebd92bb-... error=Unable to match input value to any allowed input type for the field,UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800'from the Tag spend update, andInvalid JSON: unexpected end of hex escapefrom the daily tag rollupLiteLLM_SpendLogs. The next chat request's row was written, so the writer did not stall on main, this request's spend was simply lostAfter (12fdb94)
Body base_model lowers a success row
"base_model":"gpt-4o-mini"chatcmpl-EbBHY4Ws... | 7.500000000000001e-05 | 14 | 4, which is 14 x 2.5e-6 + 4 x 1e-5, the gpt-4o ratesBody base_model lowers a client disconnect row
curl -m 1streaming request with"base_model":"gpt-4o-mini"chatcmpl-EbBHZWMx... | 3.25e-05 | 13 | 0, which is 13 x 2.5e-6, the gpt-4o input rateLone surrogate in multipart metadata
-F 'metadata={"tags":["poison-\ud800-tag"]}'transcription request{"error":{"message":"Invalid form payload: metadata 'utf-8' codec can't encode character '\\ud800' in position 18: surrogates not allowed","type":"invalid_request_error","param":"metadata","code":"400"}} HTTP 400-F 'metadata={"tags":["caf\u00e9-\ud83d\ude00"]}'returns 200 and its row showsrequest_tags = ["café-😀", ...], so valid non-ASCII and surrogate pairs still passType
🐛 Bug Fix
Caveats (if any)
Low
UnicodeEncodeErrorbranch has no live repro on main: every request field is escaped bysafe_dumpsbefore it reaches the row, so only the unit test exercises itmetadatawith a lone surrogate was a 200 that lost its spend row, it is now a 400Final Attestation
Link to Devin session: https://app.devin.ai/sessions/8dabd40db4c548c9b0ef6ac556657051
Open in Devin Desktop: https://app.devin.ai/desktop/session/8dabd40db4c548c9b0ef6ac556657051?variant=devin
Requested by: @kerrylu-berri
Note
Medium Risk
Changes request sanitization and spend-log persistence for pricing abuse and encoding edge cases; behavior shifts from silent spend loss to 400 for bad multipart metadata.
Overview
Closes a spend-pricing bypass where clients could send
base_modelin the request body to have their usage logged at a cheaper model’s rates (including billed failure rows).base_modelis now stripped with the other client pricing fields unlessallow_client_pricing_overrideis set.Multipart form
metadata(e.g. audio transcriptions) is validated the same way as JSON bodies: lone surrogate escapes like"\ud800"return 400 withparam=metadatainstead of succeeding and later breaking spend logs, tag spend, and rollups.The spend-log
create_manypoison-row path also treatsUnicodeEncodeErroras a permanent bad row to drop and log, so one unencodable row cannot block the rest of the batch or spin on retries.Reviewed by Cursor Bugbot for commit bd402ba. Bugbot is set up for automated code reviews on this repo. Configure here.