Skip to content

feat(proxy): bounded daily activity routes (aggregated, search, model_top_keys, export, cache_leakage_keys) for all usage entities - #43408

Merged
yassin-berriai merged 1 commit into
mainfrom
litellm_usage_service
Oct 1, 2026
Merged

yassin-berriai merged 1 commit into
mainfrom
litellm_usage_service

Conversation

@devin-ai-integration

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Usage pages drain /…/daily/activity?page=N into the browser
  • Key search, export, and per-model top keys only see the top-N subset
  • Tag, org, customer, agent have no bounded aggregated endpoint

How it solves it:

  • One route factory registers six route families for six usage entities
  • /{entity}/daily/activity/aggregated/keys pages ranked key totals so the dashboard can list every key
  • Six explicit scope resolvers reuse each entity's existing auth rules
  • Every family runs on the same resolved scope and the layer 1 repository
  • Empty allowed entity or key sets fail closed instead of widening scope
  • Result bounds are query params with hardcoded maximums, so clients set them and no env var is added

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

File What changed and why
litellm/proxy/management_endpoints/daily_activity_routes.py New. register_daily_activity_routes(router, resolver) registers aggregated, /keys, /search, /model_top_keys, /export and (user only) /cache_leakage_keys for one entity. Bounds are Query(ge=1, le=...) from litellm.constants; ScopeDenied becomes a 403/404 HTTPException in one place; export reads the first row before returning the StreamingResponse so a failing query is a JSON error, not a truncated file
litellm/proxy/management_endpoints/daily_activity_scopes.py New. EntityQuery, ResolvedScope, ScopeDenied and 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 renders FALSE
litellm/proxy/management_endpoints/common_daily_activity.py ScopeDenied, InvalidDateRange and raise_public (exhaustive match over the error union) so every family reports the same structured error; spend_logs_window renamed from its private form because the new module uses it
litellm/proxy/management_endpoints/internal_user_endpoints.py The hand-written /user/daily/activity/aggregated handler is replaced by the factory registration with the same path, params and response shape
litellm/proxy/management_endpoints/team_endpoints.py Same for /team/daily/activity/aggregated; the team scope helper now also owns the member-key filter
litellm/proxy/management_endpoints/organization_endpoints.py Org admin and membership checks factored into a scope helper used by both the paginated route and the new families
litellm/proxy/management_endpoints/customer_endpoints.py Admin-only customer scope helper; /end_user/... aliases registered hidden from OpenAPI
litellm/proxy/management_endpoints/tag_management_endpoints.py Tag scope helper import for the new families
litellm/proxy/agent_endpoints/endpoints.py Agent scope resolution moved into a helper that checks "agents" feature access, shared with the new families
litellm/proxy/proxy_server.py Includes the daily activity router
litellm/proxy/_types.py New paths added to the internal-user, team-member and org-admin route allowlists
backend/routes/allowlist.py Agent daily activity paths allowed for the dashboard backend
litellm/types/proxy/management_endpoints/common_daily_activity.py DailyActivityKeyPageResponse, DailyActivityKeySearchResponse, DailyActivityModelTopKeysResponse, ExportType, ExportFormat. Leaf module: stdlib, litellm.types and pydantic only, no litellm.proxy import
terraform/provider/tools/endpointaudit/coverage_allowlist.txt The new routes listed for the endpoint coverage audit
litellm/proxy/_lazy_openapi_snapshot.json Regenerated with python -m litellm.proxy._lazy_openapi_snapshot
ui/litellm-dashboard/src/lib/http/schema.d.ts Regenerated with npm run gen:api; mostly operation reordering from the new router plus the new paths

Stack

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 adds api_key_limit (1 to 1000, default 100), which also bounds each entity's key breakdown; metadata.entity_total_api_keys carries each entity's full key count. Search adds search and limit (1 to 100, default 100), model top keys adds model_group, by_model_group and limit (1 to 100, default 5), cache leakage adds limit (1 to 100, default 20), key page adds offset (0 or more, default 0) and limit (1 to 100, default 50), export adds export_type (daily, daily_with_keys, daily_with_models, daily_with_users) and format (csv, json). Out-of-range limits return 422

