-
-
Notifications
You must be signed in to change notification settings - Fork 11.2k
feat(spend): add a per-session auto-router benchmarks rollup #35839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: litellm_internal_staging
Are you sure you want to change the base?
Changes from all commits
2e2b262
8c20ac7
901eb3d
702da45
7eeafa9
798e54d
ee0e194
34ff4e1
270da20
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| CREATE TABLE IF NOT EXISTS "LiteLLM_AutoRouterSession" ( | ||
| api_key TEXT NOT NULL, | ||
| session_id TEXT NOT NULL, | ||
| model_group TEXT NOT NULL, | ||
| router_kind TEXT NOT NULL, | ||
| baseline_model TEXT, | ||
| turns INTEGER NOT NULL DEFAULT 0, | ||
| turns_with_usage INTEGER NOT NULL DEFAULT 0, | ||
| total_tokens BIGINT NOT NULL DEFAULT 0, | ||
| spend DOUBLE PRECISION NOT NULL DEFAULT 0, | ||
| baseline_spend DOUBLE PRECISION NOT NULL DEFAULT 0, | ||
| first_visit_turns INTEGER NOT NULL DEFAULT 0, | ||
| first_visit_hits INTEGER NOT NULL DEFAULT 0, | ||
| warm_turns INTEGER NOT NULL DEFAULT 0, | ||
| warm_hits INTEGER NOT NULL DEFAULT 0, | ||
| expired_turns INTEGER NOT NULL DEFAULT 0, | ||
| expired_hits INTEGER NOT NULL DEFAULT 0, | ||
| unordered_turns INTEGER NOT NULL DEFAULT 0, | ||
| unordered_hits INTEGER NOT NULL DEFAULT 0, | ||
| unknown_ttl_turns INTEGER NOT NULL DEFAULT 0, | ||
| unknown_ttl_hits INTEGER NOT NULL DEFAULT 0, | ||
| cache_5m_turns INTEGER NOT NULL DEFAULT 0, | ||
| cache_1h_turns INTEGER NOT NULL DEFAULT 0, | ||
| cache_ttl_unknown_turns INTEGER NOT NULL DEFAULT 0, | ||
| tiers JSONB NOT NULL DEFAULT '{}', | ||
| first_turn_at TIMESTAMP(3) NOT NULL, | ||
| last_turn_at TIMESTAMP(3) NOT NULL, | ||
| updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
|
|
||
| CONSTRAINT "LiteLLM_AutoRouterSession_pkey" PRIMARY KEY (api_key, session_id, model_group) | ||
| ); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS "idx_auto_router_session_started" | ||
| ON "LiteLLM_AutoRouterSession" (first_turn_at); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS "idx_auto_router_session_activity" | ||
| ON "LiteLLM_AutoRouterSession" (last_turn_at); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,9 @@ | |
| from litellm.proxy.db.db_transaction_queue.spend_logs_partition_manager import ( | ||
| SpendLogsPartitionManager, | ||
| ) | ||
| from litellm.proxy.spend_tracking.auto_router_benchmarks import ( | ||
| AUTO_ROUTER_SESSION_RETENTION_DAYS, | ||
| ) | ||
| from litellm.proxy.utils import PrismaClient | ||
|
|
||
|
|
||
|
|
@@ -186,22 +189,42 @@ async def _delete_old_tool_index_rows(self, prisma_client: PrismaClient, cutoff_ | |
| time_column="start_time", | ||
| ) | ||
|
|
||
| async def _delete_old_auto_router_sessions(self, prisma_client: PrismaClient, cutoff_date: datetime) -> int: | ||
| """Expire auto-router rollups past the given cutoff. | ||
|
|
||
| Keyed on last activity rather than session start, so a conversation still running | ||
| when the cutoff passes is not pruned out from under itself. | ||
| """ | ||
| return await self._delete_old_rows_batched( | ||
| prisma_client, | ||
| cutoff_date, | ||
| table_name="LiteLLM_AutoRouterSession", | ||
| key_columns=("api_key", "session_id", "model_group"), | ||
| time_column="last_turn_at", | ||
| ) | ||
|
|
||
| def _auto_router_session_cutoff(self, retention_seconds: float | None) -> datetime: | ||
| """Rows the benchmarks endpoint can no longer read are collected at the read | ||
| horizon even with no retention configured; a shorter configured retention wins.""" | ||
| now: Final = datetime.now(timezone.utc) | ||
| horizon: Final = now - timedelta(days=AUTO_ROUTER_SESSION_RETENTION_DAYS) | ||
| return horizon if retention_seconds is None else max(horizon, now - timedelta(seconds=retention_seconds)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Active old sessions never prunedMedium Severity Retention keys off Additional Locations (1)Reviewed by Cursor Bugbot for commit 270da20. Configure here. |
||
|
|
||
| async def cleanup_old_spend_logs(self, prisma_client: PrismaClient) -> None: | ||
| """ | ||
| Main cleanup function. Deletes old spend logs in batches. | ||
| If pod_lock_manager is available, ensures only one pod runs cleanup. | ||
| If no pod_lock_manager, runs cleanup without distributed locking. | ||
|
|
||
| Spend logs and their tool index only expire when | ||
| ``maximum_spend_logs_retention_period`` is configured. The auto-router rollup is | ||
| collected on every run regardless; see ``_auto_router_session_cutoff``. | ||
| """ | ||
| lock_acquired = False | ||
| try: | ||
| verbose_proxy_logger.info("Cleanup job triggered at %s", datetime.now()) | ||
|
|
||
| if not self._should_delete_spend_logs(): | ||
| return | ||
|
|
||
| if self.retention_seconds is None: | ||
| verbose_proxy_logger.error("Retention seconds is None, cannot proceed with cleanup") | ||
| return | ||
| retention_seconds: Final = self.retention_seconds if self._should_delete_spend_logs() else None | ||
|
|
||
| # If we have a pod lock manager, try to acquire the lock | ||
| if self.pod_lock_manager and self.pod_lock_manager.redis_cache: | ||
|
|
@@ -219,31 +242,39 @@ async def cleanup_old_spend_logs(self, prisma_client: PrismaClient) -> None: | |
| verbose_proxy_logger.info("Another pod is already running cleanup") | ||
| return | ||
|
|
||
| cutoff_date: Final = datetime.now(timezone.utc) - timedelta(seconds=float(self.retention_seconds)) | ||
| verbose_proxy_logger.info("Removing logs older than %s", cutoff_date.isoformat()) | ||
| if retention_seconds is not None: | ||
| cutoff_date: Final = datetime.now(timezone.utc) - timedelta(seconds=float(retention_seconds)) | ||
| verbose_proxy_logger.info("Removing logs older than %s", cutoff_date.isoformat()) | ||
|
|
||
| if self.general_settings.get( | ||
| "use_spend_logs_partitioning", False | ||
| ) and await self.partition_manager.is_partitioned(prisma_client): | ||
| await self.partition_manager.ensure_partitions(prisma_client) | ||
| dropped: Final = await self.partition_manager.drop_partitions_older_than(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info( | ||
| "Dropped %d expired spend-log partitions: %s", | ||
| len(dropped), | ||
| dropped, | ||
| ) | ||
| # DROP only reclaims whole expired partitions. Expired rows can | ||
| # still sit in the DEFAULT partition (backfill, coverage gaps) | ||
| # or in a partition that spans the cutoff, so retention must | ||
| # also delete those stragglers row-wise. | ||
| total_deleted = await self._delete_old_logs(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info("Deleted %s expired logs not covered by dropped partitions", total_deleted) | ||
| else: | ||
| total_deleted = await self._delete_old_logs(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info("Deleted %s logs", total_deleted) | ||
| if self.general_settings.get( | ||
| "use_spend_logs_partitioning", False | ||
| ) and await self.partition_manager.is_partitioned(prisma_client): | ||
| await self.partition_manager.ensure_partitions(prisma_client) | ||
| dropped: Final = await self.partition_manager.drop_partitions_older_than(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info( | ||
| "Dropped %d expired spend-log partitions: %s", | ||
| len(dropped), | ||
| dropped, | ||
| ) | ||
| # DROP only reclaims whole expired partitions. Expired rows can | ||
| # still sit in the DEFAULT partition (backfill, coverage gaps) | ||
| # or in a partition that spans the cutoff, so retention must | ||
| # also delete those stragglers row-wise. | ||
| total_deleted = await self._delete_old_logs(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info( | ||
| "Deleted %s expired logs not covered by dropped partitions", total_deleted | ||
| ) | ||
| else: | ||
| total_deleted = await self._delete_old_logs(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info("Deleted %s logs", total_deleted) | ||
|
|
||
| index_deleted: Final = await self._delete_old_tool_index_rows(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info("Deleted %s expired tool index rows", index_deleted) | ||
| index_deleted: Final = await self._delete_old_tool_index_rows(prisma_client, cutoff_date) | ||
| verbose_proxy_logger.info("Deleted %s expired tool index rows", index_deleted) | ||
|
|
||
| sessions_deleted: Final = await self._delete_old_auto_router_sessions( | ||
| prisma_client, self._auto_router_session_cutoff(retention_seconds) | ||
| ) | ||
| verbose_proxy_logger.info("Deleted %s expired auto-router session rollups", sessions_deleted) | ||
|
|
||
| except Exception as e: | ||
| # .exception() captures the traceback; str(e) alone on a Prisma/DB | ||
|
|
||


Uh oh!
There was an error while loading. Please reload this page.