Skip to content

fix(spend-tracking): recover key alias for session tokens from spend logs - #40275

Merged
mateo-berri merged 10 commits into
litellm_internal_stagingfrom
litellm_lit6852_spend_attribution
Sep 9, 2026
Merged

mateo-berri merged 10 commits into
litellm_internal_stagingfrom
litellm_lit6852_spend_attribution

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Usage APIs show key-hash-... rows for CLI session tokens, no alias or email
  • Session tokens never get a key record, so the existing lookups find nothing
  • The Admin UI Usage page inherits the same nameless rows

How it solves it:

  • Read the owner back from the spend rows for keys nothing else resolved
  • One bounded scan per date window, named rows only, sha256 and JWT digests
  • Found identities cached per worker for ten minutes, a first empty or failed answer for thirty seconds and a repeated one for ten, one spend-log scan at a time per worker, keyed by digest and window
  • A field (alias, team, or owner) is named only when every spend row behind the digest agrees on it, so the experimental UI login's shared ui-token digest keeps its alias and team but names no owner
  • Each spend-log scan runs inside a transaction with a five-second statement timeout, so a window too large for the unindexed table falls back to nameless rows for that window instead of holding up usage reads
  • No migration, no new table, three usage paths pick it up

User Flow

Before: an admin checking usage after a teammate used a CLI session token sees a bare key hash with no alias or email

  1. A developer signs in with litellm-proxy login and gets a 24-hour session token instead of a virtual key
  2. They send POST https://litellm-domain/v1/chat/completions with Authorization: Bearer <session token> and "model": "gpt-4o-mini", and get a 200 with the reply
  3. The admin calls GET https://litellm-domain/user/daily/activity?start_date=2026-09-08&end_date=2026-09-08 with the master key: the row for that key comes back with "key_alias": null and "user_email": null
  4. The admin opens https://litellm-domain/ui/?page=new_usage, Key Activity tab: the row is labeled key-hash-d8c5b4eebd89..., so nobody can tell whose spend it is

After: the same row carries the developer's alias and email in the API and on the Usage page

  1. A developer signs in with litellm-proxy login and gets a 24-hour session token instead of a virtual key
  2. They send POST https://litellm-domain/v1/chat/completions with Authorization: Bearer <session token> and "model": "gpt-4o-mini", and get a 200 with the reply
  3. The admin calls GET https://litellm-domain/user/daily/activity?start_date=2026-09-08&end_date=2026-09-08 with the master key: the row now comes back with "key_alias": "cli-session-repro-user-6852" and "user_email": "repro6852@example.com"
  4. The admin opens https://litellm-domain/ui/?page=new_usage, Key Activity tab: the row is labeled cli-session-repro-user-6852

Relevant issues

Linear ticket

Resolves LIT-6852

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/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
  • 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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 2 on port 52245 against a local Postgres, one model gpt-4o-mini -> openai/gpt-4o-mini (real OpenAI spend), master key in $LITELLM_MASTER_KEY. A CLI session token for user repro6852@example.com with alias cli-session-repro-user-6852 sits in $CLI_SESSION_TOKEN; its spend rows land under key hash d8c5b4eebd89.... A normal virtual key with alias normal-alias-6852 and 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 legs

Before (ee1a640)