Entity Aggregated Search Model top keys Export Entity params
User /user/daily/activity/aggregated /user/daily/activity/aggregated/search /user/daily/activity/aggregated/model_top_keys /user/daily/activity/export user_id, include_current_utc_day
Team /team/daily/activity/aggregated /team/daily/activity/aggregated/search /team/daily/activity/aggregated/model_top_keys /team/daily/activity/export team_ids, exclude_team_ids
Tag /tag/daily/activity/aggregated /tag/daily/activity/aggregated/search /tag/daily/activity/aggregated/model_top_keys /tag/daily/activity/export tags
Organization /organization/daily/activity/aggregated /organization/daily/activity/aggregated/search /organization/daily/activity/aggregated/model_top_keys /organization/daily/activity/export organization_ids, exclude_organization_ids
Customer (admin only) /customer/daily/activity/aggregated /customer/daily/activity/aggregated/search /customer/daily/activity/aggregated/model_top_keys /customer/daily/activity/export end_user_ids, exclude_end_user_ids
Agent /agent/daily/activity/aggregated /agent/daily/activity/aggregated/search /agent/daily/activity/aggregated/model_top_keys /agent/daily/activity/export agent_ids, exclude_agent_ids

Every entity also gets /{entity}/daily/activity/aggregated/keys, which returns DailyActivityKeyPageResponse (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 with api_key=<key>&api_key_limit=1 when it is expanded. User only: /user/daily/activity/aggregated/cache_leakage_keys returns the top cache-leakage keys. Customer routes are also served under hidden /end_user/... aliases. Responses: aggregated returns the existing SpendAnalyticsPaginatedResponse with api_key_limit and a complete total_api_keys; search returns DailyActivityKeySearchResponse; model top keys returns ModelTopKeysResponse; cache leakage returns CacheLeakageKeysResponse; export streams CSV or a JSON array with Cache-Control: no-store and formula-escaped CSV cells

Shape of the factory:

for resolver in (USER, TEAM, TAG, ORGANIZATION, CUSTOMER, AGENT):
    register_daily_activity_routes(router, resolver)
# each handler:
#   scope = await resolver.resolve(auth, entity_query, prisma_client)  # ResolvedScope | ScopeDenied -> 403/404
#   repository (Depends(get_daily_activity_repository)).aggregated / search_keys / model_top_keys / export_rows / cache_leakage_keys(scope, ...)

The existing /user/daily/activity/aggregated and /team/daily/activity/aggregated handlers 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

  1. They call GET https://litellm-domain/team/daily/activity/aggregated?team_ids=t1&start_date=...&end_date=... and get only the top 100 keys per day
  2. They call GET https://litellm-domain/team/daily/activity/aggregated/search?search=sk-... and get 404 Not Found
  3. They call GET https://litellm-domain/tag/daily/activity/aggregated or the organization, customer, agent equivalents and get 404 Not Found
  4. To export or see every key they must page through GET https://litellm-domain/team/daily/activity?page=N until has_more is false

After: the same admin gets bounded aggregates plus server-side search, ranking, and export for every entity

  1. GET https://litellm-domain/team/daily/activity/aggregated returns the top keys plus total_api_keys counting every key in range
  2. GET https://litellm-domain/team/daily/activity/aggregated/search?search=sk-... returns the matching key even when it is outside the top-N, with metrics summed across days
  3. GET https://litellm-domain/team/daily/activity/export?export_type=daily_with_keys&format=csv streams every row, not the top-N subset
  4. The same four calls work under /user, /tag, /organization, /customer, and /agent
  5. An internal user calling any of them still only sees their own user, their teams' keys, their tag keys, or orgs they admin; a non-admin calling /customer/... gets 403

Linear ticket

Resolves LIT-8898

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/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
  • 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

Setup: a fresh Postgres database migrated by the proxy at boot (189 migrations), seeded with the fixture from tests/integration/spend/_daily_activity_fixtures.py on 2026-09-26 (5 keys plus the PTU sentinel, owner user-1 with email user@example.com). Base proxy on layer 1 (85e3e2ac31), head proxy on this branch (9d7376a413; since then layer 1 added two unreachable raise lines and the entity bound, which is proven below), each started with PYTHONPATH set to its own worktree and checked with python -c "import litellm; print(litellm.__file__)". No USAGE_* env vars were set. Master key redacted

Live 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; entity a carries alpha+beta, entity b carries beta+gamma). MEMBER is a key for internal user l2-user-a who is a member of l2-team-a only.

