Skip to content

fix(usage): preserve daily spend by public model - #44357

Open
tin-berri wants to merge 5 commits into
mainfrom
litellm_public_model_daily_usage
Open

tin-berri wants to merge 5 commits into
mainfrom
litellm_public_model_daily_usage

Conversation

@tin-berri

@tin-berri tin-berri commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Usage merges public model names sharing one deployment

How it solves it:

  • Keep each public model’s daily totals separate
  • Preserve stable PTU charges across model renames

Intentional product change: Usage shows N/A when there are no successful requests to average, and explains UTC daily totals

User Flow

Before: two public names can appear as one model in Usage

  1. Send POST https://litellm-domain/v1/chat/completions as the same key using direct-model, then alternate-model, backed by one deployment
  2. Open https://litellm-domain/ui/usage/ and select the request date
  3. One model row contains both requests; the other name is absent

Merged public model usage

After: Usage retains the separate public names and their totals

  1. Send the same two requests using direct-model and alternate-model
  2. Open https://litellm-domain/ui/usage/ and select the request date
  3. Each model row contains its own spend, tokens and requests

Separate public model usage

Relevant issues

Changes

  • Include model_group in all six daily queue, bulk-upsert and database identities
  • Synchronize three Prisma schemas and replace six unique indexes without rewriting historical rows
  • Preserve stable PTU IDs across renames and concurrent writes
  • Explain zero-request averages and UTC usage days in the dashboard

Linear ticket

Resolves LIT-9198

Pre-Submission checklist

  • Meaningful regressions: 94 added test lines / 97 implementation lines
  • 357 targeted Python tests and 61 dashboard tests pass independently
  • make check, discovery/shard guards and migration scanner pass locally
  • This PR addresses one defect and can merge independently
  • Fresh CI, coverage and reviews pending on this split commit

Screenshots / Proof of Fix

Real local proxies and isolated Postgres, using paid moonshot/kimi-k3 calls on 2026-10-03. direct-model and alternate-model share a deployment. Each endpoint has a separate user/key. $PROXY is http://127.0.0.1:4584 before and http://127.0.0.1:4585 after

The User Flow screenshots show http://127.0.0.1:3014/usage/ before and http://127.0.0.1:3015/usage/ after: open Usage, choose Model Activity, then Public Model Name

Send each payload twice, replacing <MODEL> with each public name:

curl "$PROXY/v1/chat/completions" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"<MODEL>","messages":[{"role":"user","content":"Reply with the word hello."}],"max_tokens":64}'
curl "$PROXY/v1/messages" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"<MODEL>","messages":[{"role":"user","content":"Reply with the word hello."}],"max_tokens":64}'
curl "$PROXY/v1/responses" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"<MODEL>","input":"Reply with the word hello.","max_output_tokens":64}'
curl "$PROXY/user/daily/activity/aggregated?start_date=2026-10-03&end_date=2026-10-03&user_id=$USER_ID" -H "Authorization: Bearer $ADMIN_KEY"

Before (5724117)

Chat Completions

  1. Run the Chat Completions pair and usage query
  2. direct-model contains both requests: 70 tokens/$0.000474; alternate-model is absent

Anthropic Messages

  1. Run the Messages pair and usage query
  2. The same incorrect merged row contains 70 tokens/$0.000474

Responses

  1. Run the Responses pair and usage query
  2. The same incorrect merged row contains 70 tokens/$0.000474

After (c6669ba)

Chat Completions

  1. Repeat the Chat Completions pair and usage query
  2. Each public name retains 1 request, 35 tokens and $0.000237

Anthropic Messages

  1. Repeat the Messages pair and usage query
  2. Each public name retains 1 request, 35 tokens and $0.000237

Responses

  1. Repeat the Responses pair and usage query
  2. Each public name retains 1 request, 35 tokens and $0.000237

The current migration was applied twice to the current base schema using real Postgres. Historical totals, nullable groups, repeated/concurrent writes across all six tables, and stable PTU IDs across renames passed

Type

Bug Fix

Caveats (if any)

Severe

  • Drain buffers and stop old writers before index replacement
  • Index construction blocks writes; schedule a maintenance window
  • Rollback requires reconciling rows before restoring old indexes

