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
merge: resolve conflict with origin/main in test_db_spend_update_writer.py
Ryan Crabbe1c1b9cda42ae
diff --cc tests/test_litellm/proxy/db/test_db_spend_update_writer.pyindex add7293285a,2a0428e2f07..abd59a66a36--- a/tests/test_litellm/proxy/db/test_db_spend_update_writer.py+++ b/tests/test_litellm/proxy/db/test_db_spend_update_writer.py@@@ -1090,167 -1078,44 +1090,210 @@@ async def test_commit_key_spend_updatesassert before_call <= last_active <= after_call+async def test_update_database_creates_single_task():+ """+ Test that update_database() fires exactly 1 asyncio.create_task() call+ (the batched task) instead of the previous 11.+ """+ db_writer = DBSpendUpdateWriter()++ # Mock all helpers so nothing real runs+ db_writer._insert_spend_log_to_db = AsyncMock()+ db_writer._batch_database_updates = AsyncMock()++ with patch("litellm.proxy.proxy_server.disable_spend_logs", False), patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), patch(+ "litellm.proxy.proxy_server.litellm_proxy_budget_name", "test-budget"+ ), patch(+ "litellm.proxy.db.db_spend_update_writer.asyncio.create_task"+ ) as mock_create_task:+ await db_writer.update_database(+ token="test-token",+ user_id="test-user",+ end_user_id="test-end-user",+ start_time=datetime.now(),+ end_time=datetime.now(),+ team_id="test-team",+ org_id="test-org",+ completion_response=MagicMock(),+ response_cost=0.1,+ kwargs={"model": "gpt-4", "custom_llm_provider": "openai"},+ )++ # Exactly 1 create_task call (the batch), not 11+ assert mock_create_task.call_count == 1+++async def test_batch_database_updates_isolation_on_failure():+ """+ Test that if one helper inside _batch_database_updates raises,+ all other helpers still execute.+ """+ db_writer = DBSpendUpdateWriter()++ # Make _update_key_db raise+ db_writer._update_key_db = AsyncMock(side_effect=RuntimeError("key db boom"))++ # All other helpers are normal mocks+ db_writer._update_user_db = AsyncMock()+ db_writer._update_team_db = AsyncMock()+ db_writer._update_org_db = AsyncMock()+ db_writer._update_tag_db = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_user_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_end_user_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_agent_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_team_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_org_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_tag_transaction = AsyncMock()++ await db_writer._batch_database_updates(+ response_cost=0.1,+ user_id="u1",+ hashed_token="t1",+ team_id="team1",+ org_id="org1",+ end_user_id="eu1",+ prisma_client=MagicMock(),+ user_api_key_cache=MagicMock(),+ litellm_proxy_budget_name="budget",+ payload_copy={"key": "value"},+ request_tags=None,+ )++ # _update_key_db raised, but all others should still have been called+ db_writer._update_user_db.assert_awaited_once()+ db_writer._update_key_db.assert_awaited_once()+ db_writer._update_team_db.assert_awaited_once()+ db_writer._update_org_db.assert_awaited_once()+ db_writer._update_tag_db.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_user_transaction.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_end_user_transaction.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_agent_transaction.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_team_transaction.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_org_transaction.assert_awaited_once()+ db_writer.add_spend_log_transaction_to_daily_tag_transaction.assert_awaited_once()+++async def test_daily_agent_receives_deepcopied_payload():+ """+ Test that the daily agent handler receives a deepcopied payload (not the original).++ Previously, add_spend_log_transaction_to_daily_agent_transaction received the raw+ payload without a deepcopy, which was a mutation bug. This test goes through+ update_database() to verify the production deepcopy path.+ """+ db_writer = DBSpendUpdateWriter()++ # Capture the payload object that get_logging_payload returns (the "original")+ # and the payload the agent handler receives (should be a deepcopy)+ original_payload_ref = {}+ captured_agent_payloads = []++ async def capture_agent_payload(**kwargs):+ captured_agent_payloads.append(kwargs.get("payload"))++ # Mock all helpers+ db_writer._insert_spend_log_to_db = AsyncMock()+ db_writer._update_user_db = AsyncMock()+ db_writer._update_key_db = AsyncMock()+ db_writer._update_team_db = AsyncMock()+ db_writer._update_org_db = AsyncMock()+ db_writer._update_tag_db = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_user_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_end_user_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_agent_transaction = AsyncMock(+ side_effect=capture_agent_payload+ )+ db_writer.add_spend_log_transaction_to_daily_team_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_org_transaction = AsyncMock()+ db_writer.add_spend_log_transaction_to_daily_tag_transaction = AsyncMock()++ # Mock get_logging_payload to return a known dict and capture its identity+ fake_payload = {+ "startTime": "2024-01-01T00:00:00",+ "endTime": "2024-01-01T00:01:00",+ "model": "gpt-4",+ "custom_llm_provider": "openai",+ "spend": 0.0,+ "nested": {"a": 1},+ }+ original_payload_ref["obj"] = fake_payload # store reference to the original++ with patch("litellm.proxy.proxy_server.disable_spend_logs", True), patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), patch(+ "litellm.proxy.proxy_server.litellm_proxy_budget_name", "test-budget"+ ), patch(+ "litellm.proxy.spend_tracking.spend_tracking_utils.get_logging_payload",+ return_value=fake_payload,+ ):+ await db_writer.update_database(+ token="test-token",+ user_id="test-user",+ end_user_id="test-end-user",+ team_id="test-team",+ org_id="test-org",+ kwargs={"model": "gpt-4", "custom_llm_provider": "openai"},+ completion_response=MagicMock(),+ start_time=datetime.now(),+ end_time=datetime.now(),+ response_cost=0.1,+ )++ # Let the single batched task run+ await asyncio.sleep(0)++ # The agent handler should have been called+ assert len(captured_agent_payloads) == 1+ # The payload must NOT be the same object as the original (deepcopy occurred)+ assert captured_agent_payloads[0] is not original_payload_ref["obj"]+ # But it should have equivalent content+ assert captured_agent_payloads[0]["model"] == "gpt-4"+ assert captured_agent_payloads[0]["spend"] == 0.1+++++ @pytest.mark.asyncio+ async def test_commit_spend_updates_uses_pipeline():+ """+ Verify that _commit_spend_updates_to_db_with_redis uses+ get_all_transactions_from_redis_buffer_pipeline instead of 7 individual calls.+ """+ db_writer = DBSpendUpdateWriter()++ mock_redis_update_buffer = AsyncMock()+ mock_redis_update_buffer.store_in_memory_spend_updates_in_redis = AsyncMock()+ # Return all-None tuple (no data to commit)+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline = AsyncMock(+ return_value=(None, None, None, None, None, None, None)+ )+ 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++ mock_prisma_client = MagicMock()+ mock_proxy_logging = MagicMock()++ await db_writer._commit_spend_updates_to_db_with_redis(+ prisma_client=mock_prisma_client,+ n_retry_times=1,+ proxy_logging_obj=mock_proxy_logging,+ )++ # Pipeline method should be called once+ mock_redis_update_buffer.get_all_transactions_from_redis_buffer_pipeline.assert_called_once()++ # Individual methods should NOT be called+ mock_redis_update_buffer.get_all_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_spend_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_team_spend_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_org_spend_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_end_user_spend_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_agent_spend_update_transactions_from_redis_buffer.assert_not_called()+ mock_redis_update_buffer.get_all_daily_tag_spend_update_transactions_from_redis_buffer.assert_not_called()