Skip to content

fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI - #47037

Merged
yuneng-berri merged 15 commits into
mainfrom
litellm_circleci_heal_integration_tests
Oct 17, 2026
Merged

yuneng-berri merged 15 commits into
mainfrom
litellm_circleci_heal_integration_tests

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Calls bill $0 when the response names a model only a price-free capability rule matches. Bedrock Claude ids that a custom cost map prices only under their route name hit it most, and the OpenAI reasoning, Gemini chat and wandb rules do the same on Azure, Azure AI, OpenAI, Gemini, Vertex and Anthropic routes
  • A Bedrock application inference profile with a one-hour base_model sends a one-hour cache TTL, but the router pins the prefix for five minutes
  • Four integration jobs on main's CircleCI fail on test setup or stale expectations

How it solves it:

  • Cost lookup tries names with a real cost-map entry before names only a price-free rule matches, reading only the static cost map and rules. A rule carrying any price keeps its place, and explicit pricing skips the sort
  • The prompt caching pin decides one-hour support with the same bedrock_capability_model check the wire uses
  • The CircleCI context section lists each test fix

This 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

  1. A proxy admin adds bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0, and their cost map prices only that route name
  2. They send POST http://localhost:4000/v1/chat/completions (also /v1/messages and /v1/responses) and get a 200 with no x-litellm-response-cost header
  3. GET http://localhost:4000/spend/logs shows each request at spend 0.0
  4. They also run three Bedrock application inference profile deployments with a one-hour-capable base_model and send a prompt cached with ttl: "1h"
  5. A follow-up turn more than five minutes later comes back with a different x-litellm-model-id

After: the requests bill at the route's price, and the follow-up stays on its deployment

  1. A proxy admin adds the same deployment with the same cost map
  2. They send the same requests and each 200 carries x-litellm-response-cost at the route's rates
  3. GET http://localhost:4000/spend/logs shows each request at that cost
  4. They run the same three deployments and send the same one-hour cached prompt
  5. The follow-up more than five minutes later comes back with the first turn's x-litellm-model-id

CircleCI context

Failing jobs on main, their culprits, and #46763's branch pipelines

Red on main in the scheduled integration workflow of pipeline 91272 at 54ff82dd14, and also in pipeline 91270

