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
feat(proxy): spend log storage probe and the reclaimable-bytes count (#47449)
Kerry Lu8884f461af3c
diff --git a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.pyindex c82b34dfcf1..b57952b4992 100644--- a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py+++ b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py@@ -1,11 +1,12 @@import asyncio+import reimport timefrom contextvars import ContextVarfrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom typing import Final, Literal, TypeAlias-from pydantic import TypeAdapter+from pydantic import ConfigDict, TypeAdapterfrom litellm._logging import verbose_proxy_loggerfrom litellm.caching import RedisCache@@ -36,6 +37,166 @@ from litellm.types.llms.base import LiteLLMBaseModelStopReason: TypeAlias = Literal["exhausted", "budget_exhausted", "batch_cap_reached", "aborted"]+_SIZE_RE: Final = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)I?B?\s*$", re.IGNORECASE)+_SIZE_UNITS: Final = {"": 1, "K": 1024, "M": 1024**2, "G": 1024**3, "T": 1024**4}+++def size_in_bytes(value: str | int) -> int:+ """+ Parse a storage size such as '180GB', '512 MiB' or '1.5TB' into bytes; a bare int is bytes already.++ Units are powers of 1024, the same convention pg_size_pretty uses, so the number an operator reads+ off `SELECT pg_size_pretty(pg_total_relation_size(...))` is the number they can put in the config.+ """+ if isinstance(value, int):+ if value <= 0:+ raise ValueError(f"size must be positive, got {value}")+ return value+ match: Final = _SIZE_RE.match(value)+ if match is None:+ raise ValueError(f"invalid size {value!r}, expected a number with a unit such as '180GB'")+ size: Final = int(float(match.group(1)) * _SIZE_UNITS[match.group(2).upper()])+ if size <= 0:+ raise ValueError(f"size must be positive, got {value!r}")+ return size+++@dataclass(frozen=True, slots=True)+class StorageProbe:+ """+ What the catalog says about the spend-log tables, read without scanning them.++ `allocated_bytes` is what the files take on disk (heap, indexes and TOAST of LiteLLM_SpendLogs and+ LiteLLM_SpendLogToolIndex, partitions included). Deleting rows does not shrink it: deleted rows become dead+ tuples, autovacuum later turns them into free space that new rows reuse, and only VACUUM FULL or pg_repack+ hands the bytes back to the filesystem. Neither dead tuples nor free space are live data, and Postgres+ tracks only the former (`n_dead_tup`, zeroed by vacuum), so the size rule keeps its own count of the+ reclaimable bytes, see `SizeCleanupState`. `inserted_total` and `deleted_total` are the cumulative+ `n_tup_ins` and `n_tup_del` counters that count is driven by.+ """++ allocated_bytes: int+ live_rows: int+ dead_rows: int+ inserted_total: int+ deleted_total: int++ @property+ def stats_are_stale(self) -> bool:+ """No row counters at all while the files hold data: the statistics were reset, e.g. by a crash."""+ return self.allocated_bytes > 0 and self.live_rows + self.dead_rows == 0+++class SizeCleanupState(LiteLLMBaseModel):+ """+ The size rule's running count of reclaimable bytes, kept in LiteLLM_Config between checks.++ `reclaimable_bytes` is the space inside the files that holds no live row: the bytes of every row deleted+ since the count started (by this job or anyone else, from `n_tup_del`), less the free space new rows have+ since been written into (bytes inserted beyond what the files grew by), less what a VACUUM FULL handed back.+ Live bytes are `allocated_bytes - reclaimable_bytes`, whether or not autovacuum has run yet. `bytes_per_row`+ converts rows to bytes and is refreshed from live bytes over live rows on every check.+ """++ model_config = ConfigDict(frozen=True)+ allocated_bytes: int+ reclaimable_bytes: int+ bytes_per_row: float+ inserted_total: int+ deleted_total: int+++def advance_size_state(state: SizeCleanupState | None, probe: StorageProbe) -> SizeCleanupState:+ """+ Roll the reclaimable count forward to what the catalog shows now.++ Without a prior state, or after the cumulative counters went backwards (a statistics reset), the count+ starts from the dead rows Postgres still knows about, at the files' average bytes per row. A probe with no+ row counters at all (`stats_are_stale`) cannot seed anything: the prior count is carried forward, and with+ no prior count the files are taken as fully reclaimable so nothing is deleted on its say-so.+ """+ if probe.stats_are_stale:+ return SizeCleanupState(+ allocated_bytes=probe.allocated_bytes,+ reclaimable_bytes=probe.allocated_bytes+ if state is None+ else min(probe.allocated_bytes, state.reclaimable_bytes),+ bytes_per_row=1.0 if state is None else state.bytes_per_row,+ inserted_total=probe.inserted_total,+ deleted_total=probe.deleted_total,+ )+ if state is None or probe.inserted_total < state.inserted_total or probe.deleted_total < state.deleted_total:+ seed_bytes_per_row: Final = probe.allocated_bytes / max(probe.live_rows + probe.dead_rows, 1)+ return SizeCleanupState(+ allocated_bytes=probe.allocated_bytes,+ reclaimable_bytes=min(probe.allocated_bytes, round(probe.dead_rows * seed_bytes_per_row)),+ bytes_per_row=max(seed_bytes_per_row, 1.0),+ inserted_total=probe.inserted_total,+ deleted_total=probe.deleted_total,+ )+ growth: Final = probe.allocated_bytes - state.allocated_bytes+ bytes_deleted: Final = (probe.deleted_total - state.deleted_total) * state.bytes_per_row+ free_space_refilled: Final = max(+ 0.0, (probe.inserted_total - state.inserted_total) * state.bytes_per_row - max(0, growth)+ )+ returned_to_filesystem: Final = max(0, -growth)+ reclaimable: Final = min(+ probe.allocated_bytes,+ max(0, round(state.reclaimable_bytes + bytes_deleted - free_space_refilled - returned_to_filesystem)),+ )+ live_bytes: Final = probe.allocated_bytes - reclaimable+ return SizeCleanupState(+ allocated_bytes=probe.allocated_bytes,+ reclaimable_bytes=reclaimable,+ bytes_per_row=max(live_bytes / probe.live_rows, 1.0) if probe.live_rows > 0 else state.bytes_per_row,+ inserted_total=probe.inserted_total,+ deleted_total=probe.deleted_total,+ )+++@dataclass(frozen=True, slots=True)+class SpendLogStorage:+ """What the spend-log tables weigh at one point: the files on disk and the live bytes inside them."""++ allocated_bytes: int+ reclaimable_bytes: int+ bytes_per_row: float+ live_rows: int++ @property+ def estimated_live_bytes(self) -> int:+ return max(0, self.allocated_bytes - self.reclaimable_bytes)++ def after_deleting(self, rows: int, allocated_bytes: int) -> "SpendLogStorage":+ """+ The same storage once `rows` more rows are gone and the files measure `allocated_bytes`.++ Files that grew while the pass only deleted (a visibility map or free space map fork a DELETE creates,+ an index page split) hold no live row, so the growth counts as reclaimable; rows inserted meanwhile are+ taken back out at the next check from n_tup_ins.+ """+ return SpendLogStorage(+ allocated_bytes=allocated_bytes,+ reclaimable_bytes=min(+ allocated_bytes,+ round(+ self.reclaimable_bytes + rows * self.bytes_per_row + max(0, allocated_bytes - self.allocated_bytes)+ ),+ ),+ bytes_per_row=self.bytes_per_row,+ live_rows=max(0, self.live_rows - rows),+ )++ def to_state(self, inserted_total: int, deleted_total: int) -> SizeCleanupState:+ return SizeCleanupState(+ allocated_bytes=self.allocated_bytes,+ reclaimable_bytes=self.reclaimable_bytes,+ bytes_per_row=self.bytes_per_row,+ inserted_total=inserted_total,+ deleted_total=deleted_total,+ )++Cutoff: TypeAlias = datetime | str"""Rows strictly older than this are expired: a timestamp, or an ISO calendar day for tables keyed by day"""@@ -87,6 +248,57 @@ class _RemainingRow(LiteLLMBaseModel):_REMAINING_ROWS: Final = TypeAdapter(list[_RemainingRow])++class _StorageRow(LiteLLMBaseModel):+ """One row of the storage probe, validated out of prisma's untyped result."""++ model_config = ConfigDict(frozen=True)+ allocated_bytes: int+ live_rows: int+ dead_rows: int+ inserted_total: int+ deleted_total: int+++_STORAGE_ROWS: Final = TypeAdapter(list[_StorageRow])+++class _SizeStateRow(LiteLLMBaseModel):+ model_config = ConfigDict(frozen=True)+ state_json: str+++_SIZE_STATE_ROWS: Final = TypeAdapter(list[_SizeStateRow])+SPEND_LOG_SIZE_CLEANUP_STATE_PARAM: Final = "spend_logs_size_cleanup_state"+_LOAD_SIZE_STATE_SQL: Final = 'SELECT param_value::text AS state_json FROM "LiteLLM_Config" WHERE param_name = $1'+_SAVE_SIZE_STATE_SQL: Final = """+ INSERT INTO "LiteLLM_Config" (param_name, param_value) VALUES ($1, $2::jsonb)+ ON CONFLICT (param_name) DO UPDATE SET param_value = EXCLUDED.param_value+ """+++_SPEND_LOG_TABLES: Final = ("LiteLLM_SpendLogs", "LiteLLM_SpendLogToolIndex")++# Partition children are counted with their parent: a partitioned parent has no storage of its own.+_STORAGE_SQL: Final = """+ SELECT coalesce(sum(pg_total_relation_size(s.relid)), 0)::bigint AS allocated_bytes,+ coalesce(sum(s.n_live_tup), 0)::bigint AS live_rows,+ coalesce(sum(s.n_dead_tup), 0)::bigint AS dead_rows,+ coalesce(sum(s.n_tup_ins), 0)::bigint AS inserted_total,+ coalesce(sum(s.n_tup_del), 0)::bigint AS deleted_total+ FROM pg_stat_user_tables s+ WHERE s.schemaname = current_schema()+ AND (+ s.relname = ANY($1::text[])+ OR s.relid IN (+ SELECT i.inhrelid FROM pg_inherits i+ JOIN pg_class p ON p.oid = i.inhparent+ JOIN pg_namespace n ON n.oid = p.relnamespace+ WHERE p.relname = ANY($1::text[]) AND n.nspname = current_schema()+ )+ )+ """+SPEND_LOG_CLEANUP_BOUND_SETTINGS: Final = ("maximum_spend_logs_cleanup_batch_size","maximum_spend_logs_cleanup_max_batches",@@ -244,6 +456,58 @@ class SpendLogCleanup:self.retention_seconds = self._retention_seconds_for("maximum_spend_logs_retention_period")return self.retention_seconds is not None+ async def _probe_storage(self, prisma_client: PrismaClient, deadline: float) -> StorageProbe | None:+ """Read what the spend-log tables weigh from the catalog, or None when the probe fails or has no budget."""+ if time.monotonic() >= deadline:+ return None+ timeout_ms: Final = self._timeout_ms(deadline)+ try:+ async with db_span("measure_storage", "LiteLLM_SpendLogs"), bounded_tx(prisma_client, timeout_ms) as tx:+ await tx.execute_raw(trusted_sql(f"SET LOCAL statement_timeout = {timeout_ms}"))+ rows: Final = _STORAGE_ROWS.validate_python(+ await tx.query_raw(trusted_sql(_STORAGE_SQL), list(_SPEND_LOG_TABLES))+ )+ except Exception as e: # noqa: BLE001 - a failed measurement skips the size pass, it must not fail the run+ verbose_proxy_logger.warning("Could not measure spend-log storage: %s: %s", type(e).__name__, e)+ return None+ if not rows:+ return None+ row: Final = rows[0]+ return StorageProbe(+ allocated_bytes=row.allocated_bytes,+ live_rows=row.live_rows,+ dead_rows=row.dead_rows,+ inserted_total=row.inserted_total,+ deleted_total=row.deleted_total,+ )++ async def _load_size_state(self, prisma_client: PrismaClient, deadline: float) -> SizeCleanupState | None:+ """The reclaimable count saved by the last check, or None on the first check or when it cannot be read."""+ if time.monotonic() >= deadline:+ return None+ timeout_ms: Final = self._timeout_ms(deadline)+ try:+ async with db_span("load_size_state", "LiteLLM_Config"), bounded_tx(prisma_client, timeout_ms) as tx:+ await tx.execute_raw(trusted_sql(f"SET LOCAL statement_timeout = {timeout_ms}"))+ rows: Final = _SIZE_STATE_ROWS.validate_python(+ await tx.query_raw(trusted_sql(_LOAD_SIZE_STATE_SQL), SPEND_LOG_SIZE_CLEANUP_STATE_PARAM)+ )+ return SizeCleanupState.model_validate_json(rows[0].state_json) if rows else None+ except Exception as e: # noqa: BLE001 - an unreadable count restarts from the catalog, it must not fail the run+ verbose_proxy_logger.warning("Could not read the spend-log size cleanup state: %s: %s", type(e).__name__, e)+ return None++ async def _save_size_state(self, prisma_client: PrismaClient, deadline: float, state: SizeCleanupState) -> None:+ timeout_ms: Final = max(self._timeout_ms(deadline), 1000)+ try:+ async with db_span("save_size_state", "LiteLLM_Config"), bounded_tx(prisma_client, timeout_ms) as tx:+ await tx.execute_raw(trusted_sql(f"SET LOCAL statement_timeout = {timeout_ms}"))+ await tx.execute_raw(+ trusted_sql(_SAVE_SIZE_STATE_SQL), SPEND_LOG_SIZE_CLEANUP_STATE_PARAM, state.model_dump_json()+ )+ except Exception as e: # noqa: BLE001 - a lost save costs one re-seed from the catalog, it must not fail the run+ verbose_proxy_logger.warning("Could not save the spend-log size cleanup state: %s: %s", type(e).__name__, e)+def _timeout_ms(self, deadline: float) -> int:"""The per-statement bound in milliseconds: the batch timeout, or whateverdiff --git a/tests/unit/proxy/test_spend_log_cleanup.py b/tests/unit/proxy/test_spend_log_cleanup.pyindex de4e5c90fe0..a9bc82d141d 100644--- a/tests/unit/proxy/test_spend_log_cleanup.py+++ b/tests/unit/proxy/test_spend_log_cleanup.py@@ -20,6 +20,10 @@ from litellm.constants import (SPEND_LOG_CLEANUP_RUN_BUDGET_SECONDS,)from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import (+ SizeCleanupState,+ SpendLogStorage,+ StorageProbe,+ advance_size_state,SPEND_LOG_CLEANUP_BOUND_SETTINGS,SpendLogCleanup,TableCleanupResult,@@ -88,10 +92,10 @@ def test_spend_log_cleanup_cron_scheduling():assert trigger_weekly is not None# Invalid cron expression should raise ValueError- with pytest.raises(ValueError, match='Wrong number of fields; got'):+ with pytest.raises(ValueError, match="Wrong number of fields; got"):CronTrigger.from_crontab("invalid cron")- with pytest.raises(ValueError, match='is higher than the maximum value'):+ with pytest.raises(ValueError, match="is higher than the maximum value"):CronTrigger.from_crontab("60 25 * * *") # Invalid minute and hour@@ -151,15 +155,11 @@ def test_spend_log_cleanup_cron_scheduler_integration():# No cron, so it should fall back to interval}- cleanup_cron_fallback = general_settings_interval.get(- "maximum_spend_logs_cleanup_cron"- )+ cleanup_cron_fallback = general_settings_interval.get("maximum_spend_logs_cleanup_cron")assert cleanup_cron_fallback is None # No cron configured# Simulate interval-based scheduling fallback- retention_interval = general_settings_interval.get(- "maximum_spend_logs_retention_interval", "1d"- )+ retention_interval = general_settings_interval.get("maximum_spend_logs_retention_interval", "1d")from litellm.litellm_core_utils.duration_parser import duration_in_secondsinterval_seconds = duration_in_seconds(retention_interval)@@ -187,27 +187,19 @@ async def test_should_delete_spend_logs():assert cleaner._should_delete_spend_logs() is False# Test case 2: Valid seconds string- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "3600s"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "3600s"})assert cleaner._should_delete_spend_logs() is True# Test case 3: Valid days string- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "30d"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "30d"})assert cleaner._should_delete_spend_logs() is True# Test case 4: Valid hours string- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "24h"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "24h"})assert cleaner._should_delete_spend_logs() is True# Test case 5: Invalid format- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "invalid"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "invalid"})assert cleaner._should_delete_spend_logs() is False@@ -338,9 +330,7 @@ async def test_cleanup_old_spend_logs_retention_period_cutoff():# Verify the cutoff date is correctcutoff_date = mock_db.execute_raw.call_args[0][1]expected_cutoff = datetime.now(timezone.utc) - timedelta(seconds=86400)- assert (- abs((cutoff_date - expected_cutoff).total_seconds()) < 1- ) # Allow 1 second difference for test execution time+ assert abs((cutoff_date - expected_cutoff).total_seconds()) < 1 # Allow 1 second difference for test execution time@pytest.mark.asyncio@@ -360,9 +350,7 @@ async def test_cleanup_drops_partitions_when_enabled_and_partitioned():partition_manager = MagicMock()partition_manager.is_partitioned = AsyncMock(return_value=True)partition_manager.ensure_partitions = AsyncMock(return_value=["p1"])- partition_manager.drop_partitions_older_than = AsyncMock(- return_value=["LiteLLM_SpendLogs_p20260601"]- )+ partition_manager.drop_partitions_older_than = AsyncMock(return_value=["LiteLLM_SpendLogs_p20260601"])cleaner = SpendLogCleanup(general_settings={@@ -500,9 +488,7 @@ async def test_integer_retention_treated_as_days():An integer value for maximum_spend_logs_retention_period should be treatedas days (e.g., 3 → '3d' → 259200 seconds)."""- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": 3}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": 3})result = cleaner._should_delete_spend_logs()assert result is Trueassert cleaner.retention_seconds == 3 * 86400 # 3 days in seconds@@ -519,13 +505,11 @@ def test_string_retention_still_works():("2w", 2 * 604800),]for setting, expected_seconds in cases:- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": setting}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": setting})assert cleaner._should_delete_spend_logs() is True, f"Failed for {setting}"- assert (- cleaner.retention_seconds == expected_seconds- ), f"Expected {expected_seconds} for {setting}, got {cleaner.retention_seconds}"+ assert cleaner.retention_seconds == expected_seconds, (+ f"Expected {expected_seconds} for {setting}, got {cleaner.retention_seconds}"+ )@pytest.mark.asyncio@@ -539,9 +523,7 @@ async def test_delete_old_logs_aborts_on_non_int_execute_raw_return():mock_db.execute_raw = AsyncMock(return_value=None)mock_prisma_client.db = mock_db- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_logs(mock_prisma_client, cutoff_date, _far_deadline())@@ -560,9 +542,7 @@ async def test_delete_old_logs_continues_on_valid_int_return():mock_db.execute_raw = AsyncMock(side_effect=[500, 300, 0])mock_prisma_client.db = mock_db- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_logs(mock_prisma_client, cutoff_date, _far_deadline())@@ -609,9 +589,7 @@ async def test_delete_old_tool_index_rows_deletes_on_composite_key():mock_db.execute_raw = AsyncMock(side_effect=[5, 0])mock_prisma_client.db = mock_db- cleaner = SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_tool_index_rows(mock_prisma_client, cutoff_date, _far_deadline())@@ -631,9 +609,7 @@ async def test_delete_old_logs_continues_after_single_batch_failure(monkeypatch)import litellm.proxy.db.db_transaction_queue.spend_log_cleanup as cleanup_module# Zero out the failure backoff so the test doesn't take ~0.5s of real sleep.- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0- )+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0)mock_prisma_client = MagicMock()_wire_tx(mock_prisma_client.db)@@ -641,14 +617,10 @@ async def test_delete_old_logs_continues_after_single_batch_failure(monkeypatch)_wire_tx(mock_db)# batch 1 succeeds, batch 2 raises (one-off DB timeout), batches 3-4 succeed,# batch 5 returns 0 → loop exits naturally.- mock_db.execute_raw = AsyncMock(- side_effect=[100, TimeoutError("simulated DB timeout"), 200, 50, 0]- )+ mock_db.execute_raw = AsyncMock(side_effect=[100, TimeoutError("simulated DB timeout"), 200, 50, 0])mock_prisma_client.db = mock_db- cleaner = cleanup_module.SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = cleanup_module.SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_logs(mock_prisma_client, cutoff_date, _far_deadline())@@ -665,26 +637,18 @@ async def test_delete_old_logs_aborts_after_consecutive_failures(monkeypatch):import litellm.proxy.db.db_transaction_queue.spend_log_cleanup as cleanup_module# Lower the threshold so the test is fast and deterministic.- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3- )- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0- )+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3)+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0)mock_prisma_client = MagicMock()_wire_tx(mock_prisma_client.db)mock_db = MagicMock()_wire_tx(mock_db)# Every batch raises — must abort after exactly 3 attempts, not loop forever.- mock_db.execute_raw = AsyncMock(- side_effect=ConnectionError("simulated persistent DB outage")- )+ mock_db.execute_raw = AsyncMock(side_effect=ConnectionError("simulated persistent DB outage"))mock_prisma_client.db = mock_db- cleaner = cleanup_module.SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = cleanup_module.SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_logs(mock_prisma_client, cutoff_date, _far_deadline())@@ -699,12 +663,8 @@ async def test_delete_old_logs_resets_consecutive_failures_on_success(monkeypatcintermittent timeouts don't trip the abort threshold."""import litellm.proxy.db.db_transaction_queue.spend_log_cleanup as cleanup_module- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3- )- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0- )+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3)+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0)mock_prisma_client = MagicMock()_wire_tx(mock_prisma_client.db)@@ -725,9 +685,7 @@ async def test_delete_old_logs_resets_consecutive_failures_on_success(monkeypatc)mock_prisma_client.db = mock_db- cleaner = cleanup_module.SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = cleanup_module.SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)result = await cleaner._delete_old_logs(mock_prisma_client, cutoff_date, _far_deadline())@@ -748,9 +706,7 @@ async def test_cleanup_uses_logger_exception_for_full_traceback(monkeypatch):mock_prisma_client = MagicMock()_wire_tx(mock_prisma_client.db)# Force the outer try/except to fire by making _should_delete_spend_logs raise.- cleaner = cleanup_module.SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = cleanup_module.SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cleaner.pod_lock_manager = Nonedef boom():@@ -775,12 +731,8 @@ async def test_cleanup_releases_lock_after_persistent_batch_failures(monkeypatchmust still be released so the next scheduled run isn't permanently blocked."""import litellm.proxy.db.db_transaction_queue.spend_log_cleanup as cleanup_module- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 2- )- monkeypatch.setattr(- cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0- )+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 2)+ monkeypatch.setattr(cleanup_module, "SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.0)mock_prisma_client = MagicMock()_wire_tx(mock_prisma_client.db)@@ -794,9 +746,7 @@ async def test_cleanup_releases_lock_after_persistent_batch_failures(monkeypatchmock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)mock_pod_lock_manager.release_lock = AsyncMock()- cleaner = cleanup_module.SpendLogCleanup(- general_settings={"maximum_spend_logs_retention_period": "7d"}- )+ cleaner = cleanup_module.SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})cleaner.pod_lock_manager = mock_pod_lock_managerawait cleaner.cleanup_old_spend_logs(mock_prisma_client)@@ -1081,9 +1031,7 @@ async def test_each_batch_carries_a_statement_and_lock_timeout():})- await cleaner._delete_old_logs(- mock_prisma_client, datetime.now(timezone.utc) - timedelta(days=7), _far_deadline()- )+ await cleaner._delete_old_logs(mock_prisma_client, datetime.now(timezone.utc) - timedelta(days=7), _far_deadline())assert "SET LOCAL statement_timeout = 12000" in recordedassert "SET LOCAL lock_timeout = 12000" in recorded@@ -1219,9 +1167,7 @@ async def test_remaining_rows_probe_is_capped_so_it_cannot_scan_the_table():cleaner = SpendLogCleanup(general_settings={"maximum_spend_logs_retention_period": "7d"})- await cleaner._delete_old_logs(- mock_prisma_client, datetime.now(timezone.utc) - timedelta(days=7), _far_deadline()- )+ await cleaner._delete_old_logs(mock_prisma_client, datetime.now(timezone.utc) - timedelta(days=7), _far_deadline())count_sql = mock_db.query_raw.call_args[0][0]assert "count(*)" in count_sql@@ -1733,3 +1679,159 @@ async def test_a_cleanup_delete_batch_renders_a_postgres_delete_span_for_its_tab)assert await postgres_span_names() == ("postgres.delete LiteLLM_SpendLogs",)+++# --- spend log storage measurement and the reclaimable-bytes state ---------------------------------------+++def _storage(allocated: int, live: int, dead: int, inserted: int | None = None, deleted: int | None = None) -> dict:+ return {+ "allocated_bytes": allocated,+ "live_rows": live,+ "dead_rows": dead,+ "inserted_total": live + dead if inserted is None else inserted,+ "deleted_total": dead if deleted is None else deleted,+ }+++ ("value", "expected"),+ [+ ("180GB", 180 * 1024**3),+ ("20 GiB", 20 * 1024**3),+ ("512MB", 512 * 1024**2),+ ("1.5TB", int(1.5 * 1024**4)),+ ("4096", 4096),+ (4096, 4096),+ ],+)+def test_size_in_bytes_reads_the_units_pg_size_pretty_prints(value, expected):+ from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import size_in_bytes++ assert size_in_bytes(value) == expected++[email protected]("value", ["", "big", "-1GB", "0", 0, "1PB"])+def test_size_in_bytes_rejects_what_cannot_be_a_size(value):+ from litellm.proxy.db.db_transaction_queue.spend_log_cleanup import size_in_bytes++ with pytest.raises(ValueError, match="size"):+ size_in_bytes(value)+++_RUN_STATE = SizeCleanupState(+ allocated_bytes=32_030_720,+ reclaimable_bytes=24_015_000,+ bytes_per_row=1601.0,+ inserted_total=20_000,+ deleted_total=15_000,+)+++ ("name", "probe", "reclaimable_expected"),+ [+ (+ "vacuum zeroed the dead rows, nothing else changed",+ _storage(32_030_720, 5000, 0, 20_000, 15_000),+ 24_015_000,+ ),+ ("7000 new rows written into the free space", _storage(32_030_720, 12_000, 0, 27_000, 15_000), 12_808_000),+ (+ "7000 new rows that all grew the files",+ _storage(32_030_720 + 7000 * 1601, 12_000, 0, 27_000, 15_000),+ 24_015_000,+ ),+ ("VACUUM FULL handed the free space back", _storage(8_015_720, 5000, 0, 20_000, 15_000), 0),+ (+ "statistics wiped while the files still hold data: the count is carried forward, not reseeded",+ _storage(32_030_720, 0, 0, 0, 0),+ 24_015_000,+ ),+ ("the retention job deleted 2000 more rows", _storage(32_030_720, 3000, 2000, 20_000, 17_000), 27_217_000),+ (+ "statistics reset: counters restart from the dead rows",+ _storage(32_030_720, 5000, 1000, 5000, 1000),+ 5_338_453,+ ),+ ],+)+def test_advance_size_state_tracks_free_space_through_vacuum_inserts_and_other_deletes(+ name, probe, reclaimable_expected+):+ advanced = advance_size_state(_RUN_STATE, StorageProbe(**probe))++ assert advanced.reclaimable_bytes == reclaimable_expected, name+ assert 0 <= probe["allocated_bytes"] - advanced.reclaimable_bytes <= probe["allocated_bytes"], name+++def test_after_deleting_counts_the_rows_and_any_file_growth_as_reclaimable_and_to_state_keeps_the_counters():+ storage = SpendLogStorage(allocated_bytes=32_030_720, reclaimable_bytes=0, bytes_per_row=1601.0, live_rows=20_000)++ after = storage.after_deleting(15_000, 32_030_720 + 8192)++ assert (after.reclaimable_bytes, after.live_rows, after.estimated_live_bytes) == (24_023_192, 5000, 8_015_720)+ assert after.to_state(inserted_total=20_000, deleted_total=15_000) == SizeCleanupState(+ allocated_bytes=32_038_912,+ reclaimable_bytes=24_023_192,+ bytes_per_row=1601.0,+ inserted_total=20_000,+ deleted_total=15_000,+ )+ assert StorageProbe(+ allocated_bytes=8192, live_rows=0, dead_rows=0, inserted_total=0, deleted_total=0+ ).stats_are_stale+++async def test_probe_storage_reads_the_catalog_row_for_both_tables_and_a_failed_probe_is_none(caplog):+ prisma_client = MagicMock()+ _wire_tx(prisma_client.db)+ prisma_client.db.query_raw = AsyncMock(return_value=[_storage(32_030_720, 20_000, 0)])+ cleaner = SpendLogCleanup(general_settings={})++ probe = await cleaner._probe_storage(prisma_client, _far_deadline())++ assert probe is not None+ assert (probe.allocated_bytes, probe.live_rows, probe.dead_rows, probe.inserted_total, probe.deleted_total) == (+ 32_030_720,+ 20_000,+ 0,+ 20_000,+ 0,+ )+ assert prisma_client.db.query_raw.call_args.args[1] == ["LiteLLM_SpendLogs", "LiteLLM_SpendLogToolIndex"]++ prisma_client.db.query_raw = AsyncMock(side_effect=RuntimeError("pg_stat_user_tables unavailable"))+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):+ assert await cleaner._probe_storage(prisma_client, _far_deadline()) is None+ assert any("Could not measure spend-log storage" in record.getMessage() for record in caplog.records)+++async def test_size_state_round_trips_through_its_litellm_config_row_and_a_lost_save_is_only_a_warning(caplog):+ saved = {}+ prisma_client = MagicMock()+ _wire_tx(prisma_client.db)++ async def execute_raw(sql, *args):+ saved[args[0]] = args[1]+ return 1++ prisma_client.db.execute_raw = execute_raw+ prisma_client.db.query_raw = AsyncMock(+ side_effect=lambda sql, param: [{"state_json": saved[param]}] if param in saved else []+ )+ cleaner = SpendLogCleanup(general_settings={})++ assert await cleaner._load_size_state(prisma_client, _far_deadline()) is None+ await cleaner._save_size_state(prisma_client, _far_deadline(), _RUN_STATE)+ assert list(saved) == ["spend_logs_size_cleanup_state"]+ loaded = await cleaner._load_size_state(prisma_client, _far_deadline())+ assert loaded is not None+ assert loaded.model_dump() == _RUN_STATE.model_dump()++ prisma_client.db.execute_raw = AsyncMock(side_effect=RuntimeError("LiteLLM_Config is read only"))+ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):+ await cleaner._save_size_state(prisma_client, _far_deadline(), _RUN_STATE)+ assert any("Could not save the spend-log size cleanup state" in record.getMessage() for record in caplog.records)