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(proxy): keep tag drain inside try and cover requeue paths with tests

Devin AI118b47a8a39a
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.py
index cc266019ff7..f13bf2e2105 100644
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@ -797,11 +797,7 @@ class DBSpendUpdateWriter:
):
verbose_proxy_logger.debug("acquired lock for spend updates")
- # Track everything popped from Redis. Each category is removed once it
- # has been committed to the DB, so whatever is left after a failure can
- # be re-queued for the next tick instead of being lost. Committed
- # categories are never re-queued, so their spend is not double-counted.
- uncommitted: dict[str, Any] = {} # mutable-ok: drives which popped categories still need re-queuing
+ uncommitted: dict[str, Any] = {} # mutable-ok: tracks popped categories still needing commit
try:
(
@@ -1048,11 +1044,12 @@ class DBSpendUpdateWriter:
cronjob_id=DB_DAILY_TAG_SPEND_UPDATE_JOB_NAME,
):
verbose_proxy_logger.debug("acquired lock for daily tag spend updates")
- daily_tag_spend_update_transactions = (
- await self.redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer()
- )
+ daily_tag_spend_update_transactions: dict[str, DailyTagSpendTransaction] | None = None
committed = False
try:
+ daily_tag_spend_update_transactions = (
+ await self.redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer()
+ )
if daily_tag_spend_update_transactions:
await DBSpendUpdateWriter.update_daily_tag_spend(
n_retry_times=n_retry_times,
diff --git a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
index b30fadd86ab..660fd514d99 100644
--- a/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
+++ b/litellm/proxy/db/db_transaction_queue/redis_update_buffer.py
@@ -6,6 +6,7 @@ This is to prevent deadlocks and improve reliability
import asyncio
import json
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast
from redis.exceptions import RedisError
@@ -379,12 +380,12 @@ class RedisUpdateBuffer:
async def restore_transactions_to_redis(
self,
db_spend_update_transactions: DBSpendUpdateTransactions | None = None,
- daily_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
- daily_team_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
- daily_org_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
- daily_end_user_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
- daily_agent_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
- daily_tag_spend_update_transactions: dict[str, BaseDailySpendTransaction] | None = None,
+ daily_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_team_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_org_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_end_user_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_agent_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
+ daily_tag_spend_update_transactions: Mapping[str, BaseDailySpendTransaction] | None = None,
) -> None:
"""
Re-push transactions that were popped from Redis but not committed to the DB.
diff --git a/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py b/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
index 79909561683..3325893c5f6 100644
--- a/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
+++ b/tests/test_litellm/proxy/db/db_transaction_queue/test_redis_update_buffer.py
@@ -316,6 +316,24 @@ async def test_restore_transactions_to_redis_noop_when_empty(
mock_redis_cache.async_rpush_pipeline.assert_not_called()
+async def test_restore_transactions_to_redis_swallows_redis_error(
+ redis_update_buffer, mock_redis_cache
+):
+ """A Redis failure during restore must not propagate to the caller's finally block."""
+ from redis.exceptions import RedisError
+
+ mock_redis_cache.async_rpush_pipeline = AsyncMock(
+ side_effect=RedisError("redis down")
+ )
+
+ await redis_update_buffer.restore_transactions_to_redis(
+ db_spend_update_transactions={"key_list_transactions": {"key1": 1.0}},
+ )
+
+ mock_redis_cache.async_rpush_pipeline.assert_called_once()
+
+
def test_validate_redis_transaction_buffer_raises_without_redis():
"""
When use_redis_transaction_buffer=true but no Redis cache is configured,
diff --git a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
index 10544e82453..06d06b50234 100644
--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py
@@ -1712,6 +1712,78 @@ async def test_commit_with_redis_no_requeue_on_success():
mock_redis_update_buffer.restore_transactions_to_redis.assert_not_awaited()
+async def test_commit_daily_tag_spend_requeues_on_db_failure():
+ """A failed daily tag commit must re-queue the popped tag transactions and release the lock."""
+ db_writer = DBSpendUpdateWriter()
+
+ daily_tag = {"tag_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.store_in_memory_daily_tag_spend_updates_in_redis = AsyncMock()
+ mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer = AsyncMock(
+ return_value=daily_tag
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_tag_spend",
+ new=AsyncMock(side_effect=Exception("db down")),
+ ):
+ await db_writer._commit_daily_tag_spend_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_awaited_once_with(
+ daily_tag_spend_update_transactions=daily_tag,
+ )
+ mock_pod_lock_manager.release_lock.assert_awaited_once()
+
+
+async def test_commit_daily_tag_spend_no_requeue_on_success():
+ """A successful daily tag commit must not re-queue anything."""
+ db_writer = DBSpendUpdateWriter()
+
+ daily_tag = {"tag_key1": {"spend": 1.5, "api_requests": 1}}
+
+ mock_redis_update_buffer = AsyncMock()
+ mock_redis_update_buffer.store_in_memory_daily_tag_spend_updates_in_redis = AsyncMock()
+ mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer = AsyncMock(
+ return_value=daily_tag
+ )
+ mock_redis_update_buffer.restore_transactions_to_redis = AsyncMock()
+ db_writer.redis_update_buffer = mock_redis_update_buffer
+
+ mock_pod_lock_manager = AsyncMock()
+ mock_pod_lock_manager.acquire_lock = AsyncMock(return_value=True)
+ mock_pod_lock_manager.release_lock = AsyncMock()
+ db_writer.pod_lock_manager = mock_pod_lock_manager
+
+ with patch.object(
+ DBSpendUpdateWriter,
+ "update_daily_tag_spend",
+ new=AsyncMock(),
+ ):
+ await db_writer._commit_daily_tag_spend_to_db_with_redis(
+ prisma_client=MagicMock(),
+ n_retry_times=0,
+ proxy_logging_obj=MagicMock(),
+ )
+
+ mock_redis_update_buffer.restore_transactions_to_redis.assert_not_awaited()
+ mock_pod_lock_manager.release_lock.assert_awaited_once()
+
+
@pytest.mark.parametrize(
"bucket_name,input_dict,table_attr,method_name,where_key,expected_order",
[