integration-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] with x-litellm-response-cost None. Culprit is c3da442 (#46708), which made the scripted cost map serve the production claude-family-baseline capability rule. completion_cost tries 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 group

integration-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_one with ValueError: not enough values to unpack. The test came in with 622daf3 (#45197) and matched Postgres client_port against 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 strict

integration-accounting fails tests/integration/spend/test_daily_rollup_retry.py::test_failed_daily_user_rollup_commit_is_retried_so_spend_report_and_daily_activity_agree on main pipelines 91272 and 91275 with Left contains 1 more item: {'ptu_hours': 0.0}. Culprit is e344dbd (#43043), which intentionally added ptu_hours to daily activity SpendMetrics. The test's exact metrics dict now expects ptu_hours at 0.0 and stays otherwise strict

integration-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 with Owned proxy exited before readiness. The proxy log shows ImportError: Could not import authenticate from subscription_auth. With INTEGRATION_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 test

test_mcp_oauth_flows.py::test_per_server_resource_scopes_the_session_bearer_to_the_named_server and ::test_spec_client_discovers_the_aggregate_authorization_server_and_signs_in_to_a_session_bearer fail with an extra 'servers': None. Culprit is 1ddaa54 (#44957), which intentionally added servers to the connect-flow description. The expected dicts add it and stay exact

Greptile review on #46763 at e0fe962: a capability rule that carries prices keeps its place, and custom_pricing or base_model calls 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-replica and e2e_ui_testing passed on the first run. integration-mcp went from 53 failures on main to the one deferred test below. integration-sdk and integration-extensions failed one test each on the first run and passed on the rerun, test_sdk_native_messages_stream_delivers_one_success_callback_with_usage is also red on main 91294. Earlier #46763 pipelines were 91276, 91277, 91286, 91287, 91295 and 91296

integration-providers on main 91291, 91293 and 91294 failed to collect tests/integration/providers/test_bedrock_nova_sonic_realtime_tool_calls.py with ImportError: cannot import name '_free_port' from 'integration._support.process'. Main has since moved the peer to allocate_port and added the response.function_call_arguments.delta event #46214 emits to the expected tail, so this PR only adds a check that the delta carries the full arguments

The 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 follow base_model, so the wire carries ttl: "1h", but the pin from e136e91 (#46084) still checked the ARN and pinned for 300 seconds. _honors_one_hour_cache_ttl now resolves the capability model from the deployment model and base_model, and the case expects a one-hour pin and wire TTL

#46763 branch pipeline 91301 ran at c714d01. Its later commit 2643fff merges main with no conflicts and runs in #46763 branch pipeline 91309. There every claimed job passed, and the remaining reds are the deferred ones plus test_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 too

Deferred, each equally red on main

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

Before ran at the merge base 6d0d0bb68b and After at the tip 2223d8b93d, with the same config, .env, and cost map

Case Before After
chat cost header missing 3.551e-05
stream usage.cost null 3.551e-05
messages cost header missing 3.551e-05
responses cost header missing 3.551e-05
/spend/logs spend, 4 rows 0.0 0.00003551
1h pin, later turn 4 of 5 moved 5 of 5 held
base_model first turn 0.148313 0.14828

Shared setup

Each leg ran two workers on real Bedrock in us-east-1 with its own Postgres and Redis

Ports, cost map entry and config.yaml
  • Each leg ran litellm/proxy/proxy_cli.py --config config.yaml --num_workers 2 on a random free port (before 49486, after 50608), with its own Postgres database and its own Redis
  • Every call hit real AWS Bedrock in us-east-1
  • The stock cost map also prices claude-haiku-4-5 under its bare id, which hides the bug. So both legs read one self-hosted copy of the stock map through LITELLM_MODEL_COST_MAP_URL, with the 21 claude-haiku-4-5 keys removed and one route-priced entry added, the shape the integration-cost cases script
"bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0": {
  "litellm_provider": "bedrock", "mode": "chat",
  "input_cost_per_token": 1.19e-06, "output_cost_per_token": 5.01e-06
}
model_list:
  - model_name: haiku-route
    litellm_params:
      model: bedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0
      aws_region_name: us-east-1
  - model_name: opus-profile   # three of these, ids opus-profile-a, -b, -c
    litellm_params:
      model: bedrock/converse/arn:aws:bedrock:us-east-1:<account>:application-inference-profile/<profile>
      aws_region_name: us-east-1
    model_info:
      id: opus-profile-a
      base_model: bedrock/us.anthropic.claude-opus-4-7
router_settings:
  optional_pre_call_checks: ["prompt_caching"]
  redis_host: 127.0.0.1
  redis_port: os.environ/QA_REDIS_PORT
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

Expected cost is 13 * 1.19e-06 + 4 * 5.01e-06 = 3.551e-05

Before (6d0d0bb68b)

Chat completions on the route-priced model

curl -sS -D chat.h -o chat.json -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"haiku-route","messages":[{"role":"user","content":"Reply with the word OK."}],"max_tokens":16}' \
  http://127.0.0.1:49486/v1/chat/completions
grep -i 'HTTP/\|x-litellm-response-cost:\|x-litellm-call-id' chat.h
jq -c '{id, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}' chat.json
HTTP/1.1 200 OK
x-litellm-call-id: 8671eaa0-8d72-4197-8205-e80fb3f8a62c
{"id":"chatcmpl-ca81ac8d-8966-4af8-b5ea-7bccb5370f9d","usage":{"prompt_tokens":13,"completion_tokens":4}}

After (2223d8b93d)

Chat completions on the route-priced model

curl -sS -D chat.h -o chat.json -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"haiku-route","messages":[{"role":"user","content":"Reply with the word OK."}],"max_tokens":16}' \
  http://127.0.0.1:50608/v1/chat/completions
grep -i 'HTTP/\|x-litellm-response-cost:\|x-litellm-call-id' chat.h
jq -c '{id, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}' chat.json
HTTP/1.1 200 OK
x-litellm-call-id: 264f2620-1a64-44bf-be6b-a446ef73ea6b
x-litellm-response-cost: 3.5510000000000004e-05
{"id":"chatcmpl-293e5bd2-91a2-4916-b9c5-530898f9b231","usage":{"prompt_tokens":13,"completion_tokens":4}}

Other cases

/spend/logs for the four route-priced requests
curl -sS -H "Authorization: Bearer $LITELLM_MASTER_KEY" http://127.0.0.1:$PORT/spend/logs \
  | jq -c 'sort_by(.startTime) | .[] | select(.model_group == "haiku-route") | {request_id, call_type, prompt_tokens, completion_tokens, spend}'

Before (49486)

{"request_id":"chatcmpl-ca81ac8d-8966-4af8-b5ea-7bccb5370f9d","call_type":"acompletion","prompt_tokens":13,"completion_tokens":4,"spend":0.0}
{"request_id":"chatcmpl-a3302284-b633-40ed-b810-d6ddf89de114","call_type":"acompletion","prompt_tokens":13,"completion_tokens":4,"spend":0.0}
{"request_id":"msg_bdrk_o3elabcajnulvrfdg4by4qvvjmkwi4ryrq4yij5mi3qvbh6sbija","call_type":"anthropic_messages","prompt_tokens":13,"completion_tokens":4,"spend":0.0}
{"request_id":"chatcmpl-00c351d4-854f-4583-9e00-da80f011b5b7","call_type":"aresponses","prompt_tokens":13,"completion_tokens":4,"spend":0.0}

After (50608)

{"request_id":"chatcmpl-293e5bd2-91a2-4916-b9c5-530898f9b231","call_type":"acompletion","prompt_tokens":13,"completion_tokens":4,"spend":0.00003551}
{"request_id":"chatcmpl-f090a4ff-1e03-4214-95b9-bfe5e00fd35b","call_type":"acompletion","prompt_tokens":13,"completion_tokens":4,"spend":0.00003551}
{"request_id":"msg_bdrk_427ke6rh674w235krl47rtrpxr6oys22yfehwcoekntfrn6upcca","call_type":"anthropic_messages","prompt_tokens":13,"completion_tokens":4,"spend":0.00003551}
{"request_id":"chatcmpl-3a91456d-4f90-47e5-ad2d-399e676a67d4","call_type":"aresponses","prompt_tokens":13,"completion_tokens":4,"spend":0.00003551}
Streaming chat completions
curl -sS -N -D stream.h -o stream.sse -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"haiku-route","messages":[{"role":"user","content":"Reply with the word OK."}],"max_tokens":16,"stream":true,"stream_options":{"include_usage":true}}' \
  http://127.0.0.1:$PORT/v1/chat/completions
grep -i 'HTTP/\|x-litellm-call-id' stream.h
grep '"usage"' stream.sse | grep -v '"usage":null' | tail -1 | sed 's/^data: //' \
  | jq -c '{id, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens, cost: .usage.cost}}'

Before (49486)

HTTP/1.1 200 OK
x-litellm-call-id: 0bed44d6-b5c5-4f34-8744-b7a7d52e5258
{"id":"chatcmpl-a3302284-b633-40ed-b810-d6ddf89de114","usage":{"prompt_tokens":13,"completion_tokens":4,"cost":null}}

After (50608)

HTTP/1.1 200 OK
x-litellm-call-id: 564f2e4f-6ce6-4862-ad4b-c4c08f3d6465
{"id":"chatcmpl-f090a4ff-1e03-4214-95b9-bfe5e00fd35b","usage":{"prompt_tokens":13,"completion_tokens":4,"cost":0.000035510000000000004}}
/v1/messages
curl -sS -D messages.h -o messages.json -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' \
  -d '{"model":"haiku-route","messages":[{"role":"user","content":"Reply with the word OK."}],"max_tokens":16}' \
  http://127.0.0.1:$PORT/v1/messages
grep -i 'HTTP/\|x-litellm-response-cost:\|x-litellm-call-id' messages.h
jq -c '{id, usage: {input_tokens: .usage.input_tokens, output_tokens: .usage.output_tokens}}' messages.json

Before (49486)

HTTP/1.1 200 OK
x-litellm-call-id: dcf7ebb3-85f0-4b9e-bda3-2c1c5a1dc802
{"id":"msg_bdrk_o3elabcajnulvrfdg4by4qvvjmkwi4ryrq4yij5mi3qvbh6sbija","usage":{"input_tokens":13,"output_tokens":4}}

After (50608)

HTTP/1.1 200 OK
x-litellm-call-id: f8528903-6022-4bb0-a749-11e2d08f8489
x-litellm-response-cost: 3.5510000000000004e-05
{"id":"msg_bdrk_427ke6rh674w235krl47rtrpxr6oys22yfehwcoekntfrn6upcca","usage":{"input_tokens":13,"output_tokens":4}}
/v1/responses
curl -sS -D responses.h -o responses.json -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"haiku-route","input":"Reply with the word OK.","max_output_tokens":16}' \
  http://127.0.0.1:$PORT/v1/responses
grep -i 'HTTP/\|x-litellm-response-cost:\|x-litellm-call-id' responses.h
jq -c '{id, usage: {input_tokens: .usage.input_tokens, output_tokens: .usage.output_tokens}}' responses.json

Before (49486)

HTTP/1.1 200 OK
x-litellm-call-id: a432db3c-46ba-4398-9d28-c70ae8f36e65
{"id":"resp_Sqqsb7IqgDD-bIooGisU-UJ2ogNibuXjxXAYY21-82xbj3HxWAhEoBP3B6yd7bPU8e0HnC1Mnhvj_2GGxv6AEOf26786W-C3DjdS3ytnA0QAFBlajQB_-1qvFLwzLyb0V7U-1TMJQ-ypxz36fvTehjj9NZK1HseRPB2oT8fFImWGhPSQM7VdeyeSFq58TSHIjuqVBE914kxYC2yiOaHoVtet471olaJ_FdE1NuLBrjvD0e0ewRWGImnWQnxDszd2dpLzO_NmCesL1wEn0fllscDXXjlobdIj4XXoQpelnyj3uuU7-LfUH4SQAj3jVQPtYPZ40v10niCw52nZhaw9MYMteIiN53WPufASt-PgibkBAXVD8Gnf4Qf1fADl1uaGWyuJ_eAfb5d8AWqE-i3bsYyrUbXzPNc6MHM-2UKpGFTrXhZUM3Nv8iGboVgLdbF8PnqjV2-B","usage":{"input_tokens":13,"output_tokens":4}}

After (50608)

HTTP/1.1 200 OK
x-litellm-call-id: 05655a47-21ce-4f15-8f1e-c9a8c51c24ff
x-litellm-response-cost: 3.5510000000000004e-05
{"id":"resp_Qv6T_OzDa9UKHtM5MgG6BkMEEvLuxWoLOlXYPJJYumg4XO7MmJVn2KEST2PPKTDHmjNWlDbL9UbZxqImtXUm54v_qO7tbb2IrEQ9f3oJfYnpmw62qze7SvDGZcwmzi-lx0rs3geG7k9QHhx08gwFtYTX3GwPy077PcXOzzqiPGniE6TBWmPTKThFLFDNa-S4yvU60IEN2kJESFGRIq36r9bOGDyCrtD9ia3hNKFiXADUu286ND2IRJUXjFHABnX46CbfqYMqM0-iHV5prQNKQdpy77bLUXnM5WTj_3CbsscqPAe4K1bHnjBR68RttCxnkhx9sVgKFJKAJ5F1bgo8kqVw3Bfr4WF2shyXUTKfEdaD8qkQTk4KzhVvSHXHLRrk5sguyLRrUDMfx7HaRrMMqAEdfkLAQKXEp7qS3kegEGj789l-nTBbxar03yCixqxTopHRLeKn","usage":{"input_tokens":13,"output_tokens":4}}
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 to opus-profile, then the same five again 400 seconds later, past the old five-minute pin. Each request is

jq -n --rawfile sys long_system.txt --arg tag "$TAG-$i" --arg q "Reply with the word OK." \
  '{model: "opus-profile", max_tokens: 16, messages: [{role: "system", content: [{type: "text", text: ("Runbook " + $tag + ". " + $sys), cache_control: {type: "ephemeral", ttl: "1h"}}]}, {role: "user", content: $q}]}' > req.json
curl -sS -D resp.h -o resp.json -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  --data @req.json http://127.0.0.1:$PORT/v1/chat/completions

with the later turns asking Reply with the word OK again. Each line prints the status, the x-litellm-model-id header, and the usage cache fields

Before (49486), 4 of 5 later turns moved off their first deployment

prefix1-first 19:17:45 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":13459,"cached_tokens":0}
prefix2-first 19:17:46 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":13459,"cached_tokens":0}
prefix3-first 19:17:47 status=200 x-litellm-model-id=opus-profile-a {"cache_creation_input_tokens":13459,"cached_tokens":0}
prefix4-first 19:17:49 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":13459,"cached_tokens":0}
prefix5-first 19:17:50 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":13459,"cached_tokens":0}
waiting 400 seconds, past the five-minute pin
prefix1-later 19:24:32 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13459}
prefix2-later 19:24:33 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13459}
prefix3-later 19:24:34 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13459}
prefix4-later 19:24:35 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13459}
prefix5-later 19:24:37 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13459}

