Repository navigation
feat(proxy): map baggage values to budget tags - #47358
Conversation
…hem out of tag routing Mapped tags now apply only to billed LLM API routes, skipping token counting, model listing, MCP and A2A. They classify spend and budgets but never select deployments unless a key, team or client set the same tag. WebSocket inference returns 403 only while a required rule exists. A tag created with /tag/new resets its spend counter so its budget counts from creation. The General settings editor keeps a new mapping unsaved until every required field is filled in.
… calls, skip request previews
# Conflicts: # litellm/proxy/litellm_pre_call_utils.py
… tag lookup errors, map custom pass-through routes, check the key before the WebSocket 403
…olicy and guardrail matching, honor allow_requests_on_db_unavailable, reject control characters in baggage values
Adds integration cells for request_tag_mappings across chat, messages, responses, A2A and custom pass-through spend, required and budgeted rules, the WebSocket refusal, unbilled routes, reject_clientside_metadata_tags, tag routing and policy isolation, a dropped tag read with and without allow_requests_on_db_unavailable, and the /tag/new spend counter reset
…t JSON-string metadata tags, count litellm_metadata caller tags Requests with no mapped baggage now reuse the cached body exactly as before, so header and key tag merges still normalize metadata for routing. The client body copy is made only when a tag maps, and the base merges are mirrored onto it. A request that maps nothing no longer gets a 400 for non-object metadata. caller_tags now counts tags sent in both metadata and litellm_metadata. Optional mappings no longer reject JSON-string metadata tags under reject_clientside_metadata_tags.
# Conflicts: # litellm/constants.py
…outing strategies Auto, complexity, adaptive and quality router selection, the consumed-tags stamp and compression policy lookup now read request tags without baggage-mapped tags, unless the caller sent the tag or the key, team or project carries it, matching deployment tag filtering.
…appings_mat1059 # Conflicts: # litellm/proxy/proxy_server.py # tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Cursor Bugbot: Low Risk at Pushes do not re-run this check. Comment |
|
bugbot run |
Merging this PR will not alter performance
|
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 96b971b
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 4 · PR risk: 0/10 |
|
@litereview code-review |
|
bugbot run |
…client tags as sent under mapped baggage Merge serving deployment tags into the request tags in one pass, so a large client tag list no longer blocks the event loop. Leave a non-list metadata.tags untouched when baggage maps a tag, so the request gets the same answer as without baggage. Add the C17 integration cell for the team tag's guardrail mode under a mapped deployment tag.
|
bugbot run |
|
@litereview code-review |
… or holds non-strings Mapped baggage tags are applied again after the header and key tag merges, so a header or key tag that replaces a string metadata.tags no longer hides the mapped tag from the tag budget check. An empty or false metadata.tags is read like a missing one, and a tags list with non-string items is kept as sent with the mapped tags added after it, instead of failing auth with a 401
# Conflicts: # litellm/proxy/litellm_pre_call_utils.py
|
@litereview code-review |
|
bugbot run |
| if _has_required_baggage_tag_mapping(): | ||
| raise HTTPException( | ||
| 403, "Required baggage tag mappings need HTTP inference, WebSocket inference is disabled" | ||
| ) |
There was a problem hiding this comment.
WebSocket refusal leaks auth reservations
Medium Severity
The required-mapping WebSocket denial runs only after user_api_key_auth finishes, so budget reservations and admission counters minted for that handshake are never released by a later spend callback. Valid-key realtime, Responses, and Live upgrades then leave those holds in place until TTL expiry.
Reviewed by Cursor Bugbot for commit 7907353. Configure here.
There was a problem hiding this comment.
Not a leak. Auth stamps the reservation on the shared socket state, and BudgetReservationReleaseMiddleware releases it when the denied socket closes
|
bugbot run |
|
@litereview guide |
|
# Conflicts: # tests/unit/router_strategy/test_router_tag_routing.py
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit b13e844. Configure here.
|
@litereview guide |
|
The post-merge audit of this change is in #48784. Every behavior it checked holds at the merge commit, and it adds two integration tests |
* test(proxy): audit #47358 Add integration cells for pass-through bodies and settings-endpoint mappings across workers * test(proxy): wait for every worker to hold the saved mapping before probing * test(proxy): compare passthrough bodies to the client body and probe each worker on its own connection --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>