Medium

  • Historical merged model attribution cannot be reconstructed
  • Rows stored with a NULL model_group by releases before 2026-08-19 keep their own row if the same identity is written again on the same UTC day after the cutover; totals stay correct

Low

  • Hosted CI and reviews are running on this fresh PR
  • Upstream ROI-fixture mismatch also fails proxy-infra
  • The unchanged lockfile triggers braces@3.0.3 advisory GHSA-vfj7-8cjw-p6xm

Note

High Risk
Index replacement on production daily spend tables blocks writes and is incompatible with pre-cutover proxy writers; incorrect rollout can corrupt or duplicate attribution until reconciled.

Overview
Daily usage rollups now treat the requested public model group as part of the row identity for all six daily spend tables (user, team, org, end user, agent, tag), so two public names that share one deployment no longer merge into a single Usage row.

A migration replaces six unique indexes and updates the synced Prisma schemas. Bulk upsert and in-memory queue keys now use the same conflict_key tuple (including normalized model_group) as Postgres ON CONFLICT. PTU flat-cost rows upsert by a stable deployment/day row id and only refresh model_group on rename, so charges do not split when the display name changes.

The migration runbook documents a maintenance cutover (drain buffers, stop old writers). The Usage dashboard shows N/A for per-request averages when there are zero successful requests and adds a short note that request counts exclude internal calls while spend/tokens include them.

Reviewed by Cursor Bugbot for commit 7bc136d. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Database schema migration changes daily spend tracking identity.

The PR appears safe to merge under the documented maintenance-window cutover.

Summary

The PR separates daily spend rows by public model group while retaining deployment-based PTU charge identity.

  • Aligns six daily-spend queue keys, bulk upserts, Prisma schemas, and replacement indexes.
  • Documents the required migration cutover and clarifies zero-request averages and UTC daily usage in the dashboard.

Reviews (1) · Last reviewed commit: "fix(usage): preserve daily spend by publ..."

@codspeed

codspeed Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_public_model_daily_usage (306d699) with main (1b98748)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (d306d6d) during the generation of this report, so 1b98748 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Please review the current commit for daily public-model accounting, migration correctness, and PTU identity regressions

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

Stale Bugbot comment from a previous run.

tin-berri and others added 2 commits October 3, 2026 10:27
… a backfill

The daily spend identity indexes and the writer's ON CONFLICT target use
COALESCE("model_group", ''), so rows stored with a NULL group before
model_group joined the key share one identity with the '' new writers store
and no historical row is rewritten. Prisma cannot declare an expression index,
so the three schema copies drop the @@unique and --use_prisma_db_push runs the
identity migration right after the push.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Keeps main's service-target imports beside the PR's writer-pinned client import
in ptu_flat_cost_rollup.py; everything else merged cleanly.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…stead of a backfill"

This reverts commit 29607f8.

Prisma cannot declare the COALESCE expression index, so every database seeded
by `prisma db push` outside the proxy's own startup (the proxy-behavior CI
job, the e2e UI script) had no unique index on the daily spend tables and the
writer's ON CONFLICT failed. The legacy NULL model_group duplicate stays a
documented cutover caveat.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@tin-berri

Copy link
Copy Markdown
Contributor Author

@greptileai can you reply here with a score and why that score?

@tin-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Score: 5/5

This looks safe to merge based on the current commit. The implementation consistently carries model_group through all six daily-spend identities, queue keys, conflict targets, and bulk upserts, so aliases sharing a deployment remain separate without losing totals.

The migration updates the corresponding indexes across all six tables, and the runbook clearly documents the required maintenance-window cutover and incompatibility with old writers. PTU rows retain a stable deployment/day-derived ID while allowing the display name to change, avoiding duplicate charges on renames or concurrent rollups.

The added tests cover nullable identity fields, deterministic merging, internal-call accounting across all entities, PTU legacy-row reuse, retries, concurrency, and dashboard zero-request behavior. The migration is operationally high-risk because index replacement blocks writes, but that risk is clearly documented and is not a correctness blocker for the PR.

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

Adds the row-count query, the per-million-rows estimate measured on a 3M-row
table, the one-transaction write-freeze note, and the migrate deploy timeout
variable to the model-group identity cutover section.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

This branch had an error being deployed

1 failed deployment
e2e-changed — 306d699e Deployed Oct 3, 2026 by tin-berri via oauth #2876
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.

1 participant