After (50608), 5 of 5 later turns stayed on their first deployment

prefix1-first 20:04:00 status=200 x-litellm-model-id=opus-profile-a {"cache_creation_input_tokens":13456,"cached_tokens":0}
prefix2-first 20:04:02 status=200 x-litellm-model-id=opus-profile-a {"cache_creation_input_tokens":13456,"cached_tokens":0}
prefix3-first 20:04:03 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":13456,"cached_tokens":0}
prefix4-first 20:04:05 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":13456,"cached_tokens":0}
prefix5-first 20:04:06 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":13456,"cached_tokens":0}
waiting 400 seconds, past the five-minute pin
prefix1-later 20:10:47 status=200 x-litellm-model-id=opus-profile-a {"cache_creation_input_tokens":0,"cached_tokens":13456}
prefix2-later 20:10:49 status=200 x-litellm-model-id=opus-profile-a {"cache_creation_input_tokens":0,"cached_tokens":13456}
prefix3-later 20:10:50 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":0,"cached_tokens":13456}
prefix4-later 20:10:51 status=200 x-litellm-model-id=opus-profile-b {"cache_creation_input_tokens":0,"cached_tokens":13456}
prefix5-later 20:10:52 status=200 x-litellm-model-id=opus-profile-c {"cache_creation_input_tokens":0,"cached_tokens":13456}
base_model pricing control

