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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): include today's UTC bucket when a daily activity range ends at the caller's current day (#36051)
tin-berri86890654c5b9
diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.pyindex 9af65b50c7f..7a30f6b799a 100644--- a/litellm/proxy/management_endpoints/common_daily_activity.py+++ b/litellm/proxy/management_endpoints/common_daily_activity.py@@ -1,6 +1,6 @@import asynciofrom collections.abc import Awaitable, Callable, Mapping, Sequence-from datetime import datetime+from datetime import datetime, timedelta, timezonefrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Final, Protocol@@ -422,26 +422,46 @@ def _adjust_dates_for_timezone(start_date: str,end_date: str,timezone_offset_minutes: int | None,+ include_current_utc_day: bool = False,+ utc_now: datetime | None = None,) -> tuple[str, str]:"""- Pass-through for the local date range; the timezone offset is intentionally ignored here.+ Map a caller-local date range onto UTC bucket keys, extending only the live end.The aggregation table (e.g. LiteLLM_DailyUserSpend) stores spend in whole-UTC-day- buckets keyed on date as YYYY-MM-DD. Any conversion from a local date range to a- UTC date range using only date arithmetic must round to whole UTC days, allowing up- to 24h of slop at each boundary. The previous implementation expanded the SQL range- by an extra full UTC day on whichever side the offset pointed, which pulled in 24h- of unrelated bucket data per boundary and produced approximately 100% over-counting- on single-day queries (e.g. IST May 29 returning UTC May 28 + UTC May 29 in full).+ buckets keyed on date as YYYY-MM-DD. Any conversion of an interior local-day+ boundary using only date arithmetic must round to whole UTC days, allowing up to+ 24h of slop at each boundary. A previous implementation expanded the SQL range by+ an extra full UTC day on whichever side the offset pointed, which pulled in 24h of+ unrelated bucket data per boundary and produced approximately 100% over-counting on+ single-day queries (e.g. IST May 29 returning UTC May 28 + UTC May 29 in full).Sums of single-day queries then exceeded the equivalent multi-day aggregate, which- is mathematically impossible.-- Treating the local date as the UTC date trades a small one-time boundary slop for- correct, monotonic, additive results across single-day and multi-day queries. A- later fix can introduce hour-level buckets or pro-rata weighting on adjacent UTC- days; both require data the current schema does not store.+ is mathematically impossible. Historical dates therefore stay a pass-through: the+ local date is the UTC bucket key, trading boundary slop for monotonic, additive+ results. Hour-level buckets or pro-rata weighting would fix that properly; both+ require data the current schema does not store.++ The end boundary is different when the range reaches the caller's current day. A+ caller west of UTC asking for a range ending "today" is asking for data up to now,+ but once UTC has rolled past their local midnight, everything they sent since then+ sits in the next UTC bucket, which the pass-through excludes: a PT dashboard goes+ stale every evening from 5pm until local midnight, showing $0 for anything that+ only started accruing that evening. Extending such a range to today's UTC bucket+ cannot over-count, because the only part of that bucket outside the caller's range+ is the future, and the future is empty. ``timezone_offset_minutes`` follows the+ JS ``Date.getTimezoneOffset`` convention: UTC minus local, positive west of UTC.++ The extension is strictly opt-in via ``include_current_utc_day`` so a consumer+ whose axis or reconciliation expects the range to stop at the requested end date+ keeps today's byte-for-byte behaviour; the cost optimization dashboard opts in."""- return start_date, end_date+ if not include_current_utc_day or timezone_offset_minutes is None:+ return start_date, end_date+ now: Final = utc_now if utc_now is not None else datetime.now(timezone.utc)+ caller_local_today: Final = (now - timedelta(minutes=timezone_offset_minutes)).date().isoformat()+ if end_date < caller_local_today:+ return start_date, end_date+ return start_date, max(end_date, now.date().isoformat())def _build_where_conditions(@@ -454,10 +474,13 @@ def _build_where_conditions(api_key: str | list[str] | None,exclude_entity_ids: list[str] | None = None,timezone_offset_minutes: int | None = None,+ include_current_utc_day: bool = False,) -> dict[str, "_WhereValue"]:"""Build prisma where clause for daily activity queries."""# Adjust dates for timezone if provided- adjusted_start, adjusted_end = _adjust_dates_for_timezone(start_date, end_date, timezone_offset_minutes)+ adjusted_start, adjusted_end = _adjust_dates_for_timezone(+ start_date, end_date, timezone_offset_minutes, include_current_utc_day+ )where_conditions: Final[dict[str, _WhereValue]] = {"date": {@@ -903,6 +926,7 @@ async def get_daily_activity(exclude_entity_ids: list[str] | None = None,metadata_metrics_func: Callable[[Sequence[DailySpendRecord]], SpendMetrics] | None = None,timezone_offset_minutes: int | None = None,+ include_current_utc_day: bool = False,resolve_entity_metadata: Callable[[Sequence[DailySpendRecord]], Awaitable[dict[str, dict[str, object]]]]| None = None,) -> SpendAnalyticsPaginatedResponse:@@ -936,6 +960,7 @@ async def get_daily_activity(api_key=api_key,exclude_entity_ids=exclude_entity_ids,timezone_offset_minutes=timezone_offset_minutes,+ include_current_utc_day=include_current_utc_day,)# Get total count for paginationdiff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex dcec33f1cb2..640a735c916 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -2650,6 +2650,13 @@ async def get_user_daily_activity(description="Timezone offset in minutes from UTC (e.g., 480 for PST). ""Matches JavaScript's Date.getTimezoneOffset() convention.",),+ include_current_utc_day: bool = fastapi.Query(+ default=False,+ description="When the range ends on the caller's current local day, extend it to "+ "today's UTC bucket so spend written after the caller's local midnight (in UTC "+ "terms) is included. Requires the timezone parameter. Historical ranges are "+ "never extended.",+ ),user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),) -> SpendAnalyticsPaginatedResponse:"""@@ -2711,6 +2718,7 @@ async def get_user_daily_activity(page=page,page_size=page_size,timezone_offset_minutes=timezone,+ include_current_utc_day=include_current_utc_day,resolve_entity_metadata=lambda records: _resolve_user_email_metadata(prisma_client, records),)diff --git a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.pyindex f2749be5d6e..469e0d340f0 100644--- a/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py+++ b/tests/test_litellm/proxy/management_endpoints/test_common_daily_activity.py@@ -1,6 +1,8 @@import osimport sys+from datetime import datetime, timezonefrom types import SimpleNamespace+from typing import Finalfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -870,6 +872,66 @@ class TestAdjustDatesForTimezone:assert per_day_ends == days+class TestAdjustDatesForTimezoneLiveEnd:+ """+ Regression tests for the stale-evening bug: a caller west of UTC whose range+ ends on their local "today" was capped at that local date's UTC bucket, so+ once UTC rolled past their local midnight (5pm PT), everything sent that+ evening sat in the next UTC bucket and the dashboard reported $0 for it+ until local midnight. A range that reaches the caller's current day and+ opts in via include_current_utc_day must extend to today's UTC bucket; the+ only part of that bucket outside the range is the future, which is empty,+ so the extension cannot over-count. Callers that do not opt in keep the+ pass-through byte for byte.+ """++ PT_EVENING_UTC: Final = datetime(2026, 8, 6, 4, 30, tzinfo=timezone.utc)++ def test_pt_evening_range_ending_today_extends_to_utc_today(self):+ start, end = _adjust_dates_for_timezone(+ "2026-07-06", "2026-08-05", 420, include_current_utc_day=True, utc_now=self.PT_EVENING_UTC+ )+ assert (start, end) == ("2026-07-06", "2026-08-06")++ def test_without_opt_in_live_range_keeps_pass_through(self):+ start, end = _adjust_dates_for_timezone(+ "2026-07-06", "2026-08-05", 420, utc_now=self.PT_EVENING_UTC+ )+ assert (start, end) == ("2026-07-06", "2026-08-05")++ def test_pt_historical_range_is_untouched(self):+ start, end = _adjust_dates_for_timezone(+ "2026-07-01", "2026-08-04", 420, include_current_utc_day=True, utc_now=self.PT_EVENING_UTC+ )+ assert (start, end) == ("2026-07-01", "2026-08-04")++ def test_east_of_utc_local_today_already_covers_utc_today(self):+ ist_evening_utc: Final = datetime(2026, 8, 5, 17, 0, tzinfo=timezone.utc)+ start, end = _adjust_dates_for_timezone(+ "2026-07-07", "2026-08-06", -330, include_current_utc_day=True, utc_now=ist_evening_utc+ )+ assert (start, end) == ("2026-07-07", "2026-08-06")++ def test_missing_offset_stays_pass_through_even_for_live_range(self):+ start, end = _adjust_dates_for_timezone(+ "2026-07-06", "2026-08-05", None, include_current_utc_day=True, utc_now=self.PT_EVENING_UTC+ )+ assert (start, end) == ("2026-07-06", "2026-08-05")++ def test_utc_caller_range_ending_today_is_unchanged(self):+ utc_noon: Final = datetime(2026, 8, 5, 12, 0, tzinfo=timezone.utc)+ start, end = _adjust_dates_for_timezone(+ "2026-07-06", "2026-08-05", 0, include_current_utc_day=True, utc_now=utc_noon+ )+ assert (start, end) == ("2026-07-06", "2026-08-05")++ def test_future_end_date_extends_no_further_than_requested(self):+ start, end = _adjust_dates_for_timezone(+ "2026-07-06", "2026-08-09", 420, include_current_utc_day=True, utc_now=self.PT_EVENING_UTC+ )+ assert (start, end) == ("2026-07-06", "2026-08-09")++class TestBuildAggregatedSqlQuery:"""Asserts the SQL emitted by the aggregated query path stays anchored to thediff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsxindex fe3e792eeee..96d4644804b 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.test.tsx@@ -209,9 +209,9 @@ describe("UsageTab", () => {it("says what the line means and over what range", async () => {const { getByText, getByRole } = renderWith(twoDays());- expect(getByText("Running total saved · Jul 1 – Jul 14")).toBeInTheDocument();+ expect(getByText("Running total saved · Jul 1 – Jul 14 (UTC)")).toBeInTheDocument();await userEvent.click(getByRole("tab", { name: "Per day" }));- expect(getByText("Saved per day · Jul 1 – Jul 14")).toBeInTheDocument();+ expect(getByText("Saved per day · Jul 1 – Jul 14 (UTC)")).toBeInTheDocument();});it("builds the per-driver donut from the range totals, not the running total", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsxindex b6287602210..bd9d4f3c873 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/UsageTab.tsx@@ -141,7 +141,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {const rangeLabel = formatRangeLabel(startTime ?? undefined, endTime ?? undefined);const savingsSubtitle = [accumulation === "cumulative" ? "Running total saved" : `Saved ${intervalLabel.toLowerCase()}`,- rangeLabel,+ rangeLabel && `${rangeLabel} (UTC)`,].filter(Boolean).join(" \u00b7 ");@@ -179,6 +179,7 @@ const UsageTab: React.FC<UsageTabProps> = ({ accessToken, activity }) => {return (<div className="w-full space-y-6"><div className="flex flex-wrap items-center justify-end gap-4">+ <span className="text-sm text-muted-foreground">Spend is bucketed by UTC day</span><AdvancedDatePicker value={dateValue} onValueChange={onDateChange} /></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.test.tsxindex 9fd27d80c37..e26a3629e8c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.test.tsx@@ -22,13 +22,13 @@ describe("useDailyActivityRange", () => {it("queries every user's activity for an admin", () => {renderHook(() => useDailyActivityRange("test-token", "u1", "proxy_admin"));- expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), null]);+ expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), null, true]);});it("scopes the query to the caller for a non-admin", () => {renderHook(() => useDailyActivityRange("test-token", "u1", "internal_user"));- expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), "u1"]);+ expect(argsOfLastCall()).toEqual(["test-token", expect.any(Date), expect.any(Date), "u1", true]);});it("stays disabled until an access token is available", () => {diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.ts b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.tsindex 1c3f706726e..3a2a38c5955 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/useDailyActivityRange.ts@@ -35,7 +35,7 @@ export const useDailyActivityRange = (const { data, loading, isFetchingMore } = usePaginatedDailyActivity({fetchFn: userDailyActivityCall,- args: [accessToken, startTime, endTime, effectiveUserId],+ args: [accessToken, startTime, endTime, effectiveUserId, true],enabled: !!accessToken && !!startTime && !!endTime,});diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex 03106528a80..17a5ca37990 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -1388,6 +1388,7 @@ export const userDailyActivityCall = async (endTime: Date,page: number = 1,userId: string | null = null,+ includeCurrentUtcDay: boolean = false,) => {/*** Get daily user activity on proxy@@ -1400,6 +1401,7 @@ export const userDailyActivityCall = async (page,extraQueryParams: {user_id: userId,+ include_current_utc_day: includeCurrentUtcDay ? "true" : undefined,},});};diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 0064b1a7d87..b67083ea90f 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -53883,6 +53883,8 @@ export interface operations {page_size?: number;/** @description Timezone offset in minutes from UTC (e.g., 480 for PST). Matches JavaScript's Date.getTimezoneOffset() convention. */timezone?: number | null;+ /** @description When the range ends on the caller's current local day, extend it to today's UTC bucket so spend written after the caller's local midnight (in UTC terms) is included. Requires the timezone parameter. Historical ranges are never extended. */+ include_current_utc_day?: boolean;};header?: never;path?: never;