Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge remote-tracking branch 'origin/litellm_usage_key_free_aggregate_split' into litellm_daily_global_spend_table

yassin7c5fa53d4041
diff --cc litellm/proxy/management_endpoints/common_daily_activity.py
index 47465324f42,a5e292b177d..a1c92d37871
--- a/litellm/proxy/management_endpoints/common_daily_activity.py
+++ b/litellm/proxy/management_endpoints/common_daily_activity.py
@@@ -873,8 -804,10 +867,9 @@@ def _build_aggregated_sql_query
(GROUPING(date) << 6) | {_API_KEY_ROLLED_UP_BIT}
| GROUPING(model, {_MODEL_GROUP_EXPR},
custom_llm_provider, mcp_namespaced_tool_name,
- endpoint) AS group_level,{metric_select}
+ endpoint) AS group_level,
+ NULL::bigint AS distinct_api_keys,{metric_select}
- FROM "{pg_table}"
- WHERE {where_clause}
+ FROM {_key_free_source(pg_table, where_clause, marker_param)}
GROUP BY GROUPING SETS (
(date),
(date, model),
diff --cc tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
index ee9f886acec,e7f8bcc7e4f..ac761315a27
--- a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py
@@@ -1646,176 -1578,96 +1584,266 @@@ async def test_get_daily_activity_aggre
assert set(day.breakdown.models["gpt-5"].api_key_breakdown) == {"key-1"}
+def _prisma_with_marker(marker: str | None) -> MagicMock:
+ prisma = MagicMock()
+ prisma.db = MagicMock()
+ prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+ prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[])
+ row = (
+ None if marker is None else SimpleNamespace(param_name="m", param_value=f'{{"reconciled_through": "{marker}"}}')
+ )
+ prisma.get_generic_data = AsyncMock(return_value=row)
+ return prisma
+
+
+def _unfiltered_user_query(**overrides):
+ return {
+ "table_name": "litellm_dailyuserspend",
+ "entity_id_field": "user_id",
+ "entity_id": None,
+ "start_date": "2026-06-01",
+ "end_date": "2026-06-02",
+ "model": None,
+ "api_key": None,
+ "exclude_entity_ids": None,
+ "timezone_offset_minutes": None,
+ "include_current_utc_day": False,
+ **overrides,
+ }
+
+
+ ("marker", "overrides", "expected"),
+ [
+ ("2026-06-02", {}, "2026-06-02"),
+ ("2026-06-02", {"model": "gpt-5"}, "2026-06-02"),
+ ("2026-05-01", {}, "2026-05-01"),
+ (None, {}, None),
+ ("2026-06-02", {"api_key": "sk-1"}, None),
+ ("2026-06-02", {"api_key": []}, None),
+ ("2026-06-02", {"entity_id": "u-1"}, None),
+ ("2026-06-02", {"exclude_entity_ids": ["u-1"]}, None),
+ ("2026-06-02", {"table_name": "litellm_dailyteamspend", "entity_id_field": "team_id"}, None),
+ ],
+)
+async def test_global_rollup_marker_is_used_only_for_unfiltered_user_reads(marker, overrides, expected):
+ """Anything that filters by key or entity has no counterpart in the global table; the
+ SQL splits the range at the marker itself, so the marker passes through unchanged."""
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+ prisma = _prisma_with_marker(marker)
+
+ assert await global_rollup_reconciled_through(prisma, _unfiltered_user_query(**overrides)) == expected
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+
+
+async def test_global_rollup_marker_read_failure_falls_back_to_the_per_key_table():
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+ prisma = _prisma_with_marker(None)
+ prisma.get_generic_data = AsyncMock(side_effect=RuntimeError("db down"))
+
+ assert await global_rollup_reconciled_through(prisma, _unfiltered_user_query()) is None
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+
+
+def test_aggregated_sql_splits_the_key_free_arm_at_the_marker_and_keeps_the_key_arm_per_key():
+ sql, params = _build_aggregated_sql_query(**_unfiltered_user_query(), global_rollup_through="2026-06-01")
+ marker_param: Final = f"${len(params)}"
+
+ assert params[-1] == "2026-06-01"
+ assert (
+ f'FROM "LiteLLM_DailyGlobalSpend"\n WHERE date >= $1 AND date <= $2 AND date <= {marker_param}'
+ in sql
+ )
+ assert (
+ f'FROM "LiteLLM_DailyUserSpend"\n WHERE date >= $1 AND date <= $2 AND date > {marker_param}' in sql
+ )
+ key_arm: Final = sql.split("UNION ALL\n (WITH top_api_keys")[1]
+ assert "LiteLLM_DailyGlobalSpend" not in key_arm
+ assert marker_param not in key_arm
+
+
+def test_aggregated_sql_without_a_marker_reads_the_per_key_table_only():
+ sql, params = _build_aggregated_sql_query(**_unfiltered_user_query())
+
+ assert "LiteLLM_DailyGlobalSpend" not in sql
+ assert params[-1] == PTU_SENTINEL_API_KEY
+
+
+_GLOBAL_SPEND_MIGRATION: Final = (
+ pathlib.Path(__file__).resolve().parents[4]
+ / "litellm-proxy-extras"
+ / "litellm_proxy_extras"
+ / "migrations"
+ / "20260915000000_add_daily_global_spend"
+ / "migration.sql"
+)
+
+
+async def test_get_daily_activity_aggregated_serves_closed_days_from_the_global_table_and_open_days_live(
+ _aggregated_postgresql: psycopg.Connection,
+):
+ """Day 1 is rolled up and day 2 is still open (never rolled up), so a marker of day 1 must
+ give the same response as reading everything per-key: day 1 from the global table, day 2
+ live, one grand total across both. The per-key arm stays on the user table throughout."""
+ n_keys: Final = USAGE_TOP_API_KEYS_LIMIT + 3
+ rows: Final = [
+ (
+ f"row-{day}-{i:03d}",
+ f"user-{i % 7}",
+ day,
+ f"key-{i:03d}",
+ "gpt-5" if i % 2 else "claude",
+ "" if i % 3 else "gpt-5",
+ "openai" if i % 2 else None,
+ "/v1/chat/completions" if i % 5 else None,
+ 10,
+ float(i + 1),
+ 1,
+ 1,
+ )
+ for day in ("2026-06-01", "2026-06-02")
+ for i in range(n_keys)
+ ]
+ _seed_daily_user_spend(_aggregated_postgresql, rows)
+ with _aggregated_postgresql.cursor() as cur:
+ cur.execute(
+ 'UPDATE "LiteLLM_DailyUserSpend" SET total_response_time_ms = prompt_tokens * 25, '
+ "timed_requests = api_requests"
+ )
+ cur.execute(_GLOBAL_SPEND_MIGRATION.read_text()) # pyright: ignore[reportArgumentType] # DDL literal
+ cur.execute(
+ re.sub(r"\$(\d+)", r"%(p\1)s", RECONCILE_DAY_SQL), # pyright: ignore[reportArgumentType] # $N -> psycopg
+ {"p1": "2026-06-01"},
+ )
+ _aggregated_postgresql.commit()
+
+ async def read(marker: str | None, sql_seen: list[str]):
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+ prisma = _prisma_with_marker(marker)
+ run_query = _psycopg_query_raw(_aggregated_postgresql, [])
+
+ async def query_raw(sql: str, *params: str):
+ sql_seen.append(sql)
+ return await run_query(sql, *params)
+
+ prisma.db.query_raw = query_raw
+ return await get_daily_activity_aggregated(
+ prisma_client=prisma,
+ entity_metadata_field=None,
+ **_unfiltered_user_query(),
+ )
+
+ per_key_sql: Final[list[str]] = [] # mutable-ok: out-param for the query_raw shim
+ global_sql: Final[list[str]] = [] # mutable-ok: out-param for the query_raw shim
+ from_per_key = await read(None, per_key_sql)
+ from_global = await read("2026-06-01", global_sql)
+ await evict_config_param(DAILY_GLOBAL_SPEND_RECONCILED_THROUGH_PARAM)
+
+ assert per_key_sql[0].count('FROM "LiteLLM_DailyGlobalSpend"') == 0
+ assert global_sql[0].count('FROM "LiteLLM_DailyGlobalSpend"') == 1
+ assert global_sql[0].count('FROM "LiteLLM_DailyUserSpend"') == 3
+ assert from_global.model_dump() == from_per_key.model_dump()
+ assert from_global.metadata.total_spend == pytest.approx(2 * sum(float(i + 1) for i in range(n_keys)))
+ assert from_global.metadata.total_response_time_ms == 2 * n_keys * 10 * 25
+ assert from_global.metadata.total_timed_requests == 2 * n_keys
+ assert {day.date.isoformat() for day in from_global.results} == {"2026-06-01", "2026-06-02"}
+ assert len(from_global.results[0].breakdown.api_keys) == USAGE_TOP_API_KEYS_LIMIT
+ assert set(from_global.results[0].breakdown.model_groups) == {"gpt-5", "claude"}
+
+
+ @pytest.mark.asyncio
+ async def test_get_daily_activity_aggregated_reports_exact_limit_key_count_as_complete(
+ _aggregated_postgresql: psycopg.Connection,
+ ):
+ """With exactly USAGE_TOP_API_KEYS_LIMIT keys nothing is dropped, and the
+ response must say so: total_api_keys equals the limit rather than exceeding it."""
+ rows: Final = [
+ (
+ f"row-{i:03d}",
+ f"user-{i:03d}",
+ "2026-06-01",
+ f"key-{i:03d}",
+ "gpt-5",
+ "",
+ "openai",
+ "/v1/chat/completions",
+ 10,
+ float(i + 1),
+ 1,
+ 1,
+ )
+ for i in range(USAGE_TOP_API_KEYS_LIMIT)
+ ]
+ _seed_daily_user_spend(_aggregated_postgresql, rows)
+
+ row_counts: Final[list[int]] = [] # mutable-ok: out-param for the query_raw shim
+ mock_prisma = MagicMock()
+ mock_prisma.db = MagicMock()
+ mock_prisma.db.query_raw = _psycopg_query_raw(_aggregated_postgresql, row_counts)
+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+ mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[])
+
+ result = await get_daily_activity_aggregated(
+ prisma_client=mock_prisma,
+ table_name="litellm_dailyuserspend",
+ entity_id_field="user_id",
+ entity_id=None,
+ entity_metadata_field=None,
+ start_date="2026-06-01",
+ end_date="2026-06-01",
+ model=None,
+ api_key=None,
+ )
+
+ assert result.metadata.total_api_keys == USAGE_TOP_API_KEYS_LIMIT
+ assert result.metadata.api_key_limit == USAGE_TOP_API_KEYS_LIMIT
+ assert len(result.results[0].breakdown.api_keys) == USAGE_TOP_API_KEYS_LIMIT
+
+
+ @pytest.mark.asyncio
+ async def test_get_daily_activity_aggregated_model_group_rollups_fall_back_to_model_name(
+ _aggregated_postgresql: psycopg.Connection,
+ ):
+ """Rows stored with an empty or NULL model_group must land in the model_groups
+ breakdown under their model name instead of vanishing from the usage UI."""
+ rows: Final = [
+ ("row-0", "user-0", "2026-06-01", "key-0", "gpt-5", "gpt-5-eu", "openai", "/v1/chat/completions", 10, 7.0, 1, 1),
+ ("row-1", "user-1", "2026-06-01", "key-1", "gpt-5", "", "openai", "/v1/chat/completions", 10, 3.0, 1, 1),
+ ("row-2", "user-2", "2026-06-01", "key-2", "claude-x", None, "anthropic", "/v1/messages", 10, 2.0, 1, 1),
+ ]
+ _seed_daily_user_spend(_aggregated_postgresql, rows)
+
+ mock_prisma = MagicMock()
+ mock_prisma.db = MagicMock()
+ mock_prisma.db.query_raw = _psycopg_query_raw(_aggregated_postgresql, [])
+ mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
+ mock_prisma.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[])
+
+ result = await get_daily_activity_aggregated(
+ prisma_client=mock_prisma,
+ table_name="litellm_dailyuserspend",
+ entity_id_field="user_id",
+ entity_id=None,
+ entity_metadata_field=None,
+ start_date="2026-06-01",
+ end_date="2026-06-01",
+ model=None,
+ api_key=None,
+ )
+
+ breakdown: Final = result.results[0].breakdown
+ assert set(breakdown.model_groups) == {"gpt-5-eu", "gpt-5", "claude-x"}
+ assert breakdown.model_groups["gpt-5-eu"].metrics.spend == 7.0
+ assert breakdown.model_groups["gpt-5"].metrics.spend == 3.0
+ assert breakdown.model_groups["claude-x"].metrics.spend == 2.0
+ assert set(breakdown.model_groups["gpt-5"].api_key_breakdown) == {"key-1"}
+ assert set(breakdown.models) == {"gpt-5", "claude-x"}
+ assert breakdown.models["gpt-5"].metrics.spend == 10.0
+
+
def _no_spend_record():
"""A rollup row for a key with no spend, where SUM() returns NULL (None)."""
return SimpleNamespace(