Skip to content

fix(spend): record unpriced savings dollars as NULL, not a fabricated $0.00 - #46695

Open
choksi2212 wants to merge 3 commits into
BerriAI:mainfrom
choksi2212:fix/savings-unpriced-46677
Open

choksi2212 wants to merge 3 commits into
BerriAI:mainfrom
choksi2212:fix/savings-unpriced-46677

Conversation

@choksi2212

Copy link
Copy Markdown

Problem

Since the OpenRouter rows were removed from the cost map (#45665–#45669), every openrouter/* deployment records its savings dollars as $0.00:

The result is exactly what the issue describes: compression_saved_tokens keeps climbing in LiteLLM_DailyUserSpend while compression_savings_spend / prompt_caching_savings_spend flatline at 0, and since daily rows are priced at write time and never repriced, every unpriced request writes a row that claims a measured zero it never measured. A $0.00 reads as "saved nothing"; the truth is "could not price".

The same is true for any unmapped model, but the cost-map removals turned it from an edge case (a typo, a private deployment name) into the steady state for a whole provider.

Fix

Savings the request's pricing cannot resolve now report None, and the write path records them as NULL — the "unpriced" marker — instead of a fabricated 0.0:

  • savings.py — get_cost_per_unit(..., default_value=None) keeps a missing input rate distinguishable from an explicit 0.0 rate (a free model is a price, not an unknown). _priced_tokens() keeps 0 saved tokens a priced zero. Prompt caching stays None only when no pricing resolves; a priced request with missing/unusable usage keeps reporting 0.0 as before (that zero is about the usage, not the price).

  • SavingsSpend — compression / prompt_caching / gateway_injected_caching become float | None. autorouter keeps its plain float: an un-routed request genuinely has zero auto-router savings, and unknown estimates are already kept apart by recorded_estimated_autorouter_savings.

  • Rollup queue — _add_savings_dollars() merges an unpriced figure as "no dollars from this row": None + None = None, None + x = x. A row stays unpriced exactly while every contributing request was unpriced. Transactions that carry no savings keys at all keep their old zero semantics.

  • Bulk upsert — unpriced figures bind as NULL, and the increment becomes NULL-aware:

    "compression_savings_spend" = COALESCE(
        "LiteLLM_DailyTagSpend"."compression_savings_spend" + EXCLUDED."compression_savings_spend",
        "LiteLLM_DailyTagSpend"."compression_savings_spend",
        EXCLUDED."compression_savings_spend")

    so an unpriced request landing on a priced row contributes nothing instead of wiping it, a priced request landing on an all-unpriced row prices it, and two unpriced rows stay unpriced. spend and autorouter_savings_spend keep their plain increments.

  • schema.prisma — the three savings columns on the seven daily spend tables become nullable Float? (required for the raw-SQL NULL write; prisma db push applies it on startup). Readers need no changes: SUM() ignores NULL and the daily-activity endpoints already coalesce with or 0, so visible totals are exactly the priced dollars — the row just stops claiming a measurement it never made.

Deployment-configured per-token prices (model_info on the deployment) still price savings exactly as before — that path was already independent of the cost map.

Verification

Repro (fails on main, fixed here):

compute_savings_spend(model="openrouter/z-ai/glm-5.3-flash", custom_llm_provider="openrouter",
                       compression_saved_tokens=5000, gateway_injected_cache=False)
# main: SavingsSpend(compression=0.0, prompt_caching=0.0, ...)
# this: SavingsSpend(compression=None, prompt_caching=None, ...)

Negative controls — 14 new assertions fail on pristine main and pass on this branch:

  • savings: unmapped-provider regression, unknown/missing model unpriced, zero-token stays a priced zero, _priced_tokens distinguishes a 0.0 rate from no rate
  • queue: unpriced+unpriced aggregates to None (main: 0.0); missing-key keeps old zero
  • bulk upsert: unpriced rows survive the conflict merge as None, NULL binds for the three figures, the COALESCE fragment is pinned
  • writer end-to-end: an openrouter/* payload with 5000 compression-saved tokens queues compression_savings_spend=None with compression_saved_tokens=5000 intact (main: 0.0)

Real PostgreSQL 18 (Debian, WSL) — drove the actual build_bulk_upsert() statements against a live LiteLLM_DailyTagSpend:

step result
fresh unpriced row all three savings columns NULL, tokens recorded
priced upsert onto NULL row 0.25 / 0.10 / 0.10 — priced, not wiped
unpriced upsert onto priced row priced dollars survive (0.25 / 0.10 / 0.10), tokens accumulate
priced-zero upsert adds nothing
batch merge (priced + unpriced, same key) 0.11 with the unpriceable figure still NULL
SUM() over the table NULLs ignored — visible totals are the priced dollars only

Suites: tests/unit/proxy/spend_tracking/test_savings.py 132 pass, tests/unit/proxy/db/db_transaction_queue/test_daily_spend_update_queue.py 19 pass (incl. the pre-existing same-key exact-dict test unchanged), tests/unit/proxy/db/test_daily_spend_bulk_upsert.py 22 pass, tests/unit/proxy/db/test_db_spend_update_writer.py 191 pass. The pre-existing test_unknown_model_fails_open_to_zero / test_missing_model_fails_open_to_zero pins were updated to the new contract — the per-request estimator already distinguished unknown from zero (prompt_caching_savings_for_request(...) is None); this change stops the rollup from collapsing that distinction at the write. ruff check + ruff format clean on all touched source files; basedpyright: 0 diagnostics in the touched hunks.

Notes for reviewers

  • Billing is untouched: spend still comes from usage.cost / x-litellm-response-cost.
  • Historical 0.0 rows written before this change are indistinguishable from measured zeros and are not repriced (same as today) — new rows stop adding to that ambiguity.
  • The prisma schema change is additive-nulling only: existing rows keep their values; db push drops the NOT NULL on those three columns.

Closes #46677

… $0.00

Since the OpenRouter rows left the cost map (BerriAI#45665-BerriAI#45669), every
openrouter/* deployment resolves no pricing in compute_savings_spend():
get_model_info() raises, the input-rate lookup collapses to 0.0, and
the daily tables record compression_savings_spend = 0.00 while
compression_saved_tokens keeps climbing (BerriAI#46677).

Savings the request's pricing cannot resolve now report None and are
recorded as NULL:

- get_cost_per_unit(..., default_value=None) keeps a missing input rate
  distinguishable from an explicit 0.0 rate; zero saved tokens stay a
  priced 0.0 and a priced request with missing usage still reports 0.0
- SavingsSpend.compression/prompt_caching/gateway_injected_caching are
  float | None; autorouter keeps its plain float (an un-routed request
  is a true zero, unknown estimates are versioned separately)
- the rollup queue merges None as no-dollars-from-this-row and never
  turns an unpriced row into a measured zero
- the bulk upsert binds NULL and merges NULL-aware via
  COALESCE(col + EXCLUDED.col, col, EXCLUDED.col), so an unpriced
  request neither wipes a priced row nor zeroes an all-unpriced one
- the three savings columns on the seven daily spend tables become
  nullable Float?; readers already coalesce (SUM ignores NULL, the
  daily activity endpoints apply or 0), so visible totals are unchanged

Deployment-configured per-token prices keep pricing savings exactly as
before, and billing is untouched (spend still comes from usage.cost).

Signed-off-by: choksi2212 <choksi2212@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@CLAassistant

Copy link
Copy Markdown

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

…olumns

The root schema.prisma changes in the previous commit must be
mirrored byte-for-byte into litellm/proxy/schema.prisma and
litellm-proxy-extras/litellm_proxy_extras/schema.prisma for the
check-schema-sync CI job.

Signed-off-by: choksi2212 <choksi2212@users.noreply.github.com>
@codecov

codecov Bot commented Oct 15, 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 15, 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

✅ 31 untouched benchmarks


Comparing choksi2212:fix/savings-unpriced-46677 (93ccb3f) with main (bdd8078)

Open in CodSpeed

@charan-rathore charan-rathore left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran the four touched test files against both trees (pytest, unit suite). With main source under this branch tests, 15 assertions fail - all of them the new unpriced-savings cases (openrouter rows absent from the cost map, a missing model, and the zero-rate versus no-rate split all currently record a fabricated 0.0). On this branch all 370 tests pass. The None propagation through _priced_tokens keeps a genuine zero priced at 0.0 while unpriced savings reach the daily tables as NULL, and leaving autorouter as a plain float stays consistent with the recorded_estimated_autorouter_savings split. The three schema.prisma copies change in sync.

… fields

- declare the two merge locals in _add_savings_dollars Final (LIT010)
- move the writable-ok suppressions onto the TypedDict field lines they
  govern, matching the sibling spend fields (LIT012), which also removes
  the suppression-on-a-comment-line the gate counts as suppressing
  nothing (LIT013)

Signed-off-by: choksi2212 <choksi2212@users.noreply.github.com>
@choksi2212

Copy link
Copy Markdown
Author

@charan-rathore — thanks again for the approval on Oct 15. Gentle check-in: is anything blocking the merge here, or would this need a second pair of eyes? The full matrix is green at c3f3bd6 (370 targeted + 2645 broad tests, failure set identical to pristine main, plus the real-PG18 e2e scenarios from the PR body). Happy to address anything else.

@choksi2212

Copy link
Copy Markdown
Author

Friendly merge-check 🙂 — this was approved by @charan-rathore on Oct 15 and the follow-ups are addressed, but it looks like it hasn't landed yet. Is there anything else needed from my side, or would it help if I rebased it against the current main?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Headroom compression and prompt-caching savings recorded as $0 for openrouter/* models since cost-map rows were removed

3 participants