Repository navigation
fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI - #47037
Conversation
…onfigs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…s on the row lock
|
bugbot run |
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.00 (high at or above 0.75)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 4cf96ce
…and keep the unpriceable case unmapped Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…candidate reordering Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…cing lookups Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…r ttl its base model sends Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ries the full arguments
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 4cf96ce. Configure here.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Merging this PR will not alter performance
|
|
@litereview code-review |
|
[High impact] The PR appears safe to merge, with both previous findings addressed and no new actionable issue found SummaryThe PR puts priced model names ahead of price-free capability rules while preserving priced rules and explicit pricing
Reviews (2) · Last reviewed commit: "fix(cost): sort cost candidates from the..." · Reviewed by Greptile |
…ithout provider lookups
|
@litereview code-review |
…es, and pin application profiles for an hour on messages and cache hits
|
Automatic reviews are disabled for this repository. |
…_integration_tests # Conflicts: # tests/integration/_support/process.py
…in (#47090) * fix(bedrock)!: block realtime replay after an input-first start and reject malformed Nova Sonic session settings (#46936) * fix(bedrock): block realtime replay after input starts the session and reject non-string instructions and voice * test(bedrock): name the malformed realtime setting test for its string cases * fix(bedrock): replay the opening realtime message until Bedrock accepts the stream and refuse any fallback after commit Also rejects a malformed modalities, input_sample_rate_hertz or tools setting with invalid_type, dropped under drop_params. * fix(bedrock): replay a refused opening message on any fallback and reject OpenAI voices and non-string audio formats * fix(realtime): read the client scope only when the websocket has one and reject any-case OpenAI and empty Bedrock voices * test(bedrock): cover realtime replay, refusal and committed failure through a real proxy Fix the scripted Bedrock peer's port import and the nested tool call cell's stale expected events, so the Nova Sonic integration file collects again (cherry picked from commit 3ef0b35) * test(integration): write worker configs beside test-supplied configs (#47066) Under worker isolation the harness rewrote every proxy config into the owned proxy's directory, so modules a test placed next to its own config (custom_auth) no longer resolved and the proxy died at boot. The copy now lands next to a test-supplied config, while configs inside the checkout still go to the worker directory so nothing is written into the repo tree (cherry picked from commit e754857) * test(e2e): keep the prompt-caching affinity test on the live provider (#47072) With E2E_PROVIDER_CACHE=1 the test's Anthropic deployment went through the shared response cache. Each call's recording expires on its own, so a run could replay the cache-writing call while a follow-up went live against a cold provider cache, recording creation instead of a read. That recording then replayed as a failure for 24 hours. Mark the test provider_live, as PROVIDER_CACHE.md requires for prompt-caching tests (cherry picked from commit 6b45a19) * test(integration): send post-kill requests on a fresh connection in two worker-kill tests (#47080) kill() returns once the killed worker's main thread is a zombie, but its other threads can still be exiting and holding its sockets open. A keep-alive connection pooled to that worker still looks healthy, so the next request goes out on it and the closing socket answers with a reset. The old reap wait used to hide this. A new connection can only be accepted by a live worker, so the surviving-worker assertions now run on a fresh client (cherry picked from commit c32eea6) * fix(caching): keep prompt cache usage on streamed cache hits (#47073) * fix(caching): keep prompt cache usage on streamed cache hits A stream=true request served from the response cache rebuilt its usage from the prompt, completion and total counts only, so prompt_tokens_details and the cache read and creation counts were dropped on the replayed stream. /v1/messages clients routed to Bedrock Converse saw input_tokens equal to the whole prompt and no cache tokens on a hit. Both replays now build the usage through one helper that also restores prompt_tokens_details and the integer cache read and creation counts, skipping cached values that do not validate. * fix(caching): coerce replayed token counts the way the live usage does The replay accepted only exact ints for the token counts, so an integral float or numeric string in a cached entry became 0 where the previous replay kept it. Counts now go through pydantic int coercion and fall back only when they do not validate. (cherry picked from commit d346d76) * fix(logging): keep the async request's logging payload when the sync success thread runs late (#47019) * fix(logging): keep the async request's logging payload when sync callbacks run late Treat the "cache" success callback as internal when deciding whether to start the sync success thread for async requests. It has no branch in the sync handler, so with `cache: true` that thread did nothing except rebuild and overwrite model_call_details["standard_logging_object"]. When the sync handler does run for an async request (a real sync-only logger is configured), it now builds its own payload and hands it only to its own callbacks. The async handler keeps sole ownership of the shared payload, so edits made by async logging hooks (for example the v3 rate limiter's mirrored x-ratelimit headers that Prometheus reads) are no longer discarded. Sync requests keep their existing behavior. * fix(logging): keep sync cache hits logged and isolate the async-request payload build The sync completion cache-hit path reused handle_sync_success_callbacks_for_async_calls, so treating "cache" as internal silently dropped sync callbacks on sync cache hits. It now submits the sync handler through its own method, as it effectively always did. For async requests the sync handler builds its payload from a copy of the call details, so message redaction cannot rewrite the shared standard_logging_object, and when it builds no payload its callbacks keep the shared one instead of getting None. * test(caching): lock sync cache-hit logging for completion, embedding and text_completion * test(logging): keep sync hook edits off a caller-supplied payload for async requests * fix(logging): give sync hooks a copy of the async payload when the thread builds none * test(logging): check every legacy sync logger gets the thread's own payload * test(logging): cover traceloop and supabase sync logging for async requests (cherry picked from commit a4e0570) * fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI (#47037) * fix(test-harness): preserve sibling auth modules in isolated worker configs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect servers in MCP connect-flow descriptions Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): expect ptu_hours in daily activity metrics after #43043 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): kill every serving worker once the SCIM push blocks on the row lock * fix(cost): price exact cost-map names before price-free capability rule matches * test(streaming): price a priced alias stream at its deployment model and keep the unpriceable case unmapped Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): price an explicit base_model under its own provider after candidate reordering Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(cost): retain priced generalized candidates and skip explicit-pricing lookups Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(cost): assert custom pricing makes no remote model-info requests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(cost): keep the per-candidate pricing provider final Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(router): pin a Bedrock application profile prompt for the one-hour ttl its base model sends Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(integration): assert the Nova Sonic tool-call argument delta carries the full arguments * fix(cost): sort cost candidates from the static cost map and rules, without provider lookups * test(integration): bill route-priced Bedrock chat streams and responses, and pin application profiles for an hour on messages and cache hits --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Yuneng Jiang <yuneng@berri.ai> (cherry picked from commit 4a58784) * test(e2e): warm the memory test up with two batches before the measured one (#47087) * test(e2e): warm the memory test up with two batches before the measured one On a cold worker the second batch of failing requests can still raise the allocator's high-water mark by about 50 MB while the live Python heap stays flat, so the 48 MB budget failed about 1 in 10 Buildkite runs without a leak. The test now runs two warmup batches, measures the third against the same budget, and records every batch's settled growth per worker as an rss_batch_growth JUnit property for later calibration * test(e2e): record each memory batch's growth as soon as it settles A failure in a later batch no longer drops the growth already measured, and the worker keys are no longer sorted, which raised on a mix of named and unnamed hosts * test(e2e): silence the xunit2 record_property warning on the memory test (cherry picked from commit 1fd7f81) * test: import pytest and Final for the backported #47073 test on rc On main these imports came from an earlier commit that is not on rc/1.107.0, so the picked test failed collection with NameError --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Re-applies #47037's priced-candidates-before-unpriced-rules ordering and _pricing_provider_for_cost_candidate onto the refactored completion_cost loop
TLDR
Problem this solves:
base_modelsends a one-hour cache TTL, but the router pins the prefix for five minutesHow it solves it:
bedrock_capability_modelcheck the wire usesThis PR replaces #46763, whose commits follow the first integration-test commit, plus review fixes
User Flow
Before: a Bedrock model priced only under its route name bills $0, and a one-hour cached prompt on an application inference profile loses its deployment after five minutes
bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0, and their cost map prices only that route namex-litellm-response-costheader0.0base_modeland send a prompt cached withttl: "1h"x-litellm-model-idAfter: the requests bill at the route's price, and the follow-up stays on its deployment
x-litellm-response-costat the route's ratesx-litellm-model-idCircleCI context
Failing jobs on main, their culprits, and #46763's branch pipelines
Red on
mainin the scheduled integration workflow of pipeline 91272 at54ff82dd14, and also in pipeline 91270integration-cost fails
tests/integration/cost_calculation/test_cost_tracking.py::test_case_bills_expected_cost[bedrock-converse-apac-bare-fallback]and[bedrock-invoke-haiku-json]withx-litellm-response-cost None. Culprit is c3da442 (#46708), which made the scripted cost map serve the productionclaude-family-baselinecapability rule.completion_costtries the response-derived name first, that name matches only the price-free rule, so it bills $0 and never tries the priced route name. The same shadowing happens in production for any route-priced Bedrock id whose bare id is unmapped. The fix orders cost candidates so exact cost-map names come before rule-only matches, keeping the existing order inside each groupintegration-management and integration-management-replica fail
tests/integration/management/test_scim_group_bulk_roster.py::test_a_worker_killed_mid_push_leaves_the_old_roster_and_a_retry_lands_the_new_onewithValueError: not enough values to unpack. The test came in with 622daf3 (#45197) and matched Postgresclient_portagainst host sockets of the workers. Postgres runs in Docker on CircleCI, so the port it sees is NAT'd and never belongs to a worker. The test now waits for a session blocked on the held row lock and kills every serving worker, so the one holding the push's transaction is always killed and every roster assertion stays as strictintegration-accounting fails
tests/integration/spend/test_daily_rollup_retry.py::test_failed_daily_user_rollup_commit_is_retried_so_spend_report_and_daily_activity_agreeon main pipelines 91272 and 91275 withLeft contains 1 more item: {'ptu_hours': 0.0}. Culprit is e344dbd (#43043), which intentionally addedptu_hoursto daily activity SpendMetrics. The test's exact metrics dict now expectsptu_hoursat 0.0 and stays otherwise strictintegration-mcp fails 53 tests on main 91293, 91291 and 91290. 50 of them, every
tests/integration/mcp/test_interactions.py::test_modern_subscription_delivers_changes_between_calls_and_refreshes_tools[*]and::test_continuation_reauthenticates_caller_and_rechecks_revoked_permissions[*], fail withOwned proxy exited before readiness. The proxy log showsImportError: Could not import authenticate from subscription_auth. WithINTEGRATION_WORKER_ISOLATION=1,worker_configuration(from 3090f4b, #45863) rewrites the config into a temp dir, but the custom auth module the test writes beside the config stays behind, and the loader only looks next to the config. The modern subscription cases came in with 4a4a0e8 (#46153). #47066 fixed the same thing on main by writing the isolated config next to a test-supplied config, so this PR now takes main's version and keeps only its regression testtest_mcp_oauth_flows.py::test_per_server_resource_scopes_the_session_bearer_to_the_named_serverand::test_spec_client_discovers_the_aggregate_authorization_server_and_signs_in_to_a_session_bearerfail with an extra'servers': None. Culprit is 1ddaa54 (#44957), which intentionally addedserversto the connect-flow description. The expected dicts add it and stay exactGreptile review on #46763 at e0fe962: a capability rule that carries prices keeps its place, and
custom_pricingorbase_modelcalls skip the sort and keep the original candidate order#46763 branch pipeline 91297 at its commit b2c054f (workflow, rerun of failed jobs).
integration-cost,integration-accounting,integration-management,integration-management-replicaande2e_ui_testingpassed on the first run.integration-mcpwent from 53 failures on main to the one deferred test below.integration-sdkandintegration-extensionsfailed one test each on the first run and passed on the rerun,test_sdk_native_messages_stream_delivers_one_success_callback_with_usageis also red on main 91294. Earlier #46763 pipelines were 91276, 91277, 91286, 91287, 91295 and 91296integration-providers on main 91291, 91293 and 91294 failed to collect
tests/integration/providers/test_bedrock_nova_sonic_realtime_tool_calls.pywithImportError: cannot import name '_free_port' from 'integration._support.process'. Main has since moved the peer toallocate_portand added theresponse.function_call_arguments.deltaevent #46214 emits to the expected tail, so this PR only adds a check that the delta carries the full argumentsThe same job fails
tests/integration/routing/test_prompt_cache_pin_ttl.py::test_provider_family_pin_lifetime_agrees_with_the_ttl_the_wire_carries[pin-bedrock-arn-base]on 5 of the last 6 main runs. 6c78089 (#46569) made Bedrock capability checks on application inference profile ARNs followbase_model, so the wire carriesttl: "1h", but the pin from e136e91 (#46084) still checked the ARN and pinned for 300 seconds._honors_one_hour_cache_ttlnow resolves the capability model from the deploymentmodelandbase_model, and the case expects a one-hour pin and wire TTL#46763 branch pipeline 91301 ran at c714d01. Its later commit 2643fff merges
mainwith no conflicts and runs in #46763 branch pipeline 91309. There every claimed job passed, and the remaining reds are the deferred ones plustest_bridged_request_bills_the_same_row_as_the_native_request[gpt-5.6-responses_reasoning-messages_bridged]in integration-cost, which also fails on main 3 of 3 when run alone because the messages bridge sometimes drops reasoning tokens from usage, so it is deferred tooDeferred, each equally red on
mainintegration-mcptest_mcp_rate_limits.py::test_shared_redis_enforces_paginated_tools_and_rest_listingsgets a rate-limit error on the continued page, red on main 91290 to 91294. Thenotifications/initializedlistener from 4a4a0e8 (feat(mcp): relay authorized modern upstream subscriptions #46153) spends the same server request budget astools/list, whether it should is a product callintegration-providerstest_responses_bridge_stream_errors.py::test_bridged_invalid_prompt_answers_a_bad_request_without_trying_the_fallback[nested|top_level]falls back on a 400 invalid prompt, the layer losing the 400 is not proven yet, leading suspect 83980c9 (fix(router): read the first stream chunk before returning so a failure before any token runs through the retry and fallback budget #46493)integration-providerstest_responses_bridge_tool_search_chaos.py::test_a_previous_response_id_turn_replays_the_function_call_without_the_search_callpins dropping the search call, while 9ba4cc4 (fix(anthropic): keep tool_search_tool_result so the search call replays with its result #46440) intentionally replays it with its result, a product call between the twointegration-extensionsfails a different chaos or OTel test on each runPre-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
Before ran at the merge base
6d0d0bb68band After at the tip2223d8b93d, with the same config,.env, and cost map3.551e-05usage.costnull3.551e-053.551e-053.551e-05/spend/logsspend, 4 rows0.00.00003551base_modelfirst turn0.1483130.14828Shared setup
Each leg ran two workers on real Bedrock in
us-east-1with its own Postgres and RedisPorts, cost map entry and config.yaml
litellm/proxy/proxy_cli.py --config config.yaml --num_workers 2on a random free port (before49486, after50608), with its own Postgres database and its own Redisus-east-1claude-haiku-4-5under its bare id, which hides the bug. So both legs read one self-hosted copy of the stock map throughLITELLM_MODEL_COST_MAP_URL, with the 21claude-haiku-4-5keys removed and one route-priced entry added, the shape theintegration-costcases scriptExpected cost is
13 * 1.19e-06 + 4 * 5.01e-06 = 3.551e-05Before (
6d0d0bb68b)Chat completions on the route-priced model
After (
2223d8b93d)Chat completions on the route-priced model
Other cases
/spend/logs for the four route-priced requests
Before (
49486)After (
50608)Streaming chat completions
Before (
49486)After (
50608)/v1/messages
Before (
49486)After (
50608)/v1/responses
Before (
49486)After (
50608)One-hour prompt cache pin on an application inference profile
Five distinct prompts, each a ~13.4k-token system block with
cache_control: {"type":"ephemeral","ttl":"1h"}, sent toopus-profile, then the same five again 400 seconds later, past the old five-minute pin. Each request iswith the later turns asking
Reply with the word OK again.Each line prints the status, thex-litellm-model-idheader, and the usage cache fieldsBefore (
49486), 4 of 5 later turns moved off their first deploymentAfter (
50608), 5 of 5 later turns stayed on their first deploymentbase_model pricing control
The first
opus-profileturn above is priced throughbase_modelon both legs,x-litellm-response-cost: 0.14831299999999997before and0.14828after. Both are 18 input tokens at5.5e-06, 6 output tokens at2.75e-05, and the one-hour cache write at1.1e-05per token from thebase_modelentry, so the0.000033gap is the three fewer cache-write tokens the after leg's random prompt tag produced andbase_modelpricing is unchangedObservations
Type
🐛 Bug Fix
✅ Test
Caveats (if any)
Medium
Why every provider, and the alternatives
On base a served model that matches no rule already bills at the deployment's rate, for example an Azure deployment answering as
zz-unknown-model-1and a Gemini one answering aszz-unknown-model-2, while rule-matched names such asgpt-9-2027-01-01andgemini-9-probill0.0. The OpenAI reasoning, Gemini chat and wandb rules came in between 2026-09-10 and 2026-09-15, first released in v1.102.0, so their $0 is recent behavior and this PR treats rule-matched names the way base treats every other unmapped nameKeeping $0 and flagging the spend row as unpriced was the first alternative. It keeps under-billing and leaves budgets blind to real spend. Sorting only on Bedrock was the second, and it leaves the same $0 on the Azure, OpenAI and Gemini routes. Both lose to one rule for every provider. An Azure deployment named for one model but serving another needs
base_modelto price the served modelLow
/v1/messageson a Bedrockus.regional profile bills the bare model rate on base and tip alike. Fixing it here would widen scope into the Messages cost path, so it is tracked separatelyFinal Attestation