Session token request, then the usage APIs

  1. Command:
    curl -s http://localhost:52245/v1/chat/completions -H "Authorization: Bearer $CLI_SESSION_TOKEN" -H 'Content-Type: application/json' \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply with the single word: before"}],"max_tokens":5}' \
      | jq -c '{id, model, content: .choices[0].message.content, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}'
    Output:
    {"id":"chatcmpl-ELvUdtq1wPskrghBMBOKJXp8pkyoR","model":"gpt-4o-mini","content":"before","usage":{"prompt_tokens":14,"completion_tokens":1}}
  2. Wait about 40 seconds for the spend batch to flush
  3. Command:
    curl -s "http://localhost:52245/user/daily/activity?start_date=2026-09-08&end_date=2026-09-08" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq '.results[] | {date, api_keys: (.breakdown.api_keys | map_values({key_alias: .metadata.key_alias, user_email: .metadata.user_email, requests: .metrics.api_requests}))}'
    Output (key hashes shortened):
    {
      "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 }
      }
    }
  4. Same read against /user/daily/activity/aggregated (same query, same jq):
    {
      "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

  1. Log in at http://localhost:52245/ui/login (username admin, password the master key), open http://localhost:52245/ui/?page=new_usage, click the Key Activity tab

  2. The session token's row is labeled key-hash-d8c5b4eebd89ce9de197e5d92d1c950731e27db82777620391218a0dfd4172f2 with 2 requests, while the virtual key's row reads normal-alias-6852

    pr40275-529b8706ee-lit6852-before-ui-key-activity.png

Every other daily activity route

  1. Command:
    for r in team/daily/activity team/daily/activity/aggregated tag/daily/activity organization/daily/activity customer/daily/activity end_user/daily/activity agent/daily/activity gateway/daily/activity; do
      printf '%-36s ' "/$r"; curl -s -o /dev/null -w 'HTTP %{http_code}\n' "http://localhost:52245/$r?start_date=2026-09-08&end_date=2026-09-08" -H "Authorization: Bearer $LITELLM_MASTER_KEY"
    done
    Output:
    /team/daily/activity                 HTTP 200
    /team/daily/activity/aggregated      HTTP 200
    /tag/daily/activity                  HTTP 200
    /organization/daily/activity         HTTP 200
    /customer/daily/activity             HTTP 200
    /end_user/daily/activity             HTTP 200
    /agent/daily/activity                HTTP 200
    /gateway/daily/activity              HTTP 200
    
  2. The team and tag routes carry the same d8c5b4eebd89... entry with key_alias: null, user_email: null; the other five have no rows for this day

After (529b870)

Session token request, then the usage APIs

  1. Command:
    curl -s http://localhost:52245/v1/chat/completions -H "Authorization: Bearer $CLI_SESSION_TOKEN" -H 'Content-Type: application/json' \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply with the single word: after"}],"max_tokens":5}' \
      | jq -c '{id, model, content: .choices[0].message.content, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}'
    Output:
    {"id":"chatcmpl-EM0shTUa1LpulCGdsWQDvOW5MMX74","model":"gpt-4o-mini","content":"after","usage":{"prompt_tokens":14,"completion_tokens":1}}
  2. Wait about 15 seconds for the spend batch to flush
  3. Command:
    curl -s "http://localhost:52245/user/daily/activity?start_date=2026-09-08&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq '.results[] | {date, api_keys: (.breakdown.api_keys | map_values({key_alias: .metadata.key_alias, user_email: .metadata.user_email, requests: .metrics.api_requests}))}'
    Output (key hashes shortened):
    {
      "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 }
      }
    }
    The two ui-token rows 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
  4. Same read against /user/daily/activity/aggregated (same query, same jq):
    {
      "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

  1. Log in at http://localhost:52245/ui/login (username admin, password the master key), open http://localhost:52245/ui/?page=new_usage, click the Key Activity tab

  2. The same row is now labeled cli-session-repro-user-6852 with 9 requests on 2026-09-08, the day the page shows by default, next to normal-alias-6852; the request above and the one from the previous leg landed after midnight UTC, on 2026-09-09

    pr40275-529b8706ee-lit6852-after9-ui-key-activity.png

Every other daily activity route

  1. Same loop as Before, printing the session key's alias where the route has a row for it:
    /team/daily/activity                 HTTP 200  session alias: cli-session-repro-user-6852
    /team/daily/activity/aggregated      HTTP 200  session alias: cli-session-repro-user-6852
    /tag/daily/activity                  HTTP 200  session alias: cli-session-repro-user-6852
    /organization/daily/activity         HTTP 200  session alias: -
    /customer/daily/activity             HTTP 200  session alias: -
    /end_user/daily/activity             HTTP 200  session alias: -
    /agent/daily/activity                HTTP 200  session alias: -
    /gateway/daily/activity              HTTP 200  session alias: -
    
  2. The team and tag routes carry user_email: "repro6852@example.com" on that row too; the other five still have no rows for this day

Two 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 literal ui-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

  1. Command:
    for u in alice bob; do
      curl -s http://localhost:52245/user/new -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
        -d "{\"user_id\":\"ui-$u-6852\",\"user_email\":\"ui-$u-6852@example.com\",\"user_role\":\"internal_user\",\"auto_create_key\":false}" | jq -c '{user_id, user_email}'
    done
    Output:
    {"user_id":"ui-alice-6852","user_email":"ui-alice-6852@example.com"}
    {"user_id":"ui-bob-6852","user_email":"ui-bob-6852@example.com"}
  2. Mint one experimental UI session token per user with the proxy's own ExperimentalUIJWTToken.get_experimental_ui_login_jwt_auth_token (the function the UI login calls) into $UI_TOKEN_alice and $UI_TOKEN_bob, then one real request each:
    for u in alice bob; do
      tok=UI_TOKEN_$u
      curl -s http://localhost:52245/v1/chat/completions -H "Authorization: Bearer ${(P)tok}" -H 'Content-Type: application/json' \
        -d "{\"model\":\"gpt-4o-mini\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with the single word: $u\"}],\"max_tokens\":5}" | jq -c '{id, model, content: .choices[0].message.content}'
    done
    Output:
    {"id":"chatcmpl-EM0sqFCVyrjWtdxUkeULFlx6OZLAx","model":"gpt-4o-mini","content":"alice"}
    {"id":"chatcmpl-EM0st0jW43JWL7Vh0BXCSefUWgWRK","model":"gpt-4o-mini","content":"bob"}
  3. Wait about 10 seconds for the spend batch to flush, then:
    curl -s "http://localhost:52245/user/daily/activity?start_date=2026-09-08&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq '.results[] | .breakdown.api_keys | with_entries(select(.key | startswith("c14b71ea"))) | map_values({key_alias: .metadata.key_alias, team_id: .metadata.team_id, user_email: .metadata.user_email, requests: .metrics.api_requests})'
    Output:
    {
      "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
      }
    }
    One object per day: the 2026-09-09 row holds this run's two requests and the two from the previous run, the 2026-09-08 row the two from the run before that
  4. The six spend rows behind that digest, straight from Postgres:
    23:45:15|ui-alice-6852|ui-token|litellm-dashboard
    23:45:18|ui-bob-6852|ui-token|litellm-dashboard
    00:27:56|ui-alice-6852|ui-token|litellm-dashboard
    00:27:59|ui-bob-6852|ui-token|litellm-dashboard
    00:55:19|ui-alice-6852|ui-token|litellm-dashboard
    00:55:22|ui-bob-6852|ui-token|litellm-dashboard
    
    The reader at 907c200 ran on the same rows returns ui-bob-6852, so every UI user's spend would have carried bob's email; at this tip the row keeps ui-token and litellm-dashboard and names nobody