The first opus-profile turn above is priced through base_model on both legs, x-litellm-response-cost: 0.14831299999999997 before and 0.14828 after. Both are 18 input tokens at 5.5e-06, 6 output tokens at 2.75e-05, and the one-hour cache write at 1.1e-05 per token from the base_model entry, so the 0.000033 gap is the three fewer cache-write tokens the after leg's random prompt tag produced and base_model pricing is unchanged

Observations

  • Streaming responses carry no cost header on either leg
  • Moved turns still read the cache, the deployments share one ARN

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • A served model that only a price-free rule matches now bills at the deployment's rate on every provider instead of $0, as base already does for a served model no rule matches
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-1 and a Gemini one answering as zz-unknown-model-2, while rule-matched names such as gpt-9-2027-01-01 and gemini-9-pro bill 0.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 name

Keeping $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_model to price the served model

Low

  • /v1/messages on a Bedrock us. 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 separately
  • A name priced only by a live provider lookup and matched by a price-free rule sorts last. Reading that price would add a provider request per call, which costs more than this rare case
  • Cost lookup runs the rule matcher on up to three names, about 10 to 25 µs per call, too little to justify another product commit
  • The cost proof edits the cost map because the stock map prices no Bedrock id only by route name, which is inherent to the repro

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

mateo-berri and others added 4 commits October 16, 2026 18:24
…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>
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at 4cf96ce.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.00 (high at or above 0.75)

  • risk: low (probability of high 0.00)

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

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 17, 2026