Callers that send a W3C
baggageheader can now drive tag spend and budgets. A rule ingeneral_settings.request_tag_mappingsmaps a baggage key to a tag, by exact value or by any value under a prefix, and the proxy adds that tag to the request. Spend then tracks against the tag, budgeted or not, and an exhausted tag budget gets rejected before the provider callThis gives each entrypoint its own tag without every client setting tags by hand. Mapped tags never drive routing, policies or guardrails, since baggage comes from the client. Nothing changes until a mapping is configured, except that POST /tag/new now resets the tag spend counters, so a new budget skips earlier spend
/stupid
Original
TLDR
Problem this solves:
baggagevalues cannot select native tag budgetsHow it solves it:
baggagekey to tags by exact value or any-value prefix, and exact winsNothing changes until
request_tag_mappingsis configured, and the Severe caveats list whatrequiredandrequire_budgeted_tagthen reject. POST /tag/new now resets every tag's spend counter, with or without mappings, so a new budget skips the spend the proxy wrote before it existedDesign decisions and their alternatives
Mapped tags never select deployments under
enable_tag_filtering, an auto, complexity, adaptive or quality router strategy, a compression policy, tag-scoped policy attachments or tag-mode guardrails unless the caller also sent the tag or the key, team or project carries it, since baggage comes from the client and could otherwise steer routing, add or remove guardrails, or turn working requests into 401s. A per-rule opt-in was the alternative, left out until someone asksWith
require_budgeted_tag, a failed tag budget read answers 503 instead of skipping the check. Withallow_requests_on_db_unavailableon, the call goes through on the real key with the mapped tag unchecked, as other tag budget checks do during an outage, rather than taking the fallback identity that drops the key's own limitsA
tag_prefixrule lets the caller choose the tag under that prefix, as the feature asks.reject_clientside_metadata_tagsdoes not cover mapped tags because the admin configured them, and its error now says so. Client tags in the body or thex-litellm-tagsheader get the same answer with or without a mapped value. Refusing mappings while that flag is on, or accepting only existing tags, were the alternatives. Exact rules orrequire_budgeted_taglimit callers to known tagsA budget created with POST /tag/new counts spend from creation, so the counter resets and agrees with the new row across restarts. Seeding the row from the counter was the alternative, which would charge older spend to the new budget
A
requiredrule turns off WebSocket inference, because those connections cannot carry the tag to their spend rows. Mapping the handshake through seven WebSocket endpoints that each rebuild their request was the alternativeMappings cover every LLM API and registered pass-through POST route and skip a short list of free ones, so a
requiredrule also applies to POSTs that may cost nothing, like file uploads. An allowlist of billed routes was the alternative, which would let a newly added billed route skiprequiredwithout anyone noticing. MCP is not mapped yet, since several MCP auth paths skip the mapper and its cost rows come from rebuilt requests. Token counting, model listing and request previews cost nothing, so they are skipped. Mapped tags stay out ofrequester_metadata, so logging integrations still see only what the client sent. The OpenTelemetry propagator reads a bare+as a space, so a rule key with a+matches a baggage key sent with either+or%2B, and a request that sends both spellings maps nothing for that key. A value with a control character, like%00, maps no tag, and the duplicate-key check counts percent-decoded keysWhen a tag maps, auth works on its own copy of the request body, and the cached body stays the client's, with the base header and key tag merges applied to it too, so pass-through forwards the client's body without mapped tags. A request that maps nothing keeps the cached body exactly as before. Normalizing metadata when the body is parsed was the alternative, which would change requests that send no baggage
Mapped tags are added after the key, team, deployment and caller tags, so a tag-mode guardrail picks the same tag with or without baggage, and spend logs list mapped tags last. Adding them when auth resolves the mapping was the alternative, which let a mapped tag win over a key or deployment tag
An invalid
request_tag_mappingsvalue written straight to the DB is ignored with an ERROR log, like an invaliduser_api_key_cache_max_size, so requests are served as if it were unset until a valid value loads. Failing every mapped request was the alternative, which would block all inference over a value the settings endpoints already rejectUser Flow
Before: an application's propagated entrypoint does not select its use-case budget
baggage: entrypoint=asucceeds, but its spend log has no mapped tagAfter: the same propagated value selects its configured tag and budget
Relevant issues
Replaces #46699
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 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
Last updated:
b13e844b89. QA and /live-pr-risk ran on7907353429, the last commit with a product diffAfter ran at
7907353429and Before on #46699, each on paired 2-worker proxies with real providers, through curl, the MCP SDK, WebSocket and the Admin UI. Output is below or in the gist9f115be88d8dd60b2937litellm_metadatatag plus baggageBefore
9f115be88dAdmin UI
JSON-string metadata tags with x-litellm-tags, no rule
Rig: leg=u6base commit=9f115be88d instance A=http://127.0.0.1:24755 instance B=http://127.0.0.1:24199, 2 workers each, one Postgres (qa_u6base) and one Redis. Model group router-chat has two deployments, usecase-a-gpt-4o (OpenAI gpt-4o, tags [usecase:a]) and default-claude-haiku (Anthropic, tags [default]), enable_tag_filtering: true. No request_tag_mappings
Controls for the last group
Every control for the last table group (no rule, the optional rule config, which this base ignores, and the reject flag) ran at this base in this round, through the same rigs and steps as the other two legs. Commands and raw output are in the gist, whole
Every other case
Every case in the first table rows ran at this base in earlier rounds with the same clients, steps and setup, so it stands. Commands and raw output are in the gist
The Before legs at
eec15b37fdand8dd60b2937are in the gistAfter
7907353429JSON-string metadata tags with x-litellm-tags, no rule
Rig: leg=u6tip26 commit=7907353429 instance A=http://127.0.0.1:45345 instance B=http://127.0.0.1:52655, 2 workers each, one Postgres (u6tip26_head) and one Redis. Model group router-chat has two deployments, usecase-a-gpt-4o (OpenAI gpt-4o, tags [usecase:a]) and default-claude-haiku (Anthropic, tags [default]), enable_tag_filtering: true. No request_tag_mappings
JSON-string tags with mapped baggage, and string or list metadata, optional rule
Rig: leg=r6tip26 commit=7907353429 instance A=http://127.0.0.1:59993 instance B=http://127.0.0.1:43823, 2 workers each, one Postgres (r6tip26_head) and one Redis. Model group router-chat has two deployments, usecase-a-gpt-4o (OpenAI gpt-4o, tags [usecase:a]) and default-claude-haiku (Anthropic, tags [default]), enable_tag_filtering: true. One optional rule maps baggage entrypoint to usecase:
litellm_metadata tags plus baggage on Chat Completions, Responses and Messages
Rig: leg=r6tip26 commit=7907353429 instance A=http://127.0.0.1:59993 instance B=http://127.0.0.1:43823, 2 workers each, one Postgres (r6tip26_head) and one Redis. Model group router-chat has two deployments, usecase-a-gpt-4o (OpenAI gpt-4o, tags [usecase:a]) and default-claude-haiku (Anthropic, tags [default]), enable_tag_filtering: true. One optional rule maps baggage entrypoint to usecase:
Client tags rejected, one optional rule
Rig: leg=j6tip26 commit=7907353429 instance A=http://127.0.0.1:55403 instance B=http://127.0.0.1:43329, 2 workers each, one Postgres (j6tip26_head) and one Redis. Model group router-chat has two deployments, usecase-a-gpt-4o (OpenAI gpt-4o, tags [usecase:a]) and default-claude-haiku (Anthropic, tags [default]), enable_tag_filtering: true, reject_clientside_metadata_tags: true. One optional rule maps baggage entrypoint to usecase:
Every case of these rigs, and the configs
The number 42 and no-baggage string cases (N2, N4), the /v1/messages cases (M1 to M3) and the configs are in the gist, whole
Admin UI
The browser driver output for each step is in the gist
Every other case
Every other case from the earlier rounds ran again at this tip, with the same clients and steps, and is in the gist, whole, because it passes the body size cap. The routing file has the complexity routers, tag routing, tag policy, control characters, client tags rejected with and without a rule and the outage flag. The core file has every surface, the spent budget across instances, spend logs, the late budget cases T1 to T9, WebSocket and no database. The Admin UI file has the rule cases, skipped routes, A2A, request previews and the settings read after a save. The new cases file has guardrail modes, plus-sign keys and string, empty, false and mixed
metadata.tagsnext to a spent mapped budget, on this tip and on main0675c22d56Each case matches the earlier After output, or differs in one of four ways. The deployment tag now comes before the mapped tag, with the same tags. Spend counters are double the spend rows, as on main since #47192. Spend still in the database write batch when POST /tag/new runs reaches the new budget (T3, T4, T7, T8), and a settings read right after a save mixes old and new values (Z2) until each worker's 30 s reload
Observations
eec15b37fd,%00logged tagusecase:, row kept. Fixed at tip8dd60b2937misrouted only Chat Completionslitellm_metadatatags. Fixed at tipAudit round 2, at a0da37a
Base
0675c22d56and heada0da37a085each ran on their own 2-worker proxy with their own Postgres, Redis and scripted upstream, in oneremote_rig.py round. The head runs used treeb0d4c12ba2, which is 98cc33e plus this round's C18 test, and the same tree asa0da37a085. Base ran once and head ran twice with seed 5113701 and order seed 5113702, in CircleCI's accounting group setup (2 workers, each owned proxy on its own private database). Every cell matches its spend rows, callback payloads, guardrail calls and upstream records by a per-request uuid marker. Base had 20 reds and 21 passes, all as expected, and both head runs collected and passed the same 41 cellstest_mapped_baggage_tags_reach_spend_and_callbacks_but_not_requester_metadata[chat]litellm_metadata...[chat_litellm_metadata]...[messages]...[responses]test_json_string_metadata_gains_exactly_the_mapped_tagstest_a2a_spend_row_carries_the_mapped_tagstest_spent_mapped_tag_budget_rejects_the_next_request_before_the_providertest_required_mapping_rejects_a_request_without_its_baggage_value_before_the_providertest_require_budgeted_tag_rejects_an_unbudgeted_mapped_tag_until_the_tag_has_a_budgettest_budgeted_mapping_on_a_failed_tag_read[outage_flag_off]...[outage_flag_on]test_mapped_tags_never_select_a_tag_routed_deployment[baggage_only]...[caller_tag]...[metadata_json_tag_with_header]litellm_metadatatag routes...[litellm_metadata_tag]test_mapped_tags_never_trigger_a_tag_scoped_policy_attachmenttest_required_mapping_refuses_websocket_inference_before_the_upstreamtest_required_mapping_skips_unbilled_routes[token_counter]...[messages_count_tokens]test_custom_passthrough_spend_row_carries_the_mapped_tagstest_reject_clientside_metadata_tags_with_baggage[baggage_only]...[header_tag]...[body_tag]...[metadata_json_tag]...[metadata_json_tag_unmapped_baggage]litellm_metadatatag allowed...[litellm_metadata_tag]test_tag_budget_enforcement.py::test_tag_new_counts_spend_from_creation_not_before+key, plus on wiretest_plus_sign_rule_key_matches_either_wire_spelling_but_not_both[plus]+key,%2Bon wire...[percent_encoded]+key, both spellings...[both_spellings]test_serving_deployment_tag_selects_its_guardrail_mode_when_baggage_maps_the_same_tag[tagged_deployment]...[untagged_deployment]test_malformed_metadata_keeps_its_status_under_baggage[unmapped_baggage-non_object]...[header_tag_unmapped_baggage-non_object]...[mapped_baggage-non_object]...[header_tag_mapped_baggage-non_object]test_baggage_mapping_a_deployment_tag_keeps_the_team_tag_guardrail_mode_firstmetadata.tags, unmappedtest_malformed_metadata_keeps_its_status_under_baggage[unmapped_baggage-string_tags]...[header_tag_unmapped_baggage-string_tags]metadata.tags, mapped...[mapped_baggage-string_tags]...[header_tag_mapped_baggage-string_tags]The cells are in
tests/integration/spend/test_baggage_tag_mappings.pyunless the row names another file. This round found three behavior changes, and each one has its fix commit in the table. At f734e9e, a chat body withmetadata: "run-123"got 400 "Invalid type for 'metadata'" and no provider call with baggage that mapped a tag, while the same body without baggage (and base) got 200. Baggage that mapped the serving deployment's tag also put it ahead of a team tag, so the deployment tag's guardrail mode won and the team's post_call guardrail did not run (C17 red at f734e9e with no guardrail call, base pass). At 5281d71, a body withmetadata: {"tags": "run-123"}got 400 "'str' object has no attribute 'copy'" without baggage and 200 with mapped baggage, since the string tag was dropped (C18 red at 5281d71 on the no-header mapped cell only). 98cc33e leaves a non-listmetadata.tagsas sent, so both requests now get the same 400 as baseThe controls ran once on head. 45 of 51 passed, covering the tag budget, rpm, tpm, update, delete and info cells in
spend/test_tag_budget_enforcement.py, the tag cells inspend/test_passthrough_request_tags.py, the count_tokens cells inspend/test_cache_and_quota.py,routing/test_team_tag_routing.py, the tag-scope cells ofmanagement/test_policy_attachment_runtime.py, and the JSON-string and form metadata cells of the chat, text completion and audio transcription wire tests. 5 skip themselves on bug markers already on main. The one red control,test_repeated_count_tokens_on_budgeted_key_does_not_reserve_budget_or_block_later_completion(0.12 against 0.06), is inherited. Main's CircleCI has it red with the same figures at the merge base and on every run since #47192, apart from one green run, so it is a Low caveat. The 11 mapped unit files passed at 98cc33e, 3855 tests, including the invalid DBrequest_tag_mappingsreload and the one-pass deployment tag merge.test_router.pyran on Python 3.12, because 4 of its auto-router tests needsemantic-router, which does not install on 3.14. There are no live rows because a header-to-tag mapping inside the proxy has no vendor contract to check. JSON-stringmetadatawithout anx-litellm-tagsheader loses its own tags on base and head alike, so those cells compare against the same body sent without baggage instead of pinning that existing bugRound 2 passed with its tests in
a0da37a085.Type
🆕 New Feature
Caveats (if any)
Severe
requiredrule returns 403 on every WebSocket inference route, for every valid keyrequiredrulerequiredrule returns 400 on every LLM API POST without baggage, file uploads and the Admin UI playground includedreject_clientside_metadata_tags, so the caller picks the budgettag_prefixrule reaches every tag under the prefixrequire_budgeted_taganswers 503 when tag budgets cannot be read andallow_requests_on_db_unavailableis off, while other tag budget checks fail openLow
/queue/chat/completions, MCP, batch and background/v1/responsesspend carry no mapped tag, all but MCP gaps older than this PRrequiredrule turns an unknown agent's 404 into 400acompletion, like other auth failures there on mainrequire_budgeted_tag, atag_prefixrule accepts unlimited new tags, and an outage withallow_requests_on_db_unavailablepasses unbudgeted mapped tags+reads as a spacereject_clientside_metadata_tags, the 400 for falsy client tags plus baggage logs the mapped tag at 0 spendcaller_tagsnow also lists bodymetadata.tags, which can hold key tags, but only the mapping filter reads itrequest_tag_mappingsvalue log at ERROR, the latter on every reload, and other workers keep old mappings until a reloadopentelemetry-api, which Docker shipsFinal Attestation
Bugbot summary