Observations 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/activity routes plus /user/daily/activity/aggregated, the usage AI chat endpoint riding the same paths, and the Admin UI Key Activity label reading key_alias and user_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), and page_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 about key_alias or user_email; the run-ci label is on so they run anyway

Delta since 8c878f3: the spend-log reader is one DISTINCT ON pass per call that keeps only rows carrying an alias, user, or team, the digest gate also accepts hashed-jwt-<sha256> rows, and each worker caches hits and misses per digest and date window for ten minutes (two plain constants in litellm/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.getenv reads, 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-token digest 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), a hashed-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 unindexed LiteLLM_SpendLogs table 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), a hashed-jwt- digest live (unit tests only), the statement timeout firing against a production-sized table (verified with psql: SET LOCAL statement_timeout inside 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 shared ui-token digest 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 warnings

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Identity comes back only where spend logs carry alias, user, or team
  • Rows stay nameless where spend logs are off, external, or pruned
  • User agent analytics, cache activity, and exports still miss session tokens
  • LiteLLM_SpendLogs has no api_key index, so a usage read with unresolved digests scans the date window by startTime; 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 table
  • The experimental UI login's shared ui-token digest shows alias ui-token and team litellm-dashboard with no owner or email; it named nobody before this PR either
  • Deployments on JWT auth see the same relabel: hashed-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 email
  • Only the CLI session digest and the shared UI digest were driven live; the hashed-jwt- gate has unit tests only

Low

  • The QA token comes from the same function as litellm-proxy login, but the CLI login itself was not driven
  • A fresh session stays nameless for up to thirty seconds on one worker when a usage read lands between the daily-spend flush and the spend-log flush or the scan fails or times out; a second miss keeps it nameless for ten minutes
  • Every login mints a new digest, so Key Activity lists one cli-session-<user_id> row per login
  • A digest whose spend rows disagree on alias, team, or owner within the window names nothing for that field
  • The Usage page loads 1000 rows per page and each page's dates form their own window, so a long range can scan once per page

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

Note

Medium Risk
Adds bounded but potentially heavy LiteLLM_SpendLogs scans 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 startTime window from the page’s dates and calls recover_key_metadata_from_spend_logs, which scans LiteLLM_SpendLogs for alias, team, and owner fields (including hashed-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 UI ui-token keep 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.

…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.
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit6852_spend_attribution (529b870) with litellm_internal_staging (754a2af)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR recovers aliases, teams, and owners for unresolved session-token and hashed-JWT digests by consulting spend logs within the activity date window.

  • Adds bounded, transactional spend-log scans with a five-second PostgreSQL statement timeout.
  • Requires each recovered field to agree across all non-empty values for a digest.
  • Adds per-worker hit and miss caching plus serialization of concurrent recovery scans.
  • Integrates recovery into the daily activity aggregation paths and adds focused unit coverage.

Confidence Score: 5/5

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

Important Files Changed

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

Comment on lines +38 to +41
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

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.

P2 Spend lookup lacks indexing Aggregated ranges query and sort spend rows without an api_key-leading index, which can increase reporting latency on large windows.

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.

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

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.

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

codecov Bot commented Sep 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@devin-ai-integration

devin-ai-integration Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Devin e2e QA

Tested at: 529b870
Session: https://app.devin.ai/sessions/a57e81bbda2d4be89c3e8b9b99f7bdd3

Shared setup for both legs: proxy booted from a detached worktree with --num_workers 2 on port 47311 (checked free before binding) against a local Postgres database litellm_lit6852, one model gpt-4o-mini -> openai/gpt-4o-mini (real OpenAI spend), master key in $LITELLM_MASTER_KEY. A CLI session token for user repro-user-6852 (repro6852@example.com) was minted through ExperimentalUIJWTToken.get_cli_jwt_auth_token, the same encrypted-session path litellm-proxy login uses, and sits in $CLI_SESSION_TOKEN; its spend rows land under key hash baac0069a87f.... A normal virtual key with alias normal-alias-6852 (hash 42e86bec1a3f...) and one master-key request were sent on the same day (2026-09-09) as controls. The Before leg ran at the merge base, then the same worktree was checked out at the branch tip and the proxy rebooted against the same database; nothing else changed between legs. This is a rerun of the earlier QA (which passed at 8c878f3) against the current tip, on a fresh day so the rows below are only the ones this run produced

Before (ee1a640)

Session token request, then the usage APIs

  1. Command:
    curl -s http://localhost:47311/v1/chat/completions -H "Authorization: Bearer $CLI_SESSION_TOKEN" -H 'Content-Type: application/json' \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply with the single word: before"}],"max_tokens":5}' \
      | jq -c '{id, model, content: .choices[0].message.content, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}'
    Output:
    {"id":"chatcmpl-EM0z3qutfdDoP8F97x6Q03vL1p46U","model":"gpt-4o-mini","content":"Before","usage":{"prompt_tokens":14,"completion_tokens":1}}
    The two control requests (same body, Authorization: Bearer $NORMAL_KEY and Authorization: Bearer $LITELLM_MASTER_KEY) returned chatcmpl-EM0z3POC44Xez74aZgb4CCHs54Dwi and chatcmpl-EM0z4eeHL5AkV724x1UGQE7GS9DV2
  2. Wait about 45 seconds for the spend batch to flush
  3. Command:
    curl -s "http://localhost:47311/user/daily/activity?start_date=2026-09-09&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq '.results[] | {date, api_keys: (.breakdown.api_keys | map_values({key_alias: .metadata.key_alias, user_email: .metadata.user_email, requests: .metrics.api_requests}))}'
    Output:
    {
      "date": "2026-09-09",
      "api_keys": {
        "42e86bec1a3f0196985988778188425dc7ef341c0f9dfe5ac88a86466a134ef3": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 },
        "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 },
        "baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e": { "key_alias": null, "user_email": null, "requests": 1 }
      }
    }
  4. Same read against /user/daily/activity/aggregated (same query, same jq):
    {
      "date": "2026-09-09",
      "api_keys": {
        "42e86bec1a3f0196985988778188425dc7ef341c0f9dfe5ac88a86466a134ef3": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 },
        "baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e": { "key_alias": null, "user_email": null, "requests": 1 },
        "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 }
      }
    }
  5. The spend row itself carries the alias the API failed to surface:
    psql "$DATABASE_URL" -At -c "select api_key, metadata->>'user_api_key_alias', \"user\" from \"LiteLLM_SpendLogs\" where \"startTime\" >= '2026-09-09' order by \"startTime\""
    baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e|cli-session-repro-user-6852|repro-user-6852
    42e86bec1a3f0196985988778188425dc7ef341c0f9dfe5ac88a86466a134ef3|normal-alias-6852|repro-user-6852
    litellm_proxy_master_key||default_user_id
    