R="start_date=2026-09-28&end_date=2026-09-29"
for ent in user team tag organization customer end_user agent; do
  curl -s -H "Authorization: Bearer $ADMIN" "localhost:4010/$ent/daily/activity/aggregated?$R&<entity filter>=l2-<ent>-a"
  curl -s -H "Authorization: Bearer $ADMIN" "localhost:4010/$ent/daily/activity/aggregated/keys?$R&...&limit=1&offset=1"
  curl -s -H "Authorization: Bearer $ADMIN" "localhost:4010/$ent/daily/activity/aggregated/search?$R&...&search=beta"
  curl -s -H "Authorization: Bearer $ADMIN" "localhost:4010/$ent/daily/activity/aggregated/model_top_keys?$R&...&model_group=gpt-4o-mini"
  curl -s -H "Authorization: Bearer $ADMIN" "localhost:4010/$ent/daily/activity/export?$R&...&format=csv"
done

Every entity (user, team, tag, organization, customer, its hidden end_user alias, agent) returned the same numbers for the same seed, so one row per family below stands for all seven prefixes:

Request (admin) HTTP Result, identical for all 7 prefixes
aggregated, entity a 200 2 days, total_spend=5.25, key breakdown 2 then 1 keys, breakdown.entities = [a]
aggregated, entity a, api_key_limit=1 200 same totals, breakdown capped at 1 key per day
aggregated, no entity filter 200 2 days, total_spend=11.45, entities [a, b] (user has no entity breakdown)
/keys?limit=1&offset=1 200 [l2key_beta_hash 0.75], total_api_keys=2
/search?search=beta 200 [l2key_beta_hash 0.75], metrics folded across both days
/model_top_keys?model_group=gpt-4o-mini 200 [l2key_alpha_hash 4.5], model=gpt-4o-mini
/export?format=csv 200 header date,entity_id,entity_alias,api_key,key_alias,user_id,... plus rows
/export?format=json&export_type=daily_with_keys (user, agent) 200 5 rows, first {date: 2026-09-28, api_key: l2key_alpha_hash, spend: 1.5}
/export?format=csv&export_type=daily_with_models (user) 200 header plus 5 rows
/export?export_type=model 422 enum rejects it: daily, daily_with_keys, daily_with_models, daily_with_users
user /cache_leakage_keys 200 [l2key_alpha_hash 4.5, l2key_beta_hash 0.75]
team aggregated api_key_limit=1001 422 less than or equal to 1000
team /keys?limit=0 422 greater than or equal to 1
team aggregated without dates 400 Please provide start_date and end_date

Fail-closed paths, the handler branch each one entered is named:

Request (MEMBER, internal user l2-user-a) HTTP Branch
/user/daily/activity/aggregated?user_id=l2-user-a 200 user resolver, own id, scoped to the key's own api_key
/user/.../aggregated?user_id=l2-user-b, /search, /export 403 user resolver: Non-admin users can only view their own spend data.
/team/.../aggregated?team_ids=l2-team-a 200 team resolver, member path, filtered to the member's own keys (0 rows, the seed's keys are not theirs)
/team/.../aggregated, /keys, /model_top_keys, /export with team_ids=l2-team-b 404 team resolver: User does not belong to Team= l2-team-b
/organization/.../aggregated, /export with organization_ids=l2-org-a 403 org resolver: User is not org_admin for Organization= l2-org-a.
/customer/.../aggregated, /end_user/.../search 401 route allowlist in user_api_key_auth: Only proxy admin can be used ...; the admin-only customer resolver sits behind it
any route with an unknown key 401 Invalid proxy server token passed

