Repository navigation
fix(spend-tracking): recover key alias for session tokens from spend logs - #40275
Conversation
…logs CLI session tokens are in-memory only and never get a LiteLLM_VerificationToken row, so the usage APIs could not resolve key_alias, team_id, or user_email for their spend rows: the exact join and the reverse-hash recovery both miss. The owner is written to LiteLLM_SpendLogs.metadata at request time under the same hashed api_key, so read it back from there for keys still unresolved after the token-table passes. The lookup is sha256-gated like the existing reverse-hash recovery and bounded to the records' startTime window (min date minus one day, max date plus two) so it stays on the startTime index. No migration. Also guard the window parser against the date=None rollup rows GROUPING SETS aggregation emits, which raised TypeError from strptime and turned the aggregated usage endpoints into HTTP 500s.
…/litellm into litellm_lit6852_spend_attribution
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
Greptile SummaryThis PR recovers aliases, teams, and owners for unresolved session-token and hashed-JWT digests by consulting spend logs within the activity date window.
Confidence Score: 5/5The PR appears safe to merge; no new actionable defect or outstanding previous finding remains. The spend-log scan is date-bounded, transactionally protected by a statement timeout, and degrades to unchanged nameless metadata when recovery fails. Per-field aggregation withholds conflicting identities, and the cache and concurrency behavior are covered by focused tests. The remaining unresolved provider threads were explicitly withdrawn by Greptile after the implementation tradeoffs were accepted; all other prior findings are resolved.
|
| Filename | Overview |
|---|---|
| litellm/proxy/spend_tracking/key_metadata_recovery.py | Adds bounded spend-log metadata recovery, per-field agreement checks, caching, and concurrency control without an accepted new defect. |
| litellm/proxy/management_endpoints/common_daily_activity.py | Passes padded activity date windows into metadata recovery across the relevant aggregation paths. |
| litellm/constants.py | Defines fixed cache limits, TTLs, and the spend-log query timeout. |
| tests/test_litellm/proxy/spend_tracking/test_key_metadata_recovery.py | Covers digest filtering, metadata agreement, cache behavior, concurrency, failures, and transactional timeout setup. |
| tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py | Covers date-window construction and end-to-end metadata attachment in daily activity results. |
Reviews (10): Last reviewed commit: "test(spend-tracking): mock the spend-log..." | Re-trigger Greptile
| WHERE api_key = ANY($1::text[]) | ||
| AND "startTime" >= $2::timestamp | ||
| AND "startTime" < $3::timestamp | ||
| ORDER BY api_key, (metadata->>'user_api_key_alias') IS NULL, "startTime" DESC |
There was a problem hiding this comment.
The startTime index bounds this query to the date window. An api_key index means a boot-time build on the largest table and its own PR
There was a problem hiding this comment.
That’s fair. The existing startTime index lets PostgreSQL bound the scan to the requested window, and adding an api_key-leading index solely for this recovery path would impose a substantial build/storage cost on the largest table. The remaining cost is proportional to spend rows in the selected window, which is a reasonable trade-off for this targeted fix. I’m withdrawing the indexing finding; a composite-index follow-up should be driven by production EXPLAIN/latency data.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Devin e2e QATested at: 529b870 Shared setup for both legs: proxy booted from a detached worktree with Before (ee1a640)Session token request, then the usage APIs
Usage page, Key Activity tab
Every other daily activity route
After (529b870)Session token request, then the usage APIs
Usage page, Key Activity tab
Every other daily activity route
Observations from the run:
|
…ass with a per-worker cache The spend-log lookup for permanently unresolvable digests is back to a single DISTINCT ON scan over the requested window, keeping only rows that carry an alias, user, or team so a newer nameless row cannot hide an older named one. Results and misses are cached per worker for ten minutes keyed by digest and window, failed queries are not cached, and JWT rows keyed hashed-jwt-<sha256> now pass the digest gate. Tests cover the JWT gate, cache reuse and partial misses, window changes, error handling, the with-window guard, and the daily activity wiring
…onstants The ten minute TTL and the 10000 item ceiling need no env override, and the documentation env-key check flags any os.getenv read that the docs do not list
…conds The daily spend rows and the spend logs of one batch are written a moment apart, so a usage read landing between them used to remember the session as nameless for ten minutes on that worker. Found identities keep the ten minute entry
…peated misses Concurrent usage reads on one worker now share a single spend-log query instead of each scanning the same window, and a digest that comes back nameless a second time is remembered for the full ten minutes rather than thirty seconds, so a key that never resolves costs at most two scans per worker per window per ten minutes. The first miss still expires after thirty seconds so a read that lands between the daily spend flush and the spend-log flush recovers on the next read
| if cache.get_cache(missed_before) is not None: | ||
| cache.set_cache(key, KeyMetadataDict()) | ||
| return |
There was a problem hiding this comment.
After the initial 30-second miss expires, a second lookup that still finds no spend row sees the long-lived :missed-before marker and caches an empty result using the 600-second default TTL. If the spend row arrives after that lookup, activity reads continue showing the session anonymously for up to ten minutes. Repeated misses should continue using the shorter miss TTL.
| if cache.get_cache(missed_before) is not None: | |
| cache.set_cache(key, KeyMetadataDict()) | |
| return | |
| if cache.get_cache(missed_before) is not None: | |
| cache.set_cache(key, KeyMetadataDict(), ttl=SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL) | |
| return |
There was a problem hiding this comment.
A 30 s TTL on every miss is the rescan the previous round flagged: a digest with no identity row would rescan the whole window every 30 s per worker forever. The first miss already covers the flush gap, so a second miss is a key that will not resolve
There was a problem hiding this comment.
That tradeoff is reasonable. The :missed-before marker intentionally distinguishes the first miss (the 30-second spend-log flush gap) from repeated misses, preventing a digest that has no identity-bearing spend row from triggering a full-window scan every 30 seconds. Given the documented write ordering and the accepted caveat for delayed or pruned rows, I’m withdrawing the finding.
…rs and back off failed scans
…t and name only unanimous alias, team, and owner
… its caller now opens
|
bugbot run |
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 529b870. Configure here.
TLDR
Problem this solves:
key-hash-...rows for CLI session tokens, no alias or emailHow it solves it:
ui-tokendigest keeps its alias and team but names no ownerUser Flow
Before: an admin checking usage after a teammate used a CLI session token sees a bare key hash with no alias or email
litellm-proxy loginand gets a 24-hour session token instead of a virtual keyAuthorization: Bearer <session token>and"model": "gpt-4o-mini", and get a 200 with the reply"key_alias": nulland"user_email": nullkey-hash-d8c5b4eebd89..., so nobody can tell whose spend it isAfter: the same row carries the developer's alias and email in the API and on the Usage page
litellm-proxy loginand gets a 24-hour session token instead of a virtual keyAuthorization: Bearer <session token>and"model": "gpt-4o-mini", and get a 200 with the reply"key_alias": "cli-session-repro-user-6852"and"user_email": "repro6852@example.com"cli-session-repro-user-6852Relevant issues
Linear ticket
Resolves LIT-6852
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<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@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Shared setup for both legs: the proxy booted from this branch's worktree with
--num_workers 2on port 52245 against a local Postgres, one modelgpt-4o-mini -> openai/gpt-4o-mini(real OpenAI spend), master key in$LITELLM_MASTER_KEY. A CLI session token for userrepro6852@example.comwith aliascli-session-repro-user-6852sits in$CLI_SESSION_TOKEN; its spend rows land under key hashd8c5b4eebd89.... A normal virtual key with aliasnormal-alias-6852and one master-key request are in the same day as controls. The Before leg swapped the same worktree to the merge base and rebooted the proxy; nothing else changed between legsBefore (ee1a640)
Session token request, then the usage APIs
{"id":"chatcmpl-ELvUdtq1wPskrghBMBOKJXp8pkyoR","model":"gpt-4o-mini","content":"before","usage":{"prompt_tokens":14,"completion_tokens":1}}{ "date": "2026-09-08", "api_keys": { "d8c5b4eebd89...": { "key_alias": null, "user_email": null, "requests": 2 }, "fc048c026e74...": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 }, "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 } } }/user/daily/activity/aggregated(same query, samejq):{ "date": "2026-09-08", "api_keys": { "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 }, "fc048c026e74...": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 }, "d8c5b4eebd89...": { "key_alias": null, "user_email": null, "requests": 2 } } }Usage page, Key Activity tab
Log in at http://localhost:52245/ui/login (username
admin, password the master key), open http://localhost:52245/ui/?page=new_usage, click theKey ActivitytabThe session token's row is labeled
key-hash-d8c5b4eebd89ce9de197e5d92d1c950731e27db82777620391218a0dfd4172f2with 2 requests, while the virtual key's row readsnormal-alias-6852Every other daily activity route
d8c5b4eebd89...entry withkey_alias: null, user_email: null; the other five have no rows for this dayAfter (529b870)
Session token request, then the usage APIs
{"id":"chatcmpl-EM0shTUa1LpulCGdsWQDvOW5MMX74","model":"gpt-4o-mini","content":"after","usage":{"prompt_tokens":14,"completion_tokens":1}}{ "date": "2026-09-09", "api_keys": { "c14b71ea0956...": { "key_alias": "ui-token", "user_email": null, "requests": 2 }, "0ddc8f3c1378...": { "key_alias": "ui-token", "user_email": "ui-alice-6852@example.com", "requests": 1 }, "d8c5b4eebd89...": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 2 }, "86a1eb5e4977...": { "key_alias": "ui-token", "user_email": "ui-bob-6852@example.com", "requests": 1 } } } { "date": "2026-09-08", "api_keys": { "c14b71ea0956...": { "key_alias": "ui-token", "user_email": null, "requests": 2 }, "d8c5b4eebd89...": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 9 }, "fc048c026e74...": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 }, "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 } } }ui-tokenrows that carry an email are the 401 responses to expired experimental UI tokens from an earlier run, logged under each token's own digest, and the reader names them from those failure rows/user/daily/activity/aggregated(same query, samejq):{ "date": "2026-09-09", "api_keys": { "c14b71ea0956...": { "key_alias": "ui-token", "user_email": null, "requests": 2 }, "0ddc8f3c1378...": { "key_alias": "ui-token", "user_email": "ui-alice-6852@example.com", "requests": 1 }, "86a1eb5e4977...": { "key_alias": "ui-token", "user_email": "ui-bob-6852@example.com", "requests": 1 }, "d8c5b4eebd89...": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 2 } } } { "date": "2026-09-08", "api_keys": { "fc048c026e74...": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 }, "d8c5b4eebd89...": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 9 }, "c14b71ea0956...": { "key_alias": "ui-token", "user_email": null, "requests": 2 }, "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 } } }Usage page, Key Activity tab
Log in at http://localhost:52245/ui/login (username
admin, password the master key), open http://localhost:52245/ui/?page=new_usage, click theKey ActivitytabThe same row is now labeled
cli-session-repro-user-6852with 9 requests on 2026-09-08, the day the page shows by default, next tonormal-alias-6852; the request above and the one from the previous leg landed after midnight UTC, on 2026-09-09Every other daily activity route
user_email: "repro6852@example.com"on that row too; the other five still have no rows for this dayTwo users behind the shared experimental UI session digest
The experimental UI login (
EXPERIMENTAL_UI_LOGIN=true) hands every user a session whose key is the literalui-token, so all of them land under one spend-log digest,c14b71ea.... Two users share it here to show the reader does not hand one user's spend to the other{"user_id":"ui-alice-6852","user_email":"ui-alice-6852@example.com"} {"user_id":"ui-bob-6852","user_email":"ui-bob-6852@example.com"}ExperimentalUIJWTToken.get_experimental_ui_login_jwt_auth_token(the function the UI login calls) into$UI_TOKEN_aliceand$UI_TOKEN_bob, then one real request each:{"id":"chatcmpl-EM0sqFCVyrjWtdxUkeULFlx6OZLAx","model":"gpt-4o-mini","content":"alice"} {"id":"chatcmpl-EM0st0jW43JWL7Vh0BXCSefUWgWRK","model":"gpt-4o-mini","content":"bob"}{ "c14b71ea09568f1051e26d2c223f9e77720290351432ecfbc6c1a77514bdaf39": { "key_alias": "ui-token", "team_id": "litellm-dashboard", "user_email": null, "requests": 4 } } { "c14b71ea09568f1051e26d2c223f9e77720290351432ecfbc6c1a77514bdaf39": { "key_alias": "ui-token", "team_id": "litellm-dashboard", "user_email": null, "requests": 2 } }ui-bob-6852, so every UI user's spend would have carried bob's email; at this tip the row keepsui-tokenandlitellm-dashboardand names nobodyObservations from the run:
Master key rows stay a bare sentinel; unchanged by this PR
Session tokens spent before v1.99 stored raw, still nameless; pre-existing
Two workers without Redis show the Redis banner; unrelated
8c878f3 passes /live-pr-risk
Changed surface: the shared key metadata lookup gains one optional parameter (defaults to off), one new spend-log reader, two date-window helpers. Dependents: the three usage aggregation paths behind the ten
/*/daily/activityroutes plus/user/daily/activity/aggregated, the usage AI chat endpoint riding the same paths, and the Admin UI Key Activity label readingkey_aliasanduser_email. Covered by the new unit tests: the reader, the sha256 gate, the window math, the null-date rollup rows. Driven live base vs head, same two-worker topology: the ten routes above, plus on head an empty date range (2026-09-01..02, 200, no rows), a 39-day range (200, alias resolved), andpage_size=1(200, alias resolved), five sequential reads at 14 to 19 ms. Not verified: organization, customer, end_user, agent, and gateway routes returned no rows because the QA database has none of those entities, so their metadata path was exercised only to the empty result; the CloudZero and Focus export helpers do not call the changed lookup and were left alone. The four CircleCI legacy suites that hit daily activity assert nothing aboutkey_aliasoruser_email; therun-cilabel is on so they run anywayDelta since 8c878f3: the spend-log reader is one
DISTINCT ONpass per call that keeps only rows carrying an alias, user, or team, the digest gate also acceptshashed-jwt-<sha256>rows, and each worker caches hits and misses per digest and date window for ten minutes (two plain constants inlitellm/constants.py), never a failed query. Same dependents as before, plus the per-process cache as new in-memory state, so the head ran as two workers sharing one database with reads alternating across them. Driven live on head: the ten routes above, an empty date range (2026-09-01..02, 200, no rows), a 39-day range (200, alias resolved) read twice (19 ms both),page_size=1(200, alias resolved), five sequential reads at 18 to 21 ms. Bench on a 2M-row spend-log table with 501 unresolved digests: 2.06 s for a 30-day window, 0.26 s for one day, against 59 s for the per-key lookup this replaces. One new behavior to know: the daily spend rows and the spend logs of one batch are written in that order a moment apart, so a usage read landing between them caches that digest as nameless on that worker until the miss entry expires; the other worker and the next window are unaffected. Not verified: same five entity routes as before (no rows in the QA database)Delta since 550e733: the two cache limits are plain constants instead of
os.getenvreads, so there is no runtime toggle and the documentation env-key check has nothing new to list. Default behavior is identical. The After leg above re-ran at this tip on the same two-worker topology: six requests on the session row, alias and email on every route that carries the digest, five sequential reads at 24 to 36 ms, the 39-day range at 22 ms then 16 ms. Not verified: the same five entity routes as before (no rows in the QA database)Delta since f4aef5a: an empty spend-log answer is remembered for thirty seconds instead of ten minutes, found identities keep the ten minute entry. The flush-gap read above now shows the session nameless for half a minute on that worker (a second miss keeps it nameless for ten minutes). Same dependents, same two-worker topology; the After leg re-ran at this tip: 7 requests on the session row, alias and email on every route that carries the digest, five sequential reads at 9 to 15 ms, the 39-day range at 9 then 9 ms. Not verified: the same five entity routes as before (no rows in the QA database)
Delta since 0c2d0f4: concurrent usage reads on one worker share a single spend-log query, and a digest that misses twice keeps the ten minute entry, so a key that never resolves costs at most two scans per worker per window per ten minutes. Same dependents, same two-worker topology; the After leg re-ran at this tip: 8 requests on the session row, alias and email on every route that carries the digest, five sequential reads at 73, 21, 48, 50, and 26 ms, the 39-day range at 21 then 92 ms. Not verified: the same five entity routes as before (no rows in the QA database)
Delta since 907c200: the spend-log query also returns the first and last owner seen per digest in the window, and a digest whose named rows disagree on the owner keeps alias and team but no user, so the experimental UI login's shared
ui-tokendigest cannot hand one user's spend to another; an empty alias counts as missing; a scan that fails is remembered like a miss (thirty seconds, then ten minutes on a repeat) instead of re-running on every read. Same dependents, same two-worker topology; the After leg re-ran at this tip: 9 requests on the session row, alias and email on every route that carries the digest, five sequential reads at 10, 9, 8, 10, and 14 ms, the 39-day range at 10 then 10 ms, plus the two-user shared digest run above. Not verified: the same five entity routes as before (no rows in the QA database), ahashed-jwt-digest live (unit tests only)Delta since 7a6c0cb: the spend-log scan runs inside a Prisma transaction that first sets a five-second
statement_timeout, so a window too large for the unindexedLiteLLM_SpendLogstable is cancelled server-side and remembered like a miss (thirty seconds, then ten minutes on a repeat) instead of holding the per-worker lock; the query groups by digest and names alias, team, and owner only where every row in the window agrees, so an owner older rows agree on survives a nameless newest row and a digest whose rows disagree on a field names nothing for that field. Same dependents, same two-worker topology; the After leg re-ran at this tip: 10 requests on the session row, alias and email on every route that carries the digest, five sequential reads at 19, 11, 14, 13, and 11 ms, the 40-day range at 13 then 9 ms, plus the two-user shared digest run above (four rows over two days, no owner). Not verified: the same five entity routes as before (no rows in the QA database), ahashed-jwt-digest live (unit tests only), the statement timeout firing against a production-sized table (verified with psql:SET LOCAL statement_timeoutinside a transaction cancels a slow statement and does not leak past it)Delta since 268b944: test-only commit, the three usage tests in the caller's file that mocked the scan directly now mock it through the transaction it opens, nothing under
litellm/changed. The After leg re-ran at this tip on the same two-worker topology: the session request resolved to its alias and email on the user, aggregated, team, and tag routes, the sharedui-tokendigest still names nobody, five reads of the two-day window took 11, 9, 9, 9, and 9 ms, the 40-day range 9 then 10 ms, and the proxy log has no recovery warningsType
🐛 Bug Fix
Caveats (if any)
Medium
LiteLLM_SpendLogshas no api_key index, so a usage read with unresolved digests scans the date window bystartTime; each scan is bounded to five seconds server-side and there are at most two scans per worker per window per ten minutes, run one at a time. A window too large for that budget stays nameless as it did before this PR; an api_key index is a follow-up, not a boot-time migration on the largest tableui-tokendigest shows aliasui-tokenand teamlitellm-dashboardwith no owner or email; it named nobody before this PR eitherhashed-jwt-digests pick up alias and email from spend logs and scan once per window on the first read; a JWT row carries no alias, so its label falls back to the emailhashed-jwt-gate has unit tests onlyLow
litellm-proxy login, but the CLI login itself was not drivencli-session-<user_id>row per loginFinal Attestation
Note
Medium Risk
Adds bounded but potentially heavy
LiteLLM_SpendLogsscans on usage reads when keys stay unresolved; caching and timeouts limit blast radius, but correctness of attributed email depends on unanimous spend-log metadata.Overview
Fixes nameless key-hash rows on daily usage APIs and the Admin UI for CLI session tokens (and other digests with no verification-token row) by adding a third metadata recovery step after active, deleted, and double-hash token lookups.
When daily activity aggregation runs, it now derives a padded
startTimewindow from the page’s dates and callsrecover_key_metadata_from_spend_logs, which scansLiteLLM_SpendLogsfor alias, team, and owner fields (includinghashed-jwt-digests). Results are cached per worker (hits ~10 minutes, short miss backoff, serialized queries) and each scan runs in a transaction with a 5s statement timeout so large windows fail safe instead of blocking usage reads. Alias, team, and owner are only set when all matching spend rows agree on that field, so shared digests like experimental UIui-tokenkeep alias/team but not a single owner email.Reviewed by Cursor Bugbot for commit 529b870. Bugbot is set up for automated code reviews on this repo. Configure here.