Skip to content

revert(usage): remove the top-N key cap, its follow-ups and the daily global spend rollup code from rc/1.104.0 - #43385

Merged
yuneng-berri merged 6 commits into
rc/1.104.0from
litellm_rc_1_104_0_revert_top_n
Sep 27, 2026
Merged

yuneng-berri merged 6 commits into
rc/1.104.0from
litellm_rc_1_104_0_revert_top_n

Conversation

@yuneng-berri

@yuneng-berri yuneng-berri commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

User Flow

Before: an admin on rc/1.104.0 with more keys than the cap sees only the top-spend keys on the Usage pages

  1. The admin opens http://localhost:4000/ui/?page=usage with a date range covering more than 100 active keys
  2. The key widgets list only the top 100 keys by spend, and the page notes that only the top-spend keys were loaded
  3. The admin searches for a key outside the top 100 and the page calls a separate key search endpoint to find it
  4. The admin picks Export and the global export is blocked because the key cap was reached, while the team export goes through a separate server-side endpoint

After: the same admin sees every key again, the way the Usage pages behaved before #41293

  1. The admin opens http://localhost:4000/ui/?page=usage with the same date range
  2. The key widgets cover all keys, with no top-N note
  3. Key search filters the full set already on the page
  4. Export downloads the full data from the page

Affected release

Regression since v1.103.0-rc.1, carried into rc/1.104.0

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)

No new tests since this is a revert. The reverted tests go away with the code they covered

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Shared setup: a local Postgres, one proxy config with a single gpt-5.4-nano deployment, 120 virtual keys in one team created through /key/generate, and one real /v1/chat/completions call per key (120 x 200). The daily spend tables hold 120 distinct keys. The same database is served by the rc tip, by this branch, and by main right before #41293 (6e3b6d6), one at a time on port 4077. The UI runs from each tree's source with npm run dev pointed at that proxy

D=$(date -u +%F)
curl -s "localhost:4077/user/daily/activity/aggregated?start_date=$D&end_date=$D" -H "Authorization: Bearer sk-1234"
curl -s "localhost:4077/team/daily/activity/aggregated?team_ids=qa-team&start_date=$D&end_date=$D" -H "Authorization: Bearer sk-1234"
curl -s -o /dev/null -w "%{http_code}" "localhost:4077/team/daily/activity/export?team_ids=qa-team&start_date=$D&end_date=$D" -H "Authorization: Bearer sk-1234"

Before (95f33f4)

API

  1. User aggregated activity: 100 keys in the breakdown, metadata.api_key_limit: 100, metadata.total_api_keys: 120
  2. Team aggregated activity: the same 100 of 120 keys with the same cap metadata
  3. /user/daily/activity/aggregated/search, /team/daily/activity/aggregated/search and /team/daily/activity/export answer 200

Usage page

  1. Open http://localhost:3000/usage, set the range to include today, click Key Activity
  2. The panel reads "Showing 100 of 100 keys" next to "Only the 100 highest-spend keys of 120 are loaded", with 202 total and 101 successful requests
  3. Export Data is disabled, with the tooltip "Only the 100 highest-spend keys of 120 were loaded, so a per-team export would under-report"

After (de96b5e)

API

  1. User aggregated activity: 120 keys in the breakdown, no api_key_limit or total_api_keys in metadata
  2. Team aggregated activity: 120 keys, no cap metadata
  3. The three search and export routes answer 404, as they did before perf(proxy): split aggregated usage query into key-free rollups and bounded top-N keys #41293
  4. Main right before perf(proxy): split aggregated usage query into key-free rollups and bounded top-N keys #41293 answers all of the above the same way. A full JSON diff of both aggregated responses between that commit and this branch differs only by a key_exists flag on each key, added later by the Top Virtual Keys deleted key fix. Every spend, count and key matches
  5. One more real call on this branch lands in the daily spend table, so spend tracking still writes

