Skip to content

fix(proxy): strip caller base_model from spend pricing and reject lone surrogates in multipart metadata - #47639

Merged
klu-berri merged 2 commits into
mainfrom
litellm_spend_row_base_model_and_encode_poison
Oct 20, 2026
Merged

klu-berri merged 2 commits into
mainfrom
litellm_spend_row_base_model_and_encode_poison

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

A caller could put base_model in 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 drops base_model from the request like the other pricing fields unless the key or team has allow_client_pricing_override. A multipart request whose metadata form 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 Prisma UnicodeEncodeError as a poison row it drops and logs, never a transient error to retry and requeue

Details

TLDR

Problem this solves:

  • Body base_model priced the caller's own spend rows at a cheaper model
  • Multipart metadata admitted "\ud800", losing that request's spend row and tag spend
  • A row the Prisma engine cannot encode counted as transient and would requeue forever

How it solves it:

  • base_model joins the client pricing fields stripped at the request boundary
  • Multipart metadata is checked for lone surrogates and rejected with 400
  • Spend-log poison isolation also drops rows that raise UnicodeEncodeError

User Flow

Before: a developer on a key priced for gpt-4o pays gpt-4o-mini rates by adding one field

  1. They send POST http://localhost:4000/v1/chat/completions with "model": "gpt-4o", "base_model": "gpt-4o-mini"
  2. The response is a normal gpt-4o completion with 18 prompt and 8 completion tokens
  3. http://localhost:4000/ui/?page=logs shows the request at $0.0000075, the gpt-4o-mini price, instead of $0.000075
  4. Another user on the same team sees the team budget drained more slowly than the real provider bill

After: the same request is billed at the model that served it

  1. They send the same POST with "base_model": "gpt-4o-mini" in the body
  2. The response is the same gpt-4o completion
  3. http://localhost:4000/ui/?page=logs shows the request at the gpt-4o price for those tokens
  4. Nobody can lower their recorded spend from the request body. A key or team with allow_client_pricing_override: true in its metadata keeps the field

Affected 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • 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 before requesting a maintainer review

Screenshots / 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 as database_url, real OpenAI gpt-4o, gpt-4o-mini and whisper-1 deployments, master key as $K. Rows read with psql "$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

  1. 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" added
  2. Rows: chatcmpl-EbAwCIJK... | 7.500000000000001e-05 | 14 | 4 (no base_model, gpt-4o rates) and chatcmpl-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

  1. 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)
  2. Row: chatcmpl-EbAwEIOA... | 1.95e-06 | 13 | 0, which is 13 x 1.5e-7, the gpt-4o-mini input rate

Lone surrogate in multipart metadata

  1. curl localhost:4010/v1/audio/transcriptions -H "Authorization: Bearer $K" -F model=whisper-1 -F file=@tone.wav -F 'metadata={"tags":["poison-\ud800-tag"]}'
  2. 200 with the transcription, then in the proxy log 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, and Invalid JSON: unexpected end of hex escape from the daily tag rollup
  3. No row for that request in LiteLLM_SpendLogs. The next chat request's row was written, so the writer did not stall on main, this request's spend was simply lost

After (12fdb94)

Body base_model lowers a success row

  1. Same gpt-4o request with "base_model":"gpt-4o-mini"
  2. Row: chatcmpl-EbBHY4Ws... | 7.500000000000001e-05 | 14 | 4, which is 14 x 2.5e-6 + 4 x 1e-5, the gpt-4o rates

Body base_model lowers a client disconnect row

  1. Same curl -m 1 streaming request with "base_model":"gpt-4o-mini"
  2. Row: chatcmpl-EbBHZWMx... | 3.25e-05 | 13 | 0, which is 13 x 2.5e-6, the gpt-4o input rate

Lone surrogate in multipart metadata

  1. Same -F 'metadata={"tags":["poison-\ud800-tag"]}' transcription request
  2. {"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
  3. Control: -F 'metadata={"tags":["caf\u00e9-\ud83d\ude00"]}' returns 200 and its row shows request_tags = ["café-😀", ...], so valid non-ASCII and surrogate pairs still pass

Type

🐛 Bug Fix

Caveats (if any)

Low

  • The writer UnicodeEncodeError branch has no live repro on main: every request field is escaped by safe_dumps before it reaches the row, so only the unit test exercises it
  • A multipart metadata with a lone surrogate was a 200 that lost its spend row, it is now a 400

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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_model in the request body to have their usage logged at a cheaper model’s rates (including billed failure rows). base_model is now stripped with the other client pricing fields unless allow_client_pricing_override is set.

Multipart form metadata (e.g. audio transcriptions) is validated the same way as JSON bodies: lone surrogate escapes like "\ud800" return 400 with param=metadata instead of succeeding and later breaking spend logs, tag spend, and rollups.

The spend-log create_many poison-row path also treats UnicodeEncodeError as 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.

@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

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at bd402ba. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at bd402ba. 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. Bugbot run requested, finished in 6 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@codspeed

codspeed Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_spend_row_base_model_and_encode_poison (12fdb94) with main (1380e7e)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (5c341e7) during the generation of this report, so 1380e7e was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

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

@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 20, 2026
@codecov

codecov Bot commented Oct 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@klu-berri
klu-berri enabled auto-merge (squash) October 20, 2026 21:11
@klu-berri
klu-berri merged commit 2a26895 into main Oct 20, 2026
89 of 90 checks passed
@klu-berri
klu-berri deleted the litellm_spend_row_base_model_and_encode_poison branch October 20, 2026 21:14
@mateo-berri

Copy link
Copy Markdown
Contributor

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

devin-ai-integration Bot added a commit that referenced this pull request Oct 21, 2026
…e surrogates in multipart metadata (#47639)

Backport of #47639 to stable/1.103.x

Cherry-picked from 2a26895 (main)
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
…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)
yuneng-berri added a commit that referenced this pull request Oct 28, 2026
…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
yuneng-berri pushed a commit that referenced this pull request Oct 28, 2026
…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)
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
…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).
DeoLeung pushed a commit to aiyou178/litellm that referenced this pull request Nov 5, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants