Repository navigation
feat(proxy): bounded daily activity routes (aggregated, search, model_top_keys, export, cache_leakage_keys) for all usage entities - #43408
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@greptileai review |
e10c691 to
806b2ba
Compare
ab940dd to
a98a220
Compare
|
@greptileai re review on 8536c8f329b326a5727e2548f6e7c2e83ad39872 (date validation now returns InvalidDateRange and raise_public maps the union with match + assert_never) |
|
bugbot run |
8536c8f to
a7b05c3
Compare
|
@greptileai re review on a7b05c3 (rebased onto the rewritten litellm_usage_repository tip 7b25632, no code change) |
|
bugbot run |
|
@greptileai re review on bd00c35521994b3f6d17bbeb7d06df9d0db3e7f2 (rebased onto main after #43398 merged as aa601ce, no code change) |
|
bugbot run |
|
@greptileai re review on dbbf22e79547777c5082d8f41ba77878b09662b7 (adds the exhaustive assert_never arm CodeQL asked for in _permitted_daily_activity_agent_ids, nothing else) |
|
bugbot run |
|
@greptileai re review on ef4c5f7d88e5d85124315b2bd7b8ea73dea630fa (CodeQL kept flagging the match in _permitted_daily_activity_agent_ids, so it is now two early returns) |
|
bugbot run |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@greptileai re review on 02d0337 (same patch as ef4c5f7d88, rebased onto the current main tip 339f5b6) |
|
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 02d0337. Configure here.
TLDR
Problem this solves:
/…/daily/activity?page=Ninto the browserHow it solves it:
/{entity}/daily/activity/aggregated/keyspages ranked key totals so the dashboard can list every keyThe stack replaces #41293 instead of building on it; its revert (#43596) is already in main
Files changed
Diff is against
main(layer 1 merged as #43398, commit aa601ce). Test files are left out of this table.litellm/proxy/management_endpoints/daily_activity_routes.pyregister_daily_activity_routes(router, resolver)registers aggregated,/keys,/search,/model_top_keys,/exportand (user only)/cache_leakage_keysfor one entity. Bounds areQuery(ge=1, le=...)fromlitellm.constants;ScopeDeniedbecomes a 403/404HTTPExceptionin one place; export reads the first row before returning theStreamingResponseso a failing query is a JSON error, not a truncated filelitellm/proxy/management_endpoints/daily_activity_scopes.pyEntityQuery,ResolvedScope,ScopeDeniedand the six resolvers (user, team, tag, organization, customer, agent). Each one reuses the entity's existing auth rules and returns the entity ids and api keys the caller may see; an empty allowed set stays empty and the SQL rendersFALSElitellm/proxy/management_endpoints/common_daily_activity.pyScopeDenied,InvalidDateRangeandraise_public(exhaustive match over the error union) so every family reports the same structured error;spend_logs_windowrenamed from its private form because the new module uses itlitellm/proxy/management_endpoints/internal_user_endpoints.py/user/daily/activity/aggregatedhandler is replaced by the factory registration with the same path, params and response shapelitellm/proxy/management_endpoints/team_endpoints.py/team/daily/activity/aggregated; the team scope helper now also owns the member-key filterlitellm/proxy/management_endpoints/organization_endpoints.pylitellm/proxy/management_endpoints/customer_endpoints.py/end_user/...aliases registered hidden from OpenAPIlitellm/proxy/management_endpoints/tag_management_endpoints.pylitellm/proxy/agent_endpoints/endpoints.py"agents"feature access, shared with the new familieslitellm/proxy/proxy_server.pylitellm/proxy/_types.pybackend/routes/allowlist.pylitellm/types/proxy/management_endpoints/common_daily_activity.pyDailyActivityKeyPageResponse,DailyActivityKeySearchResponse,DailyActivityModelTopKeysResponse,ExportType,ExportFormat. Leaf module: stdlib,litellm.typesand pydantic only, nolitellm.proxyimportterraform/provider/tools/endpointaudit/coverage_allowlist.txtlitellm/proxy/_lazy_openapi_snapshot.jsonpython -m litellm.proxy._lazy_openapi_snapshotui/litellm-dashboard/src/lib/http/schema.d.tsnpm run gen:api; mostly operation reordering from the new router plus the new pathsStack
Layer 2 of 3: routes. Layer 1 #43398 (LIT-8897) merged into main as aa601ce, so this PR now targets main directly; head bd00c35521 is the same single commit rebased onto that merge, no code change. Layer 3 (UI) LIT-8899 stacks on this branch
Route table
All routes are
GET. Shared query params:start_date,end_date,model,api_key,timezone. Aggregated addsapi_key_limit(1 to 1000, default 100), which also bounds each entity's key breakdown;metadata.entity_total_api_keyscarries each entity's full key count. Search addssearchandlimit(1 to 100, default 100), model top keys addsmodel_group,by_model_groupandlimit(1 to 100, default 5), cache leakage addslimit(1 to 100, default 20), key page addsoffset(0 or more, default 0) andlimit(1 to 100, default 50), export addsexport_type(daily,daily_with_keys,daily_with_models,daily_with_users) andformat(csv,json). Out-of-range limits return 422/user/daily/activity/aggregated/user/daily/activity/aggregated/search/user/daily/activity/aggregated/model_top_keys/user/daily/activity/exportuser_id,include_current_utc_day/team/daily/activity/aggregated/team/daily/activity/aggregated/search/team/daily/activity/aggregated/model_top_keys/team/daily/activity/exportteam_ids,exclude_team_ids/tag/daily/activity/aggregated/tag/daily/activity/aggregated/search/tag/daily/activity/aggregated/model_top_keys/tag/daily/activity/exporttags/organization/daily/activity/aggregated/organization/daily/activity/aggregated/search/organization/daily/activity/aggregated/model_top_keys/organization/daily/activity/exportorganization_ids,exclude_organization_ids/customer/daily/activity/aggregated/customer/daily/activity/aggregated/search/customer/daily/activity/aggregated/model_top_keys/customer/daily/activity/exportend_user_ids,exclude_end_user_ids/agent/daily/activity/aggregated/agent/daily/activity/aggregated/search/agent/daily/activity/aggregated/model_top_keys/agent/daily/activity/exportagent_ids,exclude_agent_idsEvery entity also gets
/{entity}/daily/activity/aggregated/keys, which returnsDailyActivityKeyPageResponse(api_keys,total_api_keys,offset,limit). Each row carries key-level metrics and key metadata but no daily rows; the dashboard loads a key's daily rows from the existing aggregate withapi_key=<key>&api_key_limit=1when it is expanded. User only:/user/daily/activity/aggregated/cache_leakage_keysreturns the top cache-leakage keys. Customer routes are also served under hidden/end_user/...aliases. Responses: aggregated returns the existingSpendAnalyticsPaginatedResponsewithapi_key_limitand a completetotal_api_keys; search returnsDailyActivityKeySearchResponse; model top keys returnsModelTopKeysResponse; cache leakage returnsCacheLeakageKeysResponse; export streams CSV or a JSON array withCache-Control: no-storeand formula-escaped CSV cellsShape of the factory:
The existing
/user/daily/activity/aggregatedand/team/daily/activity/aggregatedhandlers moved into the factory with identical paths, params, operation ids, and response shapes (OpenAPI for all four legacy user and team paths is byte-identical to the base)User Flow
Before: an admin on a proxy with more keys than the top-N cap cannot find, rank, or export the keys beyond it
has_moreis falseAfter: the same admin gets bounded aggregates plus server-side search, ranking, and export for every entity
total_api_keyscounting every key in range/user,/tag,/organization,/customer, and/agent/customer/...gets 403Linear ticket
Resolves LIT-8898
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<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
Setup: a fresh Postgres database migrated by the proxy at boot (189 migrations), seeded with the fixture from
tests/integration/spend/_daily_activity_fixtures.pyon 2026-09-26 (5 keys plus the PTU sentinel, owneruser-1with emailuser@example.com). Base proxy on layer 1 (85e3e2ac31), head proxy on this branch (9d7376a413; since then layer 1 added two unreachableraiselines and the entity bound, which is proven below), each started withPYTHONPATHset to its own worktree and checked withpython -c "import litellm; print(litellm.__file__)". NoUSAGE_*env vars were set. Master key redactedLive verify on head a7b05c3 (rebased onto litellm_usage_repository tip 7b25632)
Proxy started from this checkout (
PYTHONPATH=~/repos/litellm,python -m litellm.proxy.proxy_cli --config config.yaml --port 4010) against a fresh Postgres database migrated at boot and seeded with two entities per table, three api keys, two models and two days (l2key_alpha_hash,l2key_beta_hash,l2key_gamma_hash; entityacarries alpha+beta, entitybcarries beta+gamma).MEMBERis a key for internal userl2-user-awho is a member ofl2-team-aonly.Every entity (user, team, tag, organization, customer, its hidden
end_useralias, agent) returned the same numbers for the same seed, so one row per family below stands for all seven prefixes:atotal_spend=5.25, key breakdown 2 then 1 keys,breakdown.entities=[a]a,api_key_limit=1total_spend=11.45, entities[a, b](user has no entity breakdown)/keys?limit=1&offset=1[l2key_beta_hash 0.75],total_api_keys=2/search?search=beta[l2key_beta_hash 0.75], metrics folded across both days/model_top_keys?model_group=gpt-4o-mini[l2key_alpha_hash 4.5],model=gpt-4o-mini/export?format=csvdate,entity_id,entity_alias,api_key,key_alias,user_id,...plus rows/export?format=json&export_type=daily_with_keys(user, agent){date: 2026-09-28, api_key: l2key_alpha_hash, spend: 1.5}/export?format=csv&export_type=daily_with_models(user)/export?export_type=modeldaily,daily_with_keys,daily_with_models,daily_with_users/cache_leakage_keys[l2key_alpha_hash 4.5, l2key_beta_hash 0.75]api_key_limit=1001less than or equal to 1000/keys?limit=0greater than or equal to 1Please provide start_date and end_dateFail-closed paths, the handler branch each one entered is named:
MEMBER, internal userl2-user-a)/user/daily/activity/aggregated?user_id=l2-user-a/user/.../aggregated?user_id=l2-user-b,/search,/exportNon-admin users can only view their own spend data./team/.../aggregated?team_ids=l2-team-a/team/.../aggregated,/keys,/model_top_keys,/exportwithteam_ids=l2-team-bUser does not belong to Team= l2-team-b/organization/.../aggregated,/exportwithorganization_ids=l2-org-aUser is not org_admin for Organization= l2-org-a./customer/.../aggregated,/end_user/.../searchuser_api_key_auth:Only proxy admin can be used ...; the admin-only customer resolver sits behind itInvalid proxy server token passedThe same
verify.shmatrix was rerun against a proxy restarted from a7b05c3 (litellm_headdatabase, same fixture): the 83-line output is byte-identical to the run on the previous head apart from timings (52 x 200, 12 x 403, 8 x 404, 4 x 401 for the admin-only customer routes with a member key, 9 x 422 for the deliberately invalidexport_type=modeland out-of-bounds limits).Key page date validation (Bugbot finding on 2b52cebb10, fixed in this head), admin key,
user_id=l2-user-a&limit=1:Date validation errors on head a7b05c3 (the Greptile P2 fix:
_date_range_errorreturnsInvalidDateRange | None,raise_publicmaps it to 400; the member fail-closed legs ride the same boundary):Team member key filter fails closed on the legacy paginated route too (Bugbot finding 2 on 0d396a6, checked, not a defect on this base): member key owns no key with spend in
l2-team-a,start_date=2026-09-28&end_date=2026-09-29:Local gates on a7b05c3 against
origin/litellm_usage_repository:scripts/ruff_strict_gate.py,scripts/type_discipline_gate.py,scripts/test_quality_gate.py,scripts/type_check_gate.pyall report OK.tests/unit/proxy/management_endpoints/test_activity_tenant_scoping.py(9 passed, includes the new fail-closed team filter test) andtests/unit/proxy/management_endpoints/test_daily_activity_routes.pyandtests/integration/spend/test_daily_activity_routes.py(3 tests, real proxy, Postgres, Redis) pass.Before (85e3e2ac31)
curl -s -H "Authorization: Bearer $KEY" 'localhost:4000/user/daily/activity/aggregated?start_date=2026-09-26&end_date=2026-09-26&api_key_limit=3'returnsHTTP 200withapi_key_limit=100and 5 keys, so the request param is ignored thereAfter (9d7376a413)
api_key_limit=0/1001api_key_limit=1000api_key_limit=1000,total_api_keys=5, 5 keys,total_spend=1273.0limit=0/limit=101limit=2limit=0/limit=101limit=2model-popularlimit=0/limit=101limit=2alias-auser-1user@example.comsearch=curl -s -H "Authorization: Bearer $KEY" 'localhost:4000/team/daily/activity/export?export_type=daily_with_keys&format=csv&start_date=2026-09-26&end_date=2026-09-26'returnsHTTP 200and streams a header plus 5 key rows./tag/daily/activity/aggregated?api_key_limit=2returnsHTTP 200(the fixture seeds no tag rows, so results are empty)Entity breakdown bound, 1,200 keys
Setup: a fresh migrated Postgres database seeded with
generate_series: 1,200 keys, 30 days, 2 models per key-day, 12 teams of 100 keys, each key in 2 of 20 tags, 6 orgs, 24 customers of 50 keys. OLD proxy on the previous layer 2 head b3ce23f, NEW proxy on the layer 2 code at 550a626c22 (the head 6b0389d only changes a test helper and formatting), same database,PYTHONPATHchecked per worktree. Each call iscurl -s -o body -w '%{http_code} %{size_download} %{time_total}' -H "Authorization: Bearer $KEY" 'localhost:<port>/<entity>/daily/activity/aggregated?start_date=...&end_date=...[&api_key_limit=1000]'/team/daily/activity/aggregated/team/daily/activity/aggregated/tag/daily/activity/aggregated/tag/daily/activity/aggregated/organization/daily/activity/aggregated/organization/daily/activity/aggregated/customer/daily/activity/aggregated/customer/daily/activity/aggregated/user/daily/activity/aggregated(global control)api_keysbreakdownmetadata.entity_total_api_keysmatches an independentCOUNT(DISTINCT api_key)per entity (sentinel excluded) for all 62 entitiesapi_key_limit=1001returns 422 on all four routesapi_key_limit=1000the payload barely shrinks because this seed has only 1,200 keysTests:
tests/test_litellm/proxy/management_endpoints/test_daily_activity_routes.pydrives every family for every entity through FastAPI with a fake repository that filters on the scope it is handed, so dropping a scope filter shows up as leaked rows (mutation-checked for all five families), and covers the 422 bounds.tests/integration/spend/test_daily_activity_routes.pyruns against a real proxy, Postgres, and Redis with more keys than the requested limit, and checks the legacy user and team responses against golden fixturesKey page (proxy on the layer 3 commit 3de7231ddd; the route code there is the same as this head, the later commits and this rebase changed no handler)
Same 131-key, 30-day seed the UI proof on #43409 uses
offset=0&limit=50total_api_keys=131, 19,776 bytesoffset=100&limit=50total_api_keys=131offset=500&limit=50total_api_keys=131offset=0&limit=100limit=101/offset=-1/limit=0offset=0&limit=50total_api_keys=131offset=0&limit=50total_api_keys=130api_key=usage-key-130&api_key_limit=1(key detail)The route tests cover response mapping for every entity and the 422 bounds. The integration tests page each entity's keys at limit 2 through a real proxy and compare them to an independent SQL ranking. They also show an internal user's pages leave out another user's key, asking for that user returns 403, and a key detail request for a key outside their scope comes back empty
Review taxonomy audit (A-BB)
Audited the full diff against the litellm PR-review caveat taxonomy before this push. Items with a changed line behind them:
/end_user/...aliases run the same customer resolver as/customer/...and sit in the same admin-only allowlist; verified above, both return 401 for a member keyScopeDeniedor an explicit allowed set; an empty set rendersFALSEin SQL and the repository returns before querying (test_empty_scope_filters_fail_closed)query.start_date or ""only feeds the missing-dates 400; numericrecord.x or 0sums treatNoneand0the same, which is the intended meaning. No allowlist isor-defaulted.update(,.append(,= [],= {})end_useralias gets them too;cache_leakage_keysis user only because the repository query is user keyed, written into the route table above/user/daily/activity/aggregated/keysskipped the format, ordering and 400-day checks its sibling routes apply. It now passesuser_aggregated=Falseand runsaggregated_date_range_error;test_user_key_page_rejects_bad_date_rangesfails on the previous head (3 failed) and passes on a7b05c3. Only the pre-existing/user/daily/activity/aggregatedkeeps the presence-only check it had on main_date_range_errorreturnsInvalidDateRange | None;raise_publictakesScopeDenied | InvalidDateRangeand maps it with match plusassert_never, pinned bytest_raise_public_maps_invalid_date_range_to_400resolve_team_daily_activity_scopereturns[]for a member with no keys or an unownedapi_key; the paginated/team/daily/activityhandler hands that toget_daily_activity, whosedaily_activity_scopemaps onlyNoneand""to "no filter", so[]becomesapi_keys=(), renderedAND FALSEin SQL andapi_key IN []in Prisma. The falsyif api_key:check the finding cites is the main handler layer 1 replaced. Pinned bytest_team_activity_member_without_matching_keys_queries_nothing, which fails under theNone if not api_keymutantapi_keytie-break on every ranked query; totals (total_api_keys,entity_total_api_keys) stay exact. The legacy user and team aggregated paths keep byte-identical OpenAPItests/belong to the per-entity handler tests the factory tests replace; each has a successor intest_daily_activity_routes.py(see test list in the file), none relaxed. No global state left behind: the fake repository is a fixturepy/cyclic-import: the shared response types live inlitellm/types/proxy/management_endpoints/common_daily_activity.py,grep -n "litellm.proxy"on it returns nothing;proxy_server.pygains one router includeX | Nonetyping (theOptional[str]strings are route description text carried over), bounds inlitellm/constants.py,schema.d.tsand the OpenAPI snapshot regenerated and the sync check is green, no new Pydantic field needs a Prisma columnNot applicable with reason: A, B (no cache or concurrent write path, routes are read-only), E, AA (no spend write), F, U-Y, BB (no provider adapter), G (streaming export is server to client only, no provider stream), M, N (no OAuth, MCP or secret), O (no guardrail), R (no helm, CI or migration change), L (no dashboard source change in this layer).
CI on bd00c35521
bd00c35521 is the a7b05c3 patch rebased onto main at aa601ce (the #43398 squash) with
git rebase --onto origin/main 7b256321b3, no conflicts, no code change;git rev-list --count origin/main..HEADis 1. Local gates on bd00c35521 againstorigin/main:ruff_strict_gate,type_discipline_gate,test_quality_gate,type_check_gateall OK, and the mapped unit files (test_daily_activity_routes.py,test_common_daily_activity.py,test_activity_tenant_scoping.py,test_daily_activity_sql.py,test_daily_activity_repository.py) pass, 243 tests. The live matrix and 400/403/404 legs below were captured on a7b05c3; the diff against main is byte-identical to the diff that head carried against its baseGreptile and Bugbot were re-anchored on bd00c35521 at 23:08 UTC. CodeQL applies now that the base is main. At 23:09 UTC the run on bd00c35521 is in progress: 79 check runs so far, 25 success, 1 skipped, 1 neutral, 1 waiting (
oauth), 51 running, 0 failures. Updated when it settlesCI on a7b05c3
a7b05c3 is the same patch as 8536c8f329 rebased onto the rewritten
litellm_usage_repositorytip 7b25632 (Layer 1 squashed its branch, which is what GitHub reported as a conflict). The rebase applied cleanly with no code change. At 22:07 UTC CI on the new head finished: 104 check runs, 97 success, 1 skipped, 1 neutral (Cursor Bugbot), 0 failures, 1 waiting (oauth, the test-mcp-oauth-e2e environment needs a human approval).schema-migrationpassed on this head, as expected once the base picked up a14af73On the previous head 8536c8f329 the run finished at 101 checks, 97 success, 1 skipped, 1 waiting, 1 failure:
schema-migration, wheretests/proxy_migration_tests/test_prisma_toolchain.py::test_db_push_timeout_hint_names_the_per_command_budgetfails withRuntimeError: Cannot verify Lens data safety; refusing prisma db push. This PR does not touchlitellm-proxy-extras/ortests/proxy_migration_tests/, and the same test failed the same way on the old base tip 0e475ac, so it was inherited from the base, not caused here. The new base tip carries a14af73 (test(proxy-extras): run the db push timeout hint test without a database URL), so this red is expected to clear on a7b05c3Bots: Greptile re-reviewed a7b05c3 at 22:04 UTC and kept 5/5 (summary: no new actionable issue, last reviewed commit a7b05c3). Bugbot on a7b05c3 found one medium issue (agent routes missing from the RBAC allowlists), rebutted in-thread and recorded under Caveats; its review of 8536c8f329 found no issues. Earlier Greptile scores: 5/5 on 0d396a6 and 2286dc1652, 4/5 on 55462f7 with the P2 fixed above. Bugbot's earlier medium finding (key page date validation) was fixed and its team key filter finding rebutted in-thread with a live A/B and a regression test. CodeQL:
.github/workflows/codeql.ymlonly runs for pull requests intomain, so no analysis exists for this PR (0 workflow runs, 0 analyses on the merge ref, 0github-advanced-security[bot]review comments); it runs when the stack lands through the Layer 1 PRType
🆕 New Feature
✅ Test
Caveats (if any)
Medium
api_keynow must own that keysearch_keysreturns ids only, metrics come from a scoped aggregatemodel_top_keysandcache_leakage_keysreturnKeySpendMetrics(spend, tokens, requests, cache tokens) instead of the fullSpendMetrics, because the repositoryKeySpendRowdoes not carry savings or response-time fieldsLow
schema.d.tsdiff is mostly operation reordering from the new router, plus the new pathsAgent routes stay admin-only at the auth layer. The new
/agent/daily/activity/aggregated*and/agent/daily/activity/exportpaths are, like the pre-existing/agent/daily/activityroute on the base, not onself_managed_routes,management_routesorinternal_user_routes, so an internal_user key gets the sameOnly proxy admin can be used ...401 on all of them (verified live on a7b05c3). Bugbot flagged this on a7b05c3; widening agent activity to non-admin keys would be a policy change for the whole agent family, including the existing route, so it is left for a follow-up rather than slipped into this PRFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/3b06b4a9ca0b4579bc22a957b11ed0c9
Open in Devin Desktop: https://app.devin.ai/desktop/session/3b06b4a9ca0b4579bc22a957b11ed0c9?variant=devin
Requested by: @yassin-berriai
Note
Medium Risk
Read-only spend endpoints with expanded surface area and centralized scoping; incorrect resolver or allowlist behavior could expose another tenant's usage data, though fail-closed empty filters and dedicated tests mitigate this.
Overview
Adds a shared route factory that registers the same bounded usage analytics families for user, team, tag, organization, customer, and agent: non-paginated aggregated summaries, paginated key rankings (
/aggregated/keys), key search, per-model top keys, CSV/JSON export, and (users only) cache leakage keys. Handlers resolve scope through per-entity resolvers that reuse existing auth rules; empty allowed entity or API-key sets stay fail-closed instead of widening queries.Refactors duplicate logic out of entity-specific modules: user/team aggregated handlers move into the factory; team, org, customer, and agent daily activity gain shared
resolve_*_daily_activity_scopehelpers. Team members without full team view now get an empty key filter (not an unscoped query) when they own no keys or request another user's key. RBAC allowlists and the dashboard backend allowlist pick up the new/agent/daily/activity/*paths; OpenAPI/types/terraform audit lists are updated accordingly.Reviewed by Cursor Bugbot for commit 02d0337. Bugbot is set up for automated code reviews on this repo. Configure here.