Usage page

  1. Same steps
  2. The panel reads "Showing 120 of 120 keys" with no top-N note, and 242 total and 121 successful requests
  3. Export Data is enabled
  4. The committed bundle is rebuilt from this source with node v24.19.0 (build id 3IOiu4hA4P0Rdw49rM7Ed, previously 4PIvKnKm3glB14S2xQDsz), and none of its chunks contain getApiKeyTruncation, api_key_limit or the "highest-spend keys" note. The page above ran from source through npm run dev; the tip commit adds only the generated bundle

Tests at the same tips: the affected Python tests (daily activity, team and key endpoints, lifecycle, route checks, spend tracking) give 2779 passed here and 2836 at the rc tip, the difference being the reverted top-N and rollup tests. Dashboard vitest over the usage, cost optimization, usage export and usage page components gives 700 passed across 45 files

Two gauntlet-mini reviews ran on this branch. One checked for unintended changes against the rc tip, and one compared the Usage flow against main right before #41293 and against the 1.103 revert. Both came back clean. Every remaining difference from the pre-#41293 Usage code traces to a later, unrelated PR (#40541 CLI session alias, the Top Virtual Keys deleted key fix, per-user team export, the prompt caching requests table, a typing refactor)

Type

🐛 Bug Fix

Caveats (if any)

Medium

Low

  • LiteLLM_DailyGlobalSpend sits idle on this rc since nothing writes or reads it

…pend_table"

Removes the daily global spend rollup job and its reads. Keeps the
LiteLLM_DailyGlobalSpend model and migration so databases that already
applied it are untouched and no new proxy-extras version is needed.

This reverts commit 87694c2, reversing changes made to its first parent.
…_aggregate_split"

Restores the aggregated usage query without the top-N key cap, so the
Usage pages, per-key widgets and exports cover every key again.
CacheLeakageCard keeps the date picker removal from #42055.

This reverts commit 2e46b10, reversing changes made to its first parent.
@greptile-apps

greptile-apps Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 1/5

[Medium risk] Removes feature flags and constants for usage tracking features.

The PR should not merge until team export attribution and CSV escaping are corrected, and compatibility and regression-test requirements are addressed

Findings

  1. P1 Security CSV exports lose formula escaping ▶
  2. P1 Team export API disappears ▶
  3. P2 Aggregation loses database coverage ▶

Summary

The PR restores uncapped Usage key aggregation, removes the top-N search and server-export follow-ups, stops the global spend rollup job, and rebuilds the Admin UI bundle

  • Team model exports can overcount usage shared across teams
  • The restored client CSV path loses formula escaping, and removing the export route breaks existing callers
  • Behavioral database coverage for the aggregation is reduced

Reviews (1) · Last reviewed commit: a6c48b2

