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]

Fix spend log cleanup: lock tracking, integer retention, skip log level

yuneng-jiang224c61711948
diff --git a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
index 8c59c79ff0a..6db7d6dd43c 100644
--- a/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
+++ b/litellm/proxy/db/db_transaction_queue/spend_log_cleanup.py
@@ -49,7 +49,11 @@ class SpendLogCleanup:
try:
if isinstance(retention_setting, int):
- retention_setting = str(retention_setting)
+ verbose_proxy_logger.warning(
+ f"maximum_spend_logs_retention_period is an integer ({retention_setting}); treating as days. "
+ "Use a string like '3d' to be explicit."
+ )
+ retention_setting = f"{retention_setting}d"
self.retention_seconds = duration_in_seconds(retention_setting)
verbose_proxy_logger.info(
f"Retention period set to {self.retention_seconds} seconds"
@@ -112,11 +116,12 @@ class SpendLogCleanup:
If pod_lock_manager is available, ensures only one pod runs cleanup.
If no pod_lock_manager, runs cleanup without distributed locking.
"""
+ lock_acquired = False
try:
verbose_proxy_logger.info(f"Cleanup job triggered at {datetime.now()}")
if not self._should_delete_spend_logs():
- verbose_proxy_logger.info(
+ verbose_proxy_logger.error(
"Skipping cleanup — invalid or missing retention setting."
)
return
@@ -155,8 +160,8 @@ class SpendLogCleanup:
verbose_proxy_logger.error(f"Error during cleanup: {str(e)}")
return # Return after error handling
finally:
- # Always release the lock if we have a pod lock manager
- if self.pod_lock_manager and self.pod_lock_manager.redis_cache:
+ # Only release the lock if it was actually acquired
+ if lock_acquired and self.pod_lock_manager and self.pod_lock_manager.redis_cache:
await self.pod_lock_manager.release_lock(
cronjob_id=SPEND_LOG_CLEANUP_JOB_NAME
)
diff --git a/tests/test_litellm/proxy/test_spend_log_cleanup.py b/tests/test_litellm/proxy/test_spend_log_cleanup.py
index c1fa3ad0c43..3a01437908d 100644
--- a/tests/test_litellm/proxy/test_spend_log_cleanup.py
+++ b/tests/test_litellm/proxy/test_spend_log_cleanup.py
@@ -233,6 +233,65 @@ async def test_cleanup_old_spend_logs_no_retention_period():
mock_prisma_client.db.execute_raw.assert_not_called()
+async def test_lock_not_released_when_not_acquired():
+ """
+ Lock release should be skipped when _should_delete_spend_logs returns False
+ before the lock is ever acquired.
+ """
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.execute_raw = AsyncMock()
+
+ mock_redis_cache = MagicMock()
+ mock_pod_lock_manager = MagicMock()
+ mock_pod_lock_manager.redis_cache = mock_redis_cache
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+
+ # No retention setting → _should_delete_spend_logs() returns False before lock is acquired
+ cleaner = SpendLogCleanup(general_settings={})
+ cleaner.pod_lock_manager = mock_pod_lock_manager
+
+ await cleaner.cleanup_old_spend_logs(mock_prisma_client)
+
+ mock_pod_lock_manager.acquire_lock.assert_not_called()
+ mock_pod_lock_manager.release_lock.assert_not_called()
+
+
+async def test_integer_retention_treated_as_days():
+ """
+ An integer value for maximum_spend_logs_retention_period should be treated
+ as days (e.g., 3 → '3d' → 259200 seconds).
+ """
+ cleaner = SpendLogCleanup(
+ general_settings={"maximum_spend_logs_retention_period": 3}
+ )
+ result = cleaner._should_delete_spend_logs()
+ assert result is True
+ assert cleaner.retention_seconds == 3 * 86400 # 3 days in seconds
+
+
+def test_string_retention_still_works():
+ """
+ String values like '3d', '24h', '3600s' should continue to parse correctly.
+ """
+ cases = [
+ ("3d", 3 * 86400),
+ ("24h", 24 * 3600),
+ ("3600s", 3600),
+ ("2w", 2 * 604800),
+ ]
+ for setting, expected_seconds in cases:
+ 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}"
+ )
+
+
def test_cleanup_batch_size_env_var(monkeypatch):
"""Ensure batch size is configurable via environment variable"""
import importlib