Skip to content

fix(usage): page and search past the top-N keys the Usage page loads - #42836

Closed
devin-ai-integration[bot] wants to merge 10 commits into
mainfrom
litellm_lit8497_usage_key_search
Closed

devin-ai-integration[bot] wants to merge 10 commits into
mainfrom
litellm_lit8497_usage_key_search

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • Aggregated usage routes accept cursor and return metadata.next_cursor (keyset pagination)
  • "Load more keys" button on Global Usage and Team usage fetches the next page and merges it
  • GET /user/daily/activity/aggregated/search finds one key by alias or hash without paging
  • Initial bounded load and its performance stay exactly as they are

User Flow

Before: an admin with more than 100 keys cannot reach a low-spend key on the Usage page

  1. They open https://litellm-domain/ui/?page=usage, Key Activity tab, and see the note "Only the 100 highest-spend keys of 340 are loaded" with nothing to click
  2. They type the alias of a key that had traffic this week but is not in the top 100
  3. The panel shows "No keys match ... in this date range", even though the key has spend in the range
  4. GET https://litellm-domain/user/daily/activity/aggregated?start_date=...&end_date=... returns the same 100 keys on every call; there is no way to ask for the rest, and cursor=... is ignored

After: every key is reachable, by paging or by search

  1. They open https://litellm-domain/ui/?page=usage, Key Activity tab, and see "Only the 100 highest-spend keys of 340 are loaded" next to a "Load more keys" button
  2. They click it: "Loading more keys..." shows briefly, the note reads "Only the 200 highest-spend keys of 340 are loaded", and the new key cards appear under the existing ones; totals at the top do not change
  3. They click until the button disappears, and every key with spend in the range is on the page
  4. Alternatively they type the alias in the search box: "Searching all keys..." then that key's card, "Showing 1 of 101 keys"
  5. GET https://litellm-domain/user/daily/activity/aggregated?start_date=...&end_date=... now returns metadata.next_cursor; repeating the call with cursor=<that value> returns the next 100 keys and next_cursor: null on the last page. A malformed cursor returns 400 {"error": "Invalid cursor"}
  6. The same works on https://litellm-domain/ui/?page=usage in the Team view via GET /team/daily/activity/aggregated
  7. A non-admin who calls the search or aggregated route only ever gets keys under their own user, and passing another user_id returns 403

Relevant issues

Supersedes #42827 (its three commits are carried over with Yassin as author)

Affected release

regression in v1.103.0-rc.1 (introduced by #41293)

Linear ticket

Resolves LIT-8497

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)

Screenshots / Proof of Fix

Shared setup: local proxy on 127.0.0.1:4497 with Postgres and Redis, the integration suite's scripted OpenAI-compatible upstream on 127.0.0.1:8497, default USAGE_TOP_API_KEYS_LIMIT=100. One internal user owns 101 keys, 100 of them with one 20+20 token chat on an expensive model (daily spend 0.06 each) and one "needle" key with one chat on a cheap model (daily spend 0.0006). $MK is the master key, $U the user id

Before (5c738cc)

Paging past the top 100

  1. curl -s "http://127.0.0.1:4497/user/daily/activity/aggregated?start_date=2026-09-23&end_date=2026-09-25&timezone=0&user_id=$U" -H "Authorization: Bearer $MK" | jq '{next_cursor: .metadata.next_cursor, total_api_keys: .metadata.total_api_keys, keys_loaded: ([.results[].breakdown.api_keys] | add | length)}'
  2. {"next_cursor": null, "total_api_keys": 101, "keys_loaded": 100}, the needle key is not among the 100 and there is no cursor to continue with
  3. Adding &cursor=anything to the same call is ignored and returns the same 100 keys (the integration test tests/integration/spend/test_user_daily_activity_key_search.py::test_aggregated_key_pages_reach_every_key_through_cursor fails here at metadata["next_cursor"])

Searching for the missing key

  1. curl -s -w '\n%{http_code}\n' "http://127.0.0.1:4497/user/daily/activity/aggregated/search?search=needle&start_date=2026-09-23&end_date=2026-09-25&timezone=0" -H "Authorization: Bearer $MK"
  2. {"detail":"Not Found"} / 404