Usage page, Key Activity tab

  1. Log in at http://localhost:47311/ui/login (username admin, password the master key), open http://localhost:47311/ui/usage/, click the Key Activity tab

  2. The session token's row is labeled key-hash-baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e, while the virtual key's row reads normal-alias-6852 and the master key row reads key-hash-litellm_proxy_master_key (request counts include the previous day's run, which the default 7 day range covers)

    Before: Key Activity tab shows key-hash row

Every other daily activity route

  1. Command:
    for r in team/daily/activity team/daily/activity/aggregated tag/daily/activity organization/daily/activity customer/daily/activity end_user/daily/activity agent/daily/activity gateway/daily/activity; do
      printf '%-36s ' "/$r"; curl -s -o /dev/null -w 'HTTP %{http_code}\n' "http://localhost:47311/$r?start_date=2026-09-09&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY"
    done
    Output:
    /team/daily/activity                 HTTP 200
    /team/daily/activity/aggregated      HTTP 200
    /tag/daily/activity                  HTTP 200
    /organization/daily/activity         HTTP 200
    /customer/daily/activity             HTTP 200
    /end_user/daily/activity             HTTP 200
    /agent/daily/activity                HTTP 200
    /gateway/daily/activity              HTTP 200
    
  2. Command (CLI row on the team and tag routes):
    for r in team/daily/activity tag/daily/activity; do
      curl -s "http://localhost:47311/$r?start_date=2026-09-09&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
        | jq -c '[.results[].breakdown.api_keys["baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e"] | select(.) | {key_alias: .metadata.key_alias, user_email: .metadata.user_email}]'
    done
    Output:
    [{"key_alias":null,"user_email":null}]
    [{"key_alias":null,"user_email":null}]

After (529b870)

Session token request, then the usage APIs

  1. Command:
    curl -s http://localhost:47311/v1/chat/completions -H "Authorization: Bearer $CLI_SESSION_TOKEN" -H 'Content-Type: application/json' \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply with the single word: after"}],"max_tokens":5}' \
      | jq -c '{id, model, content: .choices[0].message.content, usage: {prompt_tokens: .usage.prompt_tokens, completion_tokens: .usage.completion_tokens}}'
    Output:
    {"id":"chatcmpl-EM11Y01Mv8KGRRfBl4jO0h2d4i8ut","model":"gpt-4o-mini","content":"after","usage":{"prompt_tokens":14,"completion_tokens":1}}
  2. Wait about 45 seconds for the spend batch to flush
  3. Command:
    curl -s "http://localhost:47311/user/daily/activity?start_date=2026-09-09&end_date=2026-09-09" -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
      | jq '.results[] | {date, api_keys: (.breakdown.api_keys | map_values({key_alias: .metadata.key_alias, user_email: .metadata.user_email, requests: .metrics.api_requests}))}'
    Output:
    {
      "date": "2026-09-09",
      "api_keys": {
        "42e86bec1a3f0196985988778188425dc7ef341c0f9dfe5ac88a86466a134ef3": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 },
        "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 },
        "baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 2 }
      }
    }
  4. Same read against /user/daily/activity/aggregated (same query, same jq):
    {
      "date": "2026-09-09",
      "api_keys": {
        "42e86bec1a3f0196985988778188425dc7ef341c0f9dfe5ac88a86466a134ef3": { "key_alias": "normal-alias-6852", "user_email": "repro6852@example.com", "requests": 1 },
        "baac0069a87f853a278e1bcdff2b55ba8a2994463f942b1b3a861e0a723bd13e": { "key_alias": "cli-session-repro-user-6852", "user_email": "repro6852@example.com", "requests": 2 },
        "litellm_proxy_master_key": { "key_alias": null, "user_email": null, "requests": 1 }
      }
    }
  5. Same psql query as Before now shows the second CLI row, still carrying cli-session-repro-user-6852; select count(*) from "LiteLLM_VerificationToken" where key_alias = 'cli-session-repro-user-6852' returns 0, so no key record was created for the session token. Five sequential reads of /user/daily/activity after the first one all returned 200 in 15 to 19 ms, so the per-worker cache added on this tip serves repeat reads without hitting the spend logs again

