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]

Merge origin/main into litellm_fix_streaming_connection_pool_leak

Ryan Crabbe5bcaeabfd84a
diff --cc tests/test_litellm/proxy/test_proxy_server.py
index c4d549b72be,ab414db3569..5f54c151d83
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@@ -3331,152 -3519,294 +3519,445 @@@ class TestInvitationEndpoints
assert "not allowed" in str(error_content).lower()
+async def test_async_data_generator_cleanup_on_early_exit():
+ """
+ Test that async_data_generator calls response.aclose() in the finally block
+ when the generator is abandoned mid-stream (client disconnect).
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.proxy_server import async_data_generator
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_request_data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "test"}],
+ }
+
+ mock_chunks = [
+ {"choices": [{"delta": {"content": "Hello"}}]},
+ {"choices": [{"delta": {"content": " world"}}]},
+ {"choices": [{"delta": {"content": " more"}}]},
+ ]
+
+ mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ async def mock_streaming_iterator(*args, **kwargs):
+ for chunk in mock_chunks:
+ yield chunk
+
+ mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = (
+ mock_streaming_iterator
+ )
+ mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
+ side_effect=lambda **kwargs: kwargs.get("response")
+ )
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+
+ # Create a mock response with aclose
+ mock_response = MagicMock()
+ mock_response.aclose = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
+ # Consume only the first chunk then abandon the generator (simulates client disconnect)
+ gen = async_data_generator(
+ mock_response, mock_user_api_key_dict, mock_request_data
+ )
+ first_chunk = await gen.__anext__()
+ assert first_chunk.startswith("data: ")
+
+ # Close the generator early (simulates what ASGI does on client disconnect)
+ await gen.aclose()
+
+ # Verify aclose was called on the response to release the HTTP connection
+ mock_response.aclose.assert_awaited_once()
+
+
+async def test_async_data_generator_cleanup_on_normal_completion():
+ """
+ Test that async_data_generator calls response.aclose() even on normal completion.
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.proxy_server import async_data_generator
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_request_data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "test"}],
+ }
+
+ mock_chunks = [
+ {"choices": [{"delta": {"content": "Hello"}}]},
+ ]
+
+ mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ async def mock_streaming_iterator(*args, **kwargs):
+ for chunk in mock_chunks:
+ yield chunk
+
+ mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = (
+ mock_streaming_iterator
+ )
+ mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
+ side_effect=lambda **kwargs: kwargs.get("response")
+ )
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+
+ mock_response = MagicMock()
+ mock_response.aclose = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
+ yielded_data = []
+ async for data in async_data_generator(
+ mock_response, mock_user_api_key_dict, mock_request_data
+ ):
+ yielded_data.append(data)
+
+ # Should have completed normally with [DONE]
+ assert any("[DONE]" in d for d in yielded_data)
+ # aclose should still be called via finally block
+ mock_response.aclose.assert_awaited_once()
+
+
+async def test_async_data_generator_cleanup_on_midstream_error():
+ """
+ Test that async_data_generator calls response.aclose() via finally block
+ even when an exception occurs mid-stream.
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.proxy_server import async_data_generator
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)
+ mock_request_data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "test"}],
+ }
+
+ mock_proxy_logging_obj = MagicMock(spec=ProxyLogging)
+
+ async def mock_streaming_iterator_with_error(*args, **kwargs):
+ yield {"choices": [{"delta": {"content": "Hello"}}]}
+ raise RuntimeError("upstream connection reset")
+
+ mock_proxy_logging_obj.async_post_call_streaming_iterator_hook = (
+ mock_streaming_iterator_with_error
+ )
+ mock_proxy_logging_obj.async_post_call_streaming_hook = AsyncMock(
+ side_effect=lambda **kwargs: kwargs.get("response")
+ )
+ mock_proxy_logging_obj.post_call_failure_hook = AsyncMock()
+
+ mock_response = MagicMock()
+ mock_response.aclose = AsyncMock()
+
+ with patch("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj):
+ yielded_data = []
+ async for data in async_data_generator(
+ mock_response, mock_user_api_key_dict, mock_request_data
+ ):
+ yielded_data.append(data)
+
+ # Should have yielded data chunk and then an error chunk
+ assert len(yielded_data) >= 2
+ assert any("error" in d for d in yielded_data)
+ # aclose must still be called via finally block despite the error
+ mock_response.aclose.assert_awaited_once()
++
++
+ # ============================================================================
+ # store_model_in_db DB Config Override Tests
+ # ============================================================================
+
+
+ def test_store_model_in_db_in_config_general_settings():
+ """
+ Verify store_model_in_db is a valid field in ConfigGeneralSettings
+ and validates correctly for True/False values.
+ """
+ from litellm.proxy._types import ConfigGeneralSettings
+
+ assert "store_model_in_db" in ConfigGeneralSettings.model_fields
+
+ # Should validate with True
+ config = ConfigGeneralSettings(store_model_in_db=True)
+ assert config.store_model_in_db is True
+
+ # Should validate with False
+ config = ConfigGeneralSettings(store_model_in_db=False)
+ assert config.store_model_in_db is False
+
+ # Should validate with None (default)
+ config = ConfigGeneralSettings(store_model_in_db=None)
+ assert config.store_model_in_db is None
+
+ # Should validate with no value
+ config = ConfigGeneralSettings()
+ assert config.store_model_in_db is None
+
+
+ @pytest.mark.asyncio
+ async def test_update_general_settings_store_model_in_db_true():
+ """
+ Verify _update_general_settings sets global store_model_in_db to True
+ when DB general_settings has store_model_in_db=True.
+ """
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ proxy_config = ProxyConfig()
+
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ) as mock_store, patch(
+ "litellm.proxy.proxy_server.general_settings", {}
+ ) as mock_gs:
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": True}
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is True
+ assert ps.general_settings["store_model_in_db"] is True
+
+
+ @pytest.mark.asyncio
+ async def test_update_general_settings_store_model_in_db_false():
+ """
+ Verify _update_general_settings sets global store_model_in_db to False
+ when DB general_settings has store_model_in_db=False.
+ """
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ proxy_config = ProxyConfig()
+
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", True
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": False}
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is False
+ assert ps.general_settings["store_model_in_db"] is False
+
+
+ @pytest.mark.asyncio
+ async def test_update_general_settings_store_model_in_db_string_normalization():
+ """
+ Verify _update_general_settings normalizes string values for store_model_in_db.
+ """
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ proxy_config = ProxyConfig()
+
+ # Test "true" string
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": "true"}
+ )
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is True
+
+ # Test "True" string
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": "True"}
+ )
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is True
+
+ # Test "false" string
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", True
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": "false"}
+ )
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is False
+
+
+ @pytest.mark.asyncio
+ async def test_update_general_settings_store_model_in_db_none_keeps_current():
+ """
+ Verify _update_general_settings does not change store_model_in_db
+ when DB value is None.
+ """
+ from litellm.proxy.proxy_server import ProxyConfig
+
+ proxy_config = ProxyConfig()
+
+ # When current is True and DB sends None, should stay True
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", True
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": None}
+ )
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is True
+
+ # When current is False and DB sends None, should stay False
+ with patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ), patch("litellm.proxy.proxy_server.general_settings", {}):
+ await proxy_config._update_general_settings(
+ db_general_settings={"store_model_in_db": None}
+ )
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is False
+
+
+ @pytest.mark.asyncio
+ async def test_store_model_in_db_db_override_when_config_false():
+ """
+ Verify the early DB check in initialize_scheduled_background_jobs
+ overrides store_model_in_db=False when DB has True.
+ """
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_prisma_client = MagicMock()
+
+ # Mock DB returning store_model_in_db=True in general_settings
+ mock_db_record = MagicMock()
+ mock_db_record.param_value = {"store_model_in_db": True}
+ mock_prisma_client.db.litellm_config.find_first = AsyncMock(
+ return_value=mock_db_record
+ )
+
+ mock_proxy_logging = MagicMock(spec=ProxyLogging)
+ mock_proxy_logging.slack_alerting_instance = MagicMock()
+ mock_proxy_config = AsyncMock()
+
+ with patch(
+ "litellm.proxy.proxy_server.proxy_config", mock_proxy_config
+ ), patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ), patch(
+ "litellm.proxy.proxy_server.get_secret_bool", return_value=False
+ ):
+ await ProxyStartupEvent.initialize_scheduled_background_jobs(
+ general_settings={},
+ prisma_client=mock_prisma_client,
+ proxy_budget_rescheduler_min_time=1,
+ proxy_budget_rescheduler_max_time=2,
+ proxy_batch_write_at=5,
+ proxy_logging_obj=mock_proxy_logging,
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ # store_model_in_db should now be True (overridden by DB)
+ assert ps.store_model_in_db is True
+
+ # add_deployment and get_credentials should have been called
+ # since store_model_in_db is now True
+ assert mock_proxy_config.add_deployment.call_count == 1
+ assert mock_proxy_config.get_credentials.call_count == 1
+
+
+ @pytest.mark.asyncio
+ async def test_store_model_in_db_db_check_skipped_when_already_true(monkeypatch):
+ """
+ Verify the early DB check is skipped when store_model_in_db is already True.
+ The DB query for the early check should not be called.
+ """
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_config.find_first = AsyncMock(return_value=None)
+
+ mock_proxy_logging = MagicMock(spec=ProxyLogging)
+ mock_proxy_logging.slack_alerting_instance = MagicMock()
+ mock_proxy_config = AsyncMock()
+
+ with patch(
+ "litellm.proxy.proxy_server.proxy_config", mock_proxy_config
+ ), patch(
+ "litellm.proxy.proxy_server.store_model_in_db", True
+ ), patch(
+ "litellm.proxy.proxy_server.get_secret_bool", return_value=True
+ ):
+ await ProxyStartupEvent.initialize_scheduled_background_jobs(
+ general_settings={},
+ prisma_client=mock_prisma_client,
+ proxy_budget_rescheduler_min_time=1,
+ proxy_budget_rescheduler_max_time=2,
+ proxy_batch_write_at=5,
+ proxy_logging_obj=mock_proxy_logging,
+ )
+
+ # The early DB check uses find_first with param_name="general_settings".
+ # When store_model_in_db is already True, the early check should be skipped.
+ # However, add_deployment may also call find_first.
+ # We just verify that store_model_in_db stays True and jobs are scheduled.
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.store_model_in_db is True
+ assert mock_proxy_config.add_deployment.call_count == 1
+
+
+ @pytest.mark.asyncio
+ async def test_store_model_in_db_db_failure_graceful(monkeypatch):
+ """
+ Verify the early DB check handles DB failures gracefully
+ without crashing and keeps store_model_in_db as False.
+ """
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_prisma_client = MagicMock()
+ # Simulate DB failure
+ mock_prisma_client.db.litellm_config.find_first = AsyncMock(
+ side_effect=Exception("DB connection error")
+ )
+
+ mock_proxy_logging = MagicMock(spec=ProxyLogging)
+ mock_proxy_logging.slack_alerting_instance = MagicMock()
+ mock_proxy_config = AsyncMock()
+
+ with patch(
+ "litellm.proxy.proxy_server.proxy_config", mock_proxy_config
+ ), patch(
+ "litellm.proxy.proxy_server.store_model_in_db", False
+ ), patch(
+ "litellm.proxy.proxy_server.get_secret_bool", return_value=False
+ ):
+ # Should not raise an exception
+ await ProxyStartupEvent.initialize_scheduled_background_jobs(
+ general_settings={},
+ prisma_client=mock_prisma_client,
+ proxy_budget_rescheduler_min_time=1,
+ proxy_budget_rescheduler_max_time=2,
+ proxy_batch_write_at=5,
+ proxy_logging_obj=mock_proxy_logging,
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ # store_model_in_db should remain False
+ assert ps.store_model_in_db is False
+
+ # add_deployment should NOT have been called since store_model_in_db is False
+ mock_proxy_config.add_deployment.assert_not_called()