Comment on lines +38 to 40
if (formatToUse === "csv") {
handleExportCSV(spendData, exportScope, entityLabel, entityType, teamAliasMap);
toast.success(`${entityLabel} usage data exported successfully as CSV`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 security CSV exports lose formula escaping A team or key alias beginning with = now reaches the downloaded CSV without the server export's escaping and can become a spreadsheet formula when opened

How this was verified: The browser passes aliases to Papa.unparse without formula escaping; the removed server CSV path prefixed formula-like values

@@ -6818,283 +6805,6 @@ async def get_team_daily_activity_aggregated(
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Team export API disappears Existing callers of /team/daily/activity/export now receive 404 instead of CSV or JSON. Removing this route without a user-controlled compatibility flag violates the repository directive to avoid backward-incompatible changes without one

Rule Used: What: avoid backwards-incompatible changes without user-controlled flags Why: This breaks current behaviour for users using existing functionality Example of BAD: this PR (#22164) introduced run_post_custom... (source)

Comment on lines 1309 to +1339
"user-1",
"bedrock/global.anthropic.claude-opus-4-8",
"sk-test",
PTU_SENTINEL_API_KEY,
]
assert "model = $4" in sql
assert "api_key = $5" in sql

def test_model_group_rollups_fall_back_to_model_name(self):
"""Aggregated model_groups rollups must fall back to model for group-less rows.

The (date, model_group) grouping level cannot recover the model column
after the fact (it is rolled up), so the fallback has to happen in SQL;
without it, group-less rows silently vanish from the model_groups
breakdown that the usage UI now renders by default. Group-less rows are
stored as empty strings, not NULL (spend_tracking_utils defaults
model_group to ""), so a plain COALESCE is not enough: the fallback must
be NULLIF-wrapped to catch both
"""
sql, _ = _build_aggregated_sql_query(
table_name="litellm_dailyuserspend",
entity_id_field="user_id",
entity_id=None,
start_date="2026-07-01",
end_date="2026-07-01",
model=None,
api_key=None,
)

normalized = " ".join(sql.split())
fallback = "COALESCE(NULLIF(model_group, ''), model)"
assert f"{fallback} AS model_group" in normalized

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 Aggregation loses database coverage Removing the PostgreSQL-backed aggregation tests and checking only SQL text weakens behavioral coverage, including for keys past the former cap. The repository requires test changes not to weaken regression coverage; restore a behavioral check before merging

Rule Used: What: Flag any modifications to existing tests and verify they don't weaken test coverage or mask regressions. Why: Developers may alter tests to make failing code pass rather than fix the actual bug, hiding regressions. Good: ``` // Test updated t... (source)

@greptile-apps

greptile-apps Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.

  • P1 Shared keys inflate team exports ui/litellm-dashboard/src/components/EntityUsageExport/EntityUsageExportModal.tsx:42 ▶

    When one key is used by two teams on the same day and model, the restored browser export assigns its combined model usage to both teams. The daily-with-models export overstates each team's spend and requests

Comment thread litellm/constants.py
PTU_SENTINEL_API_KEY: Final[str] = "__ptu_flat_cost__"
PTU_ROLLUP_JOB_ID: Final[str] = "ptu_flat_cost_rollup_job"
PTU_ROLLUP_LOCK_TTL_SECONDS: Final[int] = 900
USAGE_TOP_API_KEYS_LIMIT: Final[int] = int(os.getenv("USAGE_TOP_API_KEYS_LIMIT", "100"))

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.

Low: Unbounded usage aggregation

Removing this cap also removes the corresponding SQL limit from the aggregated team and user activity queries. An authenticated caller with many visible keys can repeatedly query up to 400 days, forcing PostgreSQL and the worker to generate and retain rows for every key across each breakdown; keep a server-side cap or paginate these rollups, and handle complete exports through a separately bounded asynchronous path.

@veria-ai

veria-ai Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

PR overview

This PR reverts the usage changes from rc/1.104.0 by removing the top-N key cap and its follow-up changes, along with the daily global spend rollup code. It restores uncapped aggregated team and user activity queries.

One issue remains open: authenticated callers with many visible keys can request large usage aggregations over long date ranges, creating substantial PostgreSQL and worker load. Exploitability depends on the caller having access to many keys, but repeated requests could cause resource pressure until the queries are capped or paginated. No issues have yet been addressed.

Open issues (1)

Fixed/addressed: 0 · PR risk: 4/10

@codecov

codecov Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.47059% with 12 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...xy/management_endpoints/internal_user_endpoints.py 18.18% 9 Missing ⚠️
...roxy/management_endpoints/common_daily_activity.py 92.10% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@yuneng-berri
yuneng-berri merged commit 6d67248 into rc/1.104.0 Sep 27, 2026
7 of 9 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_rc_1_104_0_revert_top_n branch September 27, 2026 00:35

This branch is waiting to be deployed

1 waiting deployment
e2e-changed — de96b5e2 Waiting Sep 27, 2026 by yuneng-berri via oauth #1473
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.

1 participant