After (650dbf4)

Paging past the top 100

  1. Same curl as before
  2. {"next_cursor": "eyJzcGVuZCI6IDAuMDYsICJhcGlfa2V5IjogImZlYmU3MGZlNzEwOGI5NDEyMGY0ZWY2MDBjZjUwOTE0MTBmZjkzNTEwOTA2ZmUzY2MwZjBmMDcxZjIxOThjN2UifQ==", "total_api_keys": 101, "keys_loaded": 100}
  3. curl -s "http://127.0.0.1:4497/user/daily/activity/aggregated?start_date=2026-09-23&end_date=2026-09-25&timezone=0&user_id=$U&cursor=<next_cursor>" -H "Authorization: Bearer $MK" | jq '{next_cursor: .metadata.next_cursor, total_api_keys: .metadata.total_api_keys, keys: [.results[].breakdown.api_keys | to_entries[] | {alias: .value.metadata.key_alias, spend: .value.metrics.spend}]}'
  4. {"next_cursor": null, "total_api_keys": 101, "keys": [{"alias": "needle-b327685381fc4ef6a15ca1ce6448068b", "spend": 0.0006000000000000001}]}, the lowest-spend key arrives on page 2, total_api_keys and metadata.total_spend are the same on both pages
  5. curl -s -w '\nHTTP %{http_code}\n' "...&cursor=not-a-cursor" -H "Authorization: Bearer $MK" returns {"detail":{"error":"Invalid cursor"}} / HTTP 400
  6. The integration test above passes against this rig, as does the real-Postgres unit test that seeds 105 keys with two keys tied on spend exactly at the cutoff (page 1 keeps key-004, page 2 starts at key-005, the tiebreaker is the key hash)

Searching for the missing key

  1. curl -s "http://127.0.0.1:4497/user/daily/activity/aggregated/search?search=needle&start_date=2026-09-23&end_date=2026-09-25&timezone=0" -H "Authorization: Bearer $MK" | jq '[.results[].breakdown.api_keys | to_entries[] | {alias: .value.metadata.key_alias, spend: .value.metrics.spend}]'
  2. [{"alias": "needle-b327685381fc4ef6a15ca1ce6448068b", "spend": 0.0006}]; search=NEEDLE (case-insensitive) and search=<the key's sha256> return the same key, search=zzz-nomatch returns "results": []
  3. Same route with an internal user's key: another user's keys are not returned, and user_id=<other user> returns 403 {"error":"Non-admin users can only view their own spend data."}

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Cursor paging and "Load more keys" cover the two routes that cap keys: Global Usage (/user/daily/activity/aggregated) and Team usage (/team/daily/activity/aggregated); tag, org, customer and agent views drain the paginated routes, which never capped keys
  • Server search stays Global Usage only; the Team view reaches every key through "Load more keys"
  • Each extra page costs one more aggregated query of the same shape as the initial load; the browser holds every page the user loaded, which is opt-in per click
  • A key whose spend changes between two page fetches can move across the page boundary and be missed or repeated; the UI dedupes repeats by key hash

Low

  • The cursor is (spend, key hash) base64 encoded and is only meaningful with the same date range and filters it came from; a cursor reused with different filters just pages from that spend downward
  • Search results are capped at USAGE_TOP_API_KEYS_LIMIT by lifetime key spend; deleted keys are not found by search
  • A cursor whose spend is NaN or infinite, or whose key hash is empty, is rejected with 400 like any other malformed cursor
  • The prebuilt UI bundle is not rebuilt here; the weekly build-artifacts chore picks it up