Usage page, Key Activity tab

  1. Log in at http://localhost:47311/ui/login (username admin, password the master key), open http://localhost:47311/ui/usage/, click the Key Activity tab

  2. The same row is now labeled cli-session-repro-user-6852, next to normal-alias-6852; the master key row is still key-hash-litellm_proxy_master_key

    After: Key Activity tab shows cli-session-repro-user-6852

Every other daily activity route

  1. Same loop as Before:
    /team/daily/activity                 HTTP 200
    /team/daily/activity/aggregated      HTTP 200
    /tag/daily/activity                  HTTP 200
    /organization/daily/activity         HTTP 200
    /customer/daily/activity             HTTP 200
    /end_user/daily/activity             HTTP 200
    /agent/daily/activity                HTTP 200
    /gateway/daily/activity              HTTP 200
    
  2. Same CLI-row loop as Before:
    [{"key_alias":"cli-session-repro-user-6852","user_email":"repro6852@example.com"}]
    [{"key_alias":"cli-session-repro-user-6852","user_email":"repro6852@example.com"}]

Observations from the run:

  • Master key rows stay a bare sentinel on both legs; unchanged by this PR
  • The organization, customer, end_user, agent and gateway routes returned no rows on either leg because the QA database has none of those entities
  • Two workers without Redis show the Redis banner on boot; unrelated

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment on lines +253 to +255
if cache.get_cache(missed_before) is not None:
cache.set_cache(key, KeyMetadataDict())
return

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.

P1 Repeated Miss Stays Stale

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.

Suggested change
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

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.

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

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.

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.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…t and name only unanimous alias, team, and owner
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

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

LGTM

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant