Repository navigation
revert(usage): remove the top-N key cap, its follow-ups and the daily global spend rollup code from rc/1.104.0 - #43385
Conversation
This reverts commit 5a8ec13.
…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.
a6c48b2 to
7a3df3a
Compare
|
| if (formatToUse === "csv") { | ||
| handleExportCSV(spendData, exportScope, entityLabel, entityType, teamAliasMap); | ||
| toast.success(`${entityLabel} usage data exported successfully as CSV`); |
There was a problem hiding this comment.
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( | |||
| ) | |||
There was a problem hiding this comment.
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)
| "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 |
There was a problem hiding this comment.
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)
Comments Outside DiffThese 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.
|
| 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")) |
There was a problem hiding this comment.
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.
PR overviewThis 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 Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
TLDR
Problem this solves:
How it solves it:
LiteLLM_DailyGlobalSpendmodel and migration, same as 1.103User 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
After: the same admin sees every key again, the way the Usage pages behaved before #41293
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
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)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-nanodeployment, 120 virtual keys in one team created through/key/generate, and one real/v1/chat/completionscall 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 withnpm run devpointed at that proxyBefore (95f33f4)
API
metadata.api_key_limit: 100,metadata.total_api_keys: 120/user/daily/activity/aggregated/search,/team/daily/activity/aggregated/searchand/team/daily/activity/exportanswer 200Usage page
After (de96b5e)
API
api_key_limitortotal_api_keysin metadatakey_existsflag on each key, added later by the Top Virtual Keys deleted key fix. Every spend, count and key matchesUsage page
3IOiu4hA4P0Rdw49rM7Ed, previously4PIvKnKm3glB14S2xQDsz), and none of its chunks containgetApiKeyTruncation,api_key_limitor the "highest-spend keys" note. The page above ran from source throughnpm run dev; the tip commit adds only the generated bundleTests 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
The table and migration stay on purpose, matching 1.103
Team usage CSV exports lose formula escaping
=,+,-and@cellsescapeFormulaeto the client export is a separate change, not part of this revertAggregated usage queries are uncapped again
A key shared by two teams on the same day and model counts toward both teams in the per-model team export
Low
LiteLLM_DailyGlobalSpendsits idle on this rc since nothing writes or reads it