REVIEWER MUST KNOW BEFORE APPROVING

  • _build_aggregated_sql_query gets an optional cursor; without it the SQL is the previous query plus two extra NULL columns and the params list is unchanged, so existing callers (including the AI usage chat) behave as before
  • The keyset predicate lives in a second CTE over the GROUP BY api_key aggregate, key_spend < $n OR (key_spend = $n AND api_key > $m), matching the existing ORDER BY SUM(spend) DESC, api_key total order; total_api_keys is counted before the predicate and next_cursor is emitted only when more than a page remains after it
  • has_more is deliberately untouched (the dashboard's page-drain hook reads it); the new field is next_cursor
  • New route /user/daily/activity/aggregated/search is in the internal-user and non-admin allowed route lists with the same self-only scoping as /user/daily/activity/aggregated

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

Link to Devin session: https://app.devin.ai/sessions/06bb3c21dcee4cca96dad7822b0beb57
Open in Devin Desktop: https://app.devin.ai/desktop/session/06bb3c21dcee4cca96dad7822b0beb57?variant=devin
Requested by: @kerry-berri

yassin-berriai and others added 4 commits September 24, 2026 00:36
The Key Activity panel on the Usage page only searched the top-spend
keys the aggregated endpoint loads. A new /user/daily/activity/aggregated/search
route matches verification tokens by hash, alias, or user id and aggregates
spend for the matches; the panel debounces to it when the loaded set is
truncated. Entity panels stay local-only.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 8ddf69f)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 379a69a)
…ote results

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
(cherry picked from commit 3e74d6d)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@CLAassistant

CLAassistant commented Sep 24, 2026 •

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 all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ kerry-berri
❌ yassin-berriai
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.67089% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...xy/management_endpoints/internal_user_endpoints.py 86.84% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The pagination and cursor-hardening changes look correct, but the unresolved repository requirement against direct request-path database queries must be satisfied before merging

Findings

  1. P2 Request-path database access ▶

Summary

Adds keyset pagination to user and team usage aggregation, plus global key search and dashboard controls for reaching keys outside the initial top-spend page

  • Aggregated usage routes accept opaque cursors and return metadata.next_cursor
  • The dashboard merges additional key pages without changing overall totals
  • Global usage can search keys by hash, alias, or user ID while preserving caller scope
  • The latest changes reject non-finite cursor spend values and empty key hashes

Reviews (6) · Last reviewed commit: "fix(usage): reject non-finite spend and ..."

Comment on lines +3184 to +3188
matched_keys: Final = await VerificationTokenRepository(prisma_client).table.find_many(
where=where,
take=USAGE_TOP_API_KEYS_LIMIT,
order={"spend": "desc"}, # mutable-ok: prisma serializes order, keep it a plain dict
)

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 Request-path database access

This constructs a repository and queries it per request, violating the helper-only database-access requirement that must be satisfied before merging

Rule Used: What: In critical path of request, there should be no direct db queries. Only allow them to be made via the get_team/get_user/get_key object helper functions Why: prevent db regressions (source)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is an admin management route, not the LLM request path. It queries the same way the sibling aggregated routes in this file already do

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.

You're right. This is an authenticated management/analytics route, not the critical LLM request path covered by the helper-only database-access rule. The sibling aggregated endpoints in this module already use the same repository access pattern, and the direct VerificationTokenRepository lookup is necessary for search. Authorization is still enforced through _resolve_user_daily_activity_entity_id.

I’m withdrawing this finding.

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

@codspeed

codspeed Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_lit8497_usage_key_search (650dbf4) with main (58e41e6)1

Open in CodSpeed

Footnotes

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

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration devin-ai-integration Bot changed the title fix(usage): search keys beyond the top-N subset the Usage page loads fix(usage): page and search past the top-N keys the Usage page loads Sep 24, 2026
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@kerry-berri kerry-berri added the backport-stable P0 regression fix only (Urgent ticket): cherry-pick onto the baking rc line before the stable tag label Sep 24, 2026
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

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

Stale Bugbot comment from a previous run.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-berri

Copy link
Copy Markdown
Contributor

@greptileai

@kerry-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 650dbf4. Configure here.

@yassin-berriai

Copy link
Copy Markdown
Contributor

This is duplicate of #42827

This branch had an error being deployed

1 failed deployment
e2e-changed — 650dbf49 Deployed Sep 24, 2026 by devin-ai-integration[bot] via oauth #732
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-stable P0 regression fix only (Urgent ticket): cherry-pick onto the baking rc line before the stable tag

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants