litellm/tests
tin-berri 79d412efc2
fix: net prompt-caching savings against the cache-write premium (#36452)
* fix: net prompt-caching savings against the cache-write premium

Prompt-caching savings priced only the cache-read discount and ignored what
the provider charges to create the cache entry. Anthropic bills cache writes
at 1.25x the input rate, so a request that writes a large cache and reads
little from it is a net loss that the dashboard reported as a gain -- or, on
a pure cold write, as a flat zero.

The counterfactual the number answers is "what would this have cost with
caching off", where every token is billed at the input rate. Since
prompt_tokens partitions disjointly into text + reads + writes, that gives

    savings = reads * (input - read_rate) - writes * (write_rate - input)

The write term is the premium over the input rate, not the full write cost:
the tokens would have been paid for at the input rate anyway, so only the
markup is attributable to caching.

The premium stays signed rather than clamped. Three models in the pricing map
price writes below input, and clamping would silently drop that saving.
A model with no cache_creation_input_token_cost falls open to the input cost,
yielding a zero premium -- this is why the change is a no-op for the implicit
caching providers (OpenAI, Gemini), which publish no write price, and bites
exactly on Anthropic and Bedrock.

Verified live through the proxy on a mock Anthropic rig across four cases
(cold pure-write, warm pure-read, write-heavy, read-heavy). Reported total
matched the derived net to the cent, including the negatives; the read-only
case is unchanged.

Pre-existing rows are not backfilled, so a range spanning the deploy mixes
gross and net.

* fix: read a zero cache-write price as unpublished, not free

deepseek-chat carries a literal 0.0 cache_creation_input_token_cost. The
fall-open only caught None, so the zero was taken at face value and the
premium became 0 - input_cost -- reporting a fabricated saving of
writes * input_cost on traffic that cached nothing.

No provider gives cache writes away, so a falsy price means the same thing
an absent one does.

* test: pin that the read leg keeps a literal zero price

The two zero prices mean opposite things and the asymmetry was unpinned.
A free cache write is unpublished pricing; a free cache read is real, and
15 models charge for input while serving reads for nothing. Copying the
write leg's falsy fall-open onto the read leg would zero out their savings.

* refactor: resolve caching rates through the established pricing helpers

Addresses Greptile's P1 and P2, and replaces hand-rolled pricing lookup with
the patterns this file and the cost calculator already own:

- Deployment pricing first: rates now resolve through _effective_model_info
  (Router.get_deployment_model_info), the same helper the autorouter driver
  uses, falling back to _model_info public rates. A deployment with negotiated
  cache rates previously priced at the public map -- a 3x error on the repro.
- Individual prices read via _get_cost_per_unit, the cost calculator's
  accessor, which also coerces string prices from config.yaml and resolves
  service-tier suffixes; the previous raw .get() handled neither.
- Pricing tests no longer monkeypatch litellm.get_model_info; each case now
  pins a real pricing-map entry with a fixture-drift assertion, and the
  deployment-rate case follows the existing Router-fixture test pattern.

Behaviour on public rates is unchanged: 101 tests pass, including the exact
same live-verified formula.

* fix(cost-optimization): computeCacheLeakage divides net savings by all cached tokens, not reads alone

prompt_caching_savings_spend is net of the cache-write premium since PR #36452.
computeCacheLeakage was still dividing by cache_read_tokens alone, which:

1. Overstates the per-token rate on traffic that writes and reads cache equally:
   a 1:1 read:write key shows rate = 0.002, not 0.001, if net savings is /bin/zsh.002

2. Flips the sign on write-heavy traffic: when writes cost more than reads save
   (common on Anthropic and Bedrock), the aggregate net can go negative, but
   dividing by reads alone would show a positive 'potential savings' for keys
   that don't cache yet — recommending they start caching when it's currently
   losing money overall

Fix: divide realizedCachingSavings by (cacheReadTokens + cacheCreationTokens),
matching the semantic that a key starting to cache pays those write premiums too.

When the rate is non-positive, price nothing (potentialSavings stays null, renders
as '—'), reusing the existing no-data fallback path. The card can't meaningfully
estimate savings from a losing rate.

Rename discountPerToken → netSavingsPerCachedToken to surface the semantics and
prevent this drift in future.

Update Usage tab and Cache Leakage card tooltips to describe net-of-premium cost.

Add tests for 1:1 read:write traffic and write-heavy negative-net traffic.
2026-08-10 18:52:03 -07:00
..
agent_tests test: repair stale CircleCI contracts 2026-08-08 12:19:29 -07:00
audio_tests
base_sdk_tests fix(deps): move pydantic-settings into the base dependencies 2026-08-01 15:25:26 -07:00
basic_proxy_startup_tests
batches_tests test(batches): run Responses coverage in CI 2026-07-31 10:24:10 -04:00
benchmarks test(benchmarks): run shared logging executor inline to make CodSpeed measurements deterministic (#32435) 2026-07-09 11:14:22 +03:00
code_coverage_tests fix(ci): report budgets the startup guard cannot resolve 2026-08-10 18:12:18 +00:00
documentation_tests fix(ci): make the env-key doc gate see bare get_secret and get_secret_str reads (#35996) 2026-08-05 14:49:55 -07:00
e2e test(e2e): cover the Anthropic web_search server tool on Bedrock (#36443) 2026-08-10 17:38:08 -07:00
enterprise fix(proxy): report has_more false on caller-scoped file list pages 2026-08-08 17:28:43 -07:00
guardrails_tests fix(guardrails): honor configured timeout in Zscaler AI Guard (#36110) 2026-08-07 00:25:52 +00:00
image_gen_tests test(bedrock): switch image gen live test off EOL Titan to Nova Canvas (#31937) 2026-07-01 22:57:29 -07:00
integration
litellm fix(proxy): deny agent access when key and team grants resolve to nothing (#36221) 2026-08-07 20:44:11 +00:00
litellm-proxy-extras
litellm_core_utils
litellm_utils_tests fix(reset_budget_job): atomic budget cascade with chunked reset scans (#36287) 2026-08-10 14:42:36 -07:00
llm_responses_api_testing test: repair stale CircleCI contracts 2026-08-08 12:19:29 -07:00
llm_translation test(bedrock): port the openai-route invoke tests onto the live config 2026-07-29 20:59:08 -07:00
load_tests
local_testing test: repair three failing suites on litellm_internal_staging 2026-08-04 16:07:02 -07:00
logging_callback_tests feat(logging): add opt-in session_id and trace_id correlation to JSON log records via contextvars (#34418) 2026-08-10 10:40:13 -07:00
mcp_tests fix(mcp): keep REST tool listing in step with key/team grant enforcement 2026-07-30 22:13:10 -07:00
multi_instance_e2e_tests
ocr_tests test(ocr): use mistral-document-ai-2512 in azure_ai OCR tests 2026-07-15 18:13:22 -07:00
old_proxy_tests/tests
openai_endpoints_tests fix(batches): register managed output files on batch cancel 2026-08-05 18:28:52 -07:00
otel_tests fix(cli): mint per-session agent credential on lite login (#31072) 2026-06-26 09:05:15 -07:00
pass_through_tests test(pass-through): de-flake vertex spend-log test by routing through the proxy (#31689) 2026-06-30 15:27:48 -07:00
pass_through_unit_tests fix(proxy): re-assert the authenticated identity on passthrough requests (#36121) 2026-08-07 00:41:29 +00:00
proxy_admin_ui_tests Revert "chore: remove _experimental/out (#31546)" 2026-07-01 13:25:47 -07:00
proxy_behavior test: repair stale CircleCI contracts 2026-08-08 12:19:29 -07:00
proxy_e2e_anthropic_messages_tests
proxy_migration_tests test(docker): gate the componentized gateway and backend images on an arbitrary-uid offline boot (#36136) 2026-08-07 09:57:37 -07:00
proxy_security_tests
proxy_unit_tests perf(spend): write each daily spend batch in one upsert statement (#36448) 2026-08-10 17:06:00 -07:00
router_unit_tests feat(router): add per-deployment allowed_fails_policy and cooldown_time override support (#34416) 2026-08-10 11:02:06 -07:00
scim_tests
search_tests feat(tinyfish): make search provider permissive, attribute errors (#31997) 2026-07-03 10:17:11 -07:00
spend_tracking_tests
store_model_in_db_tests feat(team): custom metadata validation hook for team create and update (#33353) 2026-08-03 18:37:45 -07:00
test_litellm fix: net prompt-caching savings against the cache-write premium (#36452) 2026-08-10 18:52:03 -07:00
unified_google_tests
vector_store_tests
windows_tests
__init__.py
_fake_openai_endpoint_server.py
_flush_vcr_cache.py
_live_test_helpers.py
_openai_record_replay_proxy.py
_vcr_conftest_common.py
_vcr_redis_persister.py
_ws_vcr.py test(realtime): record and replay websocket traffic in redis vcr cassettes (#32390) 2026-07-08 00:19:06 -07:00
eval_swe_bench.py
fake_openai_endpoint.py
gettysburg.wav
large_text.py
openai_batch_completions.jsonl
pyrightconfig.json test: add e2e tests for spend, budgets and llms (#30869) 2026-06-24 15:01:57 -07:00
README.MD
test_anthropic_compaction_usage.py
test_budget_management.py
test_callbacks_on_proxy.py
test_config.py
test_debug_warning.py
test_default_encoding_non_root.py
test_end_users.py
test_entrypoint.py
test_fallbacks.py
test_gpt5_azure_temperature_support.py
test_health.py
test_keys.py
test_litellm_proxy_responses_config.py
test_logging.conf
test_models.py
test_new_vector_store_endpoints.py
test_openai_endpoints.py
test_organizations.py
test_otel_thread_leak.py
test_passthrough_endpoints.py
test_presidio_latency.py
test_proxy_server_non_root.py
test_ratelimit.py
test_resource_cleanup.py
test_service_logger_otel.py fix(langfuse): send v4 ingestion header for otel callback (#33907) 2026-07-18 20:36:51 -07:00
test_spend_logs.py
test_team.py
test_team_logging.py
test_team_members.py
test_users.py

In total litellm runs 1000+ tests

[02/20/2025] Update:

To make it easier to contribute and map what behavior is tested,

we've started mapping the litellm directory in tests/test_litellm

This folder can only run mock tests.