@kerry-berri kerry-berri 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.

Low risk by rule and by judgement at 4cf96ce

mateo-berri and others added 8 commits October 16, 2026 18:47
…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>

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

@mateo-berri mateo-berri changed the title test(integration): fix SCIM, MCP, and daily rollup integration tests on CircleCI fix(cost): price exact cost-map names before capability-only Claude rules, and fix SCIM and MCP integration tests on CircleCI Oct 17, 2026
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 17, 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_circleci_heal_integration_tests (6314006) with main (d346d76)

Open in CodSpeed

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

⚠️ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/cost_calculator.py, litellm/utils.py, litellm/router_utils/pre_call_checks/prompt_caching_deployment_check.py and test files. None of them sit under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**. The Bedrock helpers bedrock_capability_model and bedrock_cache_point_ttl_supported are imported from litellm/llms/bedrock/common_utils.py, but that file is unchanged.

  • Passed · Compatibility requirements (required): No supported behavior breaks, so the title needs no ! marker.

  • Cost lookup: Unpriced capability-rule candidates now sort after exact or priced candidates, and only when custom_pricing/base_model are unset. Before, a route-priced Bedrock id billed 0.0. Now it bills at the route rate. A capability-only model with no exact entry still returns 0.0 (test_completion_cost_returns_zero_for_capability_only_generalization). Priced rules keep their position (test_completion_cost_keeps_priced_generalization_before_later_exact_candidate, plus the per-second variant). Explicit pricing keeps the original order.

  • Prompt-cache pin: For a Bedrock application inference profile ARN with a one-hour-capable base_model, the pin TTL goes from 300s to one hour. This matches the ttl: "1h" the wire already sends since fix(bedrock): use base_model for Claude capability checks on application inference profile ARNs #46569. A bare ARN without base_model keeps the five-minute pin (pin-bedrock-arn family stays one_hour=False).

  • Tests: The remaining changes touch only test files and harness code.

  • Passed · Changed behavior and result consistency (required): Standards read: root AGENTS.md, tests/AGENTS.md, tests/integration/AGENTS.md, tests/unit/AGENTS.md.