The same verify.sh matrix was rerun against a proxy restarted from a7b05c3 (litellm_head database, 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 invalid export_type=model and 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:

start_date=not-a-date&end_date=2026-09-29   400 {"detail":{"error":"start_date and end_date must be valid YYYY-MM-DD dates"}}
start_date=2020-01-01&end_date=2026-09-29   400 {"detail":{"error":"Date range must be at most 400 days"}}
start_date=2026-09-29&end_date=2026-09-28   400 {"detail":{"error":"end_date must be on or after start_date"}}
start_date=2026-09-28&end_date=2026-09-29   200 {"api_keys":[{"api_key":"l2key_alpha_hash","metrics":{"spend":4.5,...}}],"total_api_keys":2,"offset":0,"limit":1}

Date validation errors on head a7b05c3 (the Greptile P2 fix: _date_range_error returns InvalidDateRange | None, raise_public maps it to 400; the member fail-closed legs ride the same boundary):

ADMIN  /user/daily/activity/aggregated/keys?start_date=not-a-date&end_date=2026-09-29         400 start_date and end_date must be valid YYYY-MM-DD dates
ADMIN  /user/daily/activity/aggregated/keys?start_date=2020-01-01&end_date=2026-09-29         400 Date range must be at most 400 days
ADMIN  /team/daily/activity/aggregated/search?start_date=2026-09-29&end_date=2026-09-28       400 end_date must be on or after start_date
ADMIN  /user/daily/activity/aggregated?end_date=2026-09-29                                    400 Please provide start_date and end_date
ADMIN  /user/daily/activity/aggregated/keys?start_date=2026-09-28&end_date=2026-09-29         200 api_keys [l2key_gamma_hash ...]
MEMBER /organization/daily/activity/aggregated?...&organization_ids=l2-org-a                  403 User is not org_admin for Organization= l2-org-a.
MEMBER /team/daily/activity/aggregated?...&team_ids=l2-team-b                                 404 User does not belong to Team= l2-team-b
MEMBER /user/daily/activity/aggregated?...&user_id=l2-user-b                                  403 Non-admin users can only view their own spend data.

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:

MEMBER /team/daily/activity?team_ids=l2-team-a                             200 results 0 total_spend 0.0
MEMBER /team/daily/activity?team_ids=l2-team-a&api_key=l2key_alpha_hash    200 results 0 total_spend 0.0
MEMBER /team/daily/activity?team_ids=l2-team-a&api_key=l2key_beta_hash     200 results 0 total_spend 0.0
ADMIN  /team/daily/activity?team_ids=l2-team-a                             200 results 2 keys [alpha, beta] total_spend 5.25

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.py all report OK. tests/unit/proxy/management_endpoints/test_activity_tenant_scoping.py (9 passed, includes the new fail-closed team filter test) and tests/unit/proxy/management_endpoints/test_daily_activity_routes.py and tests/integration/spend/test_daily_activity_routes.py (3 tests, real proxy, Postgres, Redis) pass.

Before (85e3e2ac31)

  1. Search, model top keys, cache leakage keys and export are not registered on the base; this PR adds them
  2. 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' returns HTTP 200 with api_key_limit=100 and 5 keys, so the request param is ignored there

After (9d7376a413)

for q in 'user/daily/activity/aggregated?api_key_limit=0' 'user/daily/activity/aggregated?api_key_limit=1001' 'user/daily/activity/aggregated?api_key_limit=1000' \
         'team/daily/activity/aggregated/search?search=key&limit=0' '...&limit=101' '...&limit=2' \
         'team/daily/activity/aggregated/model_top_keys?model_group=model-popular&by_model_group=false&limit=0' '...&limit=101' '...&limit=2' \
         'user/daily/activity/aggregated/cache_leakage_keys?limit=0' '...?limit=101' '...?limit=2' \
         'team/daily/activity/aggregated/search?search=alias-a&limit=10' '...?search=user-1&limit=10' '...?search=user%40example.com&limit=10' '...?search=&limit=10'; do
  curl -s -H "Authorization: Bearer $KEY" "localhost:4000/$q&start_date=2026-09-26&end_date=2026-09-26"; done
Request HTTP Result
aggregated api_key_limit=0 / 1001 422 / 422 below 1 / above 1000
aggregated api_key_limit=1000 200 api_key_limit=1000, total_api_keys=5, 5 keys, total_spend=1273.0
search limit=0 / limit=101 422 / 422 below 1 / above 100
search limit=2 200 2 keys
model_top_keys limit=0 / limit=101 422 / 422 below 1 / above 100
model_top_keys limit=2 200 2 keys for model-popular
cache_leakage_keys limit=0 / limit=101 422 / 422 below 1 / above 100
cache_leakage_keys limit=2 200 2 keys
search by key alias alias-a 200 1 key
search by owner user id user-1 200 4 keys
search by owner email user@example.com 200 4 keys
search with empty search= 422 rejected

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' returns HTTP 200 and streams a header plus 5 key rows. /tag/daily/activity/aggregated?api_key_limit=2 returns HTTP 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, PYTHONPATH checked per worktree. Each call is curl -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]'

Route (admin, no entity filter) Limit OLD bytes / sec NEW bytes / sec Max keys in one entity-day OLD / NEW
/team/daily/activity/aggregated default (100) 31,743,648 / 4.80 12,505,837 / 2.75 100 / 9
/team/daily/activity/aggregated 1000 125,880,153 / 22.62 122,386,669 / 24.00 100 / 85
/tag/daily/activity/aggregated default (100) 52,922,232 / 6.49 14,446,156 / 2.41 120 / 12
/tag/daily/activity/aggregated 1000 147,580,207 / 26.43 140,592,954 / 23.12 120 / 101
/organization/daily/activity/aggregated default (100) 31,650,620 / 3.10 12,412,672 / 2.32 200 / 18
/organization/daily/activity/aggregated 1000 125,787,125 / 21.46 122,293,526 / 23.38 200 / 169
/customer/daily/activity/aggregated default (100) 31,936,727 / 3.59 12,699,496 / 1.87 50 / 9
/customer/daily/activity/aggregated 1000 126,073,232 / 21.67 122,580,057 / 22.77 50 / 50
/user/daily/activity/aggregated (global control) default (100) 10,563,930 / 1.87 10,563,959 / 1.86 no entity breakdown
  • Totals and every entity-day's spend and request count match between OLD and NEW. Spend agrees within 1e-9, and the last digits differ because Postgres sums floats in scan order
  • Every key in a NEW entity breakdown is also in the top-level api_keys breakdown
  • metadata.entity_total_api_keys matches an independent COUNT(DISTINCT api_key) per entity (sentinel excluded) for all 62 entities
  • api_key_limit=1001 returns 422 on all four routes
  • At api_key_limit=1000 the payload barely shrinks because this seed has only 1,200 keys

Tests: tests/test_litellm/proxy/management_endpoints/test_daily_activity_routes.py drives 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.py runs against a real proxy, Postgres, and Redis with more keys than the requested limit, and checks the legacy user and team responses against golden fixtures

Key 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

for p in user team tag; do for q in 'offset=0&limit=50' 'offset=100&limit=50' 'offset=500&limit=50' 'offset=0&limit=100' 'offset=0&limit=101' 'offset=-1&limit=50' 'offset=0&limit=0'; do
  curl -s -H "Authorization: Bearer $KEY" "localhost:4000/$p/daily/activity/aggregated/keys?$q&start_date=2026-08-30&end_date=2026-09-29"; done; done
Request HTTP Result
user offset=0&limit=50 200 50 keys, total_api_keys=131, 19,776 bytes
user offset=100&limit=50 200 31 keys, total_api_keys=131
user offset=500&limit=50 200 0 keys, total_api_keys=131
user offset=0&limit=100 200 100 keys
user limit=101 / offset=-1 / limit=0 422 / 422 / 422 above 100 / below 0 / below 1
team offset=0&limit=50 200 50 keys, total_api_keys=131
tag offset=0&limit=50 200 50 keys, total_api_keys=130
user aggregate api_key=usage-key-130&api_key_limit=1 (key detail) 200 9 daily rows, spend 9.0, 52,082 bytes

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:

  • D2, Z7 (alias before check): /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 key
  • D4, Z2 (lookup failure must not widen access): every resolver returns ScopeDenied or an explicit allowed set; an empty set renders FALSE in SQL and the repository returns before querying (test_empty_scope_filters_fail_closed)
  • X1, E5, Z1 (falsy fallbacks): query.start_date or "" only feeds the missing-dates 400; numeric record.x or 0 sums treat None and 0 the same, which is the intended meaning. No allowlist is or-defaulted
  • W1, W4: no caller-owned dict is mutated, no mutable default argument in the two new modules (grep on .update(, .append(, = [], = {})
  • F3, O4 (sibling surfaces): all six families are registered for all six entities through the one factory, and the hidden end_user alias gets them too; cache_leakage_keys is user only because the repository query is user keyed, written into the route table above
  • F3, O4 (Bugbot on 2b52cebb10, confirmed and fixed): the user key page called the scope resolver with the legacy presence-only date check, so /user/daily/activity/aggregated/keys skipped the format, ordering and 400-day checks its sibling routes apply. It now passes user_aggregated=False and runs aggregated_date_range_error; test_user_key_page_rejects_bad_date_ranges fails on the previous head (3 failed) and passes on a7b05c3. Only the pre-existing /user/daily/activity/aggregated keeps the presence-only check it had on main
  • Greptile P2 on 55462f7 (date validation threw directly), fixed in a7b05c3: _date_range_error returns InvalidDateRange | None; raise_public takes ScopeDenied | InvalidDateRange and maps it with match plus assert_never, pinned by test_raise_public_maps_invalid_date_range_to_400
  • D4, Z2, X1 (Bugbot on 0d396a6, checked, not applicable on this base): resolve_team_daily_activity_scope returns [] for a member with no keys or an unowned api_key; the paginated /team/daily/activity handler hands that to get_daily_activity, whose daily_activity_scope maps only None and "" to "no filter", so [] becomes api_keys=(), rendered AND FALSE in SQL and api_key IN [] in Prisma. The falsy if api_key: check the finding cites is the main handler layer 1 replaced. Pinned by test_team_activity_member_without_matching_keys_queries_nothing, which fails under the None if not api_key mutant
  • C (response completeness, shape, ordering, size): the bound is a caller-set query param with a hardcoded maximum, default 100, no env var; ordering has an api_key tie-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 OpenAPI
  • T1-T5, T17: the 35 assert lines removed under tests/ belong to the per-entity handler tests the factory tests replace; each has a successor in test_daily_activity_routes.py (see test list in the file), none relaxed. No global state left behind: the fake repository is a fixture
  • CodeQL py/cyclic-import: the shared response types live in litellm/types/proxy/management_endpoints/common_daily_activity.py, grep -n "litellm.proxy" on it returns nothing; proxy_server.py gains one router include
  • H1-H10: no docs in this repo, no new source comments, no em dashes or emoji in added text, X | None typing (the Optional[str] strings are route description text carried over), bounds in litellm/constants.py, schema.d.ts and the OpenAPI snapshot regenerated and the sync check is green, no new Pydantic field needs a Prisma column

Not 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..HEAD is 1. Local gates on bd00c35521 against origin/main: ruff_strict_gate, type_discipline_gate, test_quality_gate, type_check_gate all 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 base

Greptile 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 settles

CI on a7b05c3

a7b05c3 is the same patch as 8536c8f329 rebased onto the rewritten litellm_usage_repository tip 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-migration passed on this head, as expected once the base picked up a14af73

On the previous head 8536c8f329 the run finished at 101 checks, 97 success, 1 skipped, 1 waiting, 1 failure: schema-migration, where tests/proxy_migration_tests/test_prisma_toolchain.py::test_db_push_timeout_hint_names_the_per_command_budget fails with RuntimeError: Cannot verify Lens data safety; refusing prisma db push. This PR does not touch litellm-proxy-extras/ or tests/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 a7b05c3

Bots: 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.yml only runs for pull requests into main, so no analysis exists for this PR (0 workflow runs, 0 analyses on the merge ref, 0 github-advanced-security[bot] review comments); it runs when the stack lands through the Layer 1 PR

Type

🆕 New Feature
✅ Test

Caveats (if any)

Medium

  • Team member without full team view passing api_key now must own that key
    • Before, any key id was accepted and filtered inside their teams
  • Search does two repository calls: search_keys returns ids only, metrics come from a scoped aggregate
  • model_top_keys and cache_leakage_keys return KeySpendMetrics (spend, tokens, requests, cache tokens) instead of the full SpendMetrics, because the repository KeySpendRow does not carry savings or response-time fields

Low

  • schema.d.ts diff is mostly operation reordering from the new router, plus the new paths
  • Export prefetches the first row before streaming, so a failing first query returns 500; a failure on a later batch still truncates the body

Agent routes stay admin-only at the auth layer. The new /agent/daily/activity/aggregated* and /agent/daily/activity/export paths are, like the pre-existing /agent/daily/activity route on the base, not on self_managed_routes, management_routes or internal_user_routes, so an internal_user key gets the same Only 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 PR

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/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_scope helpers. 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.

@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

@CLAassistant

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Adds new daily activity API routes with scope resolution across multiple entity types.

The PR appears safe to merge; no outstanding finding or new actionable issue was identified.

Summary

The PR adds shared, scoped daily-activity routes for six usage entities, including bounded key pages, search, model-top-key reporting, and streaming exports.

  • Replaces the existing user and team aggregated handlers with factory-registered routes.
  • Adds scope resolvers, response types, route permissions, and corresponding tests.

Reviews (13) · Last reviewed commit: "feat(proxy): bounded daily activity rout..."

@codecov

codecov Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.10490% with 21 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...roxy/management_endpoints/daily_activity_routes.py 90.00% 19 Missing ⚠️
...roxy/management_endpoints/common_daily_activity.py 88.88% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

@greptileai review

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai re review on 8536c8f329b326a5727e2548f6e7c2e83ad39872 (date validation now returns InvalidDateRange and raise_public maps the union with match + assert_never)

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai re review on a7b05c3 (rebased onto the rewritten litellm_usage_repository tip 7b25632, no code change)

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

Stale Bugbot comment from a previous run.

Comment thread litellm/proxy/_types.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai re review on bd00c35521994b3f6d17bbeb7d06df9d0db3e7f2 (rebased onto main after #43398 merged as aa601ce, no code change)

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

Stale Bugbot comment from a previous run.

@codspeed

codspeed Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_usage_service (02d0337) with main (339f5b6)

Open in CodSpeed

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai re review on dbbf22e79547777c5082d8f41ba77878b09662b7 (adds the exhaustive assert_never arm CodeQL asked for in _permitted_daily_activity_agent_ids, nothing else)

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai re review on ef4c5f7d88e5d85124315b2bd7b8ea73dea630fa (CodeQL kept flagging the match in _permitted_daily_activity_agent_ids, so it is now two early returns)

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

Copy link
Copy Markdown
Contributor

@greptileai re review on 02d0337 (same patch as ef4c5f7d88, rebased onto the current main tip 339f5b6)

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

Stale Bugbot comment from a previous 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 02d0337. Configure here.

This branch had an error being deployed

1 failed deployment
e2e-changed — 02d03372 Deployed Oct 1, 2026 by yassin-berriai via oauth #2486
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants