Repository navigation
fix(usage): page and search past the top-N keys the Usage page loads - #42836
devin-ai-integration[bot] wants to merge 10 commits into
Conversation
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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
bugbot run |
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
| 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 | ||
| ) |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
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>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
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 650dbf4. Configure here.
|
This is duplicate of #42827 |
TLDR
Problem this solves:
How it solves it:
cursorand returnmetadata.next_cursor(keyset pagination)GET /user/daily/activity/aggregated/searchfinds one key by alias or hash without pagingUser Flow
Before: an admin with more than 100 keys cannot reach a low-spend key on the Usage page
cursor=...is ignoredAfter: every key is reachable, by paging or by search
metadata.next_cursor; repeating the call withcursor=<that value>returns the next 100 keys andnext_cursor: nullon the last page. A malformed cursor returns 400{"error": "Invalid cursor"}user_idreturns 403Relevant 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
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)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).$MKis the master key,$Uthe user idBefore (5c738cc)
Paging past the top 100
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)}'{"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&cursor=anythingto 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 atmetadata["next_cursor"])Searching for the missing key
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"{"detail":"Not Found"}/404After (650dbf4)
Paging past the top 100
curlas before{"next_cursor": "eyJzcGVuZCI6IDAuMDYsICJhcGlfa2V5IjogImZlYmU3MGZlNzEwOGI5NDEyMGY0ZWY2MDBjZjUwOTE0MTBmZjkzNTEwOTA2ZmUzY2MwZjBmMDcxZjIxOThjN2UifQ==", "total_api_keys": 101, "keys_loaded": 100}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}]}'{"next_cursor": null, "total_api_keys": 101, "keys": [{"alias": "needle-b327685381fc4ef6a15ca1ce6448068b", "spend": 0.0006000000000000001}]}, the lowest-spend key arrives on page 2,total_api_keysandmetadata.total_spendare the same on both pagescurl -s -w '\nHTTP %{http_code}\n' "...&cursor=not-a-cursor" -H "Authorization: Bearer $MK"returns{"detail":{"error":"Invalid cursor"}}/HTTP 400key-004, page 2 starts atkey-005, the tiebreaker is the key hash)Searching for the missing key
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}]'[{"alias": "needle-b327685381fc4ef6a15ca1ce6448068b", "spend": 0.0006}];search=NEEDLE(case-insensitive) andsearch=<the key's sha256>return the same key,search=zzz-nomatchreturns"results": []user_id=<other user>returns403 {"error":"Non-admin users can only view their own spend data."}Type
🐛 Bug Fix
Caveats (if any)
Medium
/user/daily/activity/aggregated) and Team usage (/team/daily/activity/aggregated); tag, org, customer and agent views drain the paginated routes, which never capped keysLow
(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 downwardUSAGE_TOP_API_KEYS_LIMITby lifetime key spend; deleted keys are not found by searchREVIEWER MUST KNOW BEFORE APPROVING
_build_aggregated_sql_querygets an optionalcursor; 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 beforeGROUP BY api_keyaggregate,key_spend < $n OR (key_spend = $n AND api_key > $m), matching the existingORDER BY SUM(spend) DESC, api_keytotal order;total_api_keysis counted before the predicate andnext_cursoris emitted only when more than a page remains after ithas_moreis deliberately untouched (the dashboard's page-drain hook reads it); the new field isnext_cursor/user/daily/activity/aggregated/searchis in the internal-user and non-admin allowed route lists with the same self-only scoping as/user/daily/activity/aggregatedFinal Attestation
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