Cost path traced: completion_cost → raw_candidates → _priced_candidates_before_unpriced_rules → unmapped_model_generalization → _get_model_info_from_generalization, then the loop → cost_per_token and get_token_type_cost_breakdown with _pricing_provider_for_cost_candidate.

  • base_model_provider is non-None only when base_model is set. That also sets explicit_pricing, which skips the reorder. So the earlier idx == 0 provider binding is preserved by tying the provider to the candidate tuple.
  • When a candidate's provider equals the request provider, the helper falls back to the current custom_llm_provider, which may come from hidden params. This matches the old behavior.
  • The new pre-loop unmapped_model_generalization calls run outside the per-candidate try. I probed them with 15 providers (including None, empty and unknown) and 7 model shapes (empty, ARN, HF path, Claude id). None raised.

Pin path traced: async_log_success_event reads kwargs["litellm_params"]["base_model"], which get_litellm_params fills from model_info.base_model. It passes that to bedrock_capability_model and then bedrock_cache_point_ttl_supported, the same functions the converse transformation uses for the wire TTL.

Tests run: pytest tests/unit/test_cost_calculator.py tests/unit/router_utils/pre_call_checks/test_prompt_caching_deployment_check.py tests/unit/integration_support/test_process.py plus the two new/changed test_main.py stream-builder tests: 449 passed.

Defect-sensitive checks:

  • Removing the reorder makes test_completion_cost_prefers_exact_route_price_over_capability_generalization and test_completion_cost_prices_rule_only_response_model_at_the_azure_deployment_rate fail.
  • Removing the base_model resolution in the pin makes test_bedrock_application_profile_uses_its_base_model_for_one_hour_ttl fail.

Lint: ruff reports an unused OwnedProxy import and an import-order issue in test files. Both are under tests/*, which ruff.toml excludes from lint.

Other evidence: The PR body includes live proxy before/after curl evidence against real Bedrock.

  • Passed · Unit tests for changed modules (optional): .venv/bin/python -m pytest -n 8 over the three touched unit test files and the two stream-builder tests: 449 passed, 589 warnings in 32.06s.
  • Not run · Integration suites (CircleCI groups) (optional): Not run locally. These need the full proxy, Postgres, Redis and scripted-upstream harness. The PR cites branch pipelines 91297, 91301 and 91309, and the review relies on unit tests and code tracing instead.

View review · Reviewed 2223d8b93d4f

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge, with both previous findings addressed and no new actionable issue found

Summary

The PR puts priced model names ahead of price-free capability rules while preserving priced rules and explicit pricing

  • Bedrock calls use exact route prices when capability rules have no rates.
  • Bedrock profile pins last as long as their one-hour cache TTL.
  • Isolated test workers keep their sibling auth modules.
  • The SCIM push test kills workers after the database lock blocks a session.
  • Integration tests expect the fields and arguments their responses contain.

Reviews (2) · Last reviewed commit: "fix(cost): sort cost candidates from the..." · Reviewed by Greptile

Comment thread litellm/cost_calculator.py Resolved
Comment thread litellm/cost_calculator.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri mateo-berri changed the title fix(cost): price exact cost-map names before capability-only Claude rules, and fix SCIM and MCP integration tests on CircleCI fix(cost): price exact cost-map names before price-free capability rules, and fix SCIM and MCP integration tests on CircleCI Oct 17, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…es, and pin application profiles for an hour on messages and cache hits
@greptile-apps

greptile-apps Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

…_integration_tests

# Conflicts:
#	tests/integration/_support/process.py
@yuneng-berri
yuneng-berri enabled auto-merge (squash) October 17, 2026 06:37
@yuneng-berri
yuneng-berri merged commit 4a58784 into main Oct 17, 2026
93 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_circleci_heal_integration_tests branch October 17, 2026 06:46
yuneng-berri added a commit that referenced this pull request Oct 17, 2026
…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>
devin-ai-integration Bot added a commit that referenced this pull request Oct 17, 2026
Re-applies #47037's priced-candidates-before-unpriced-rules ordering and _pricing_provider_for_cost_candidate onto the refactored completion_cost loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants