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
fix(proxy): tolerate a concurrent creator when creating spend views
Yuneng Jiang77e64c5d4015
diff --git a/litellm/proxy/db/create_views.py b/litellm/proxy/db/create_views.pyindex 141ce92f172..7b7db19b4e3 100644--- a/litellm/proxy/db/create_views.py+++ b/litellm/proxy/db/create_views.py@@ -10,6 +10,29 @@ _db = Any# 'undefined function' or 'column undefined_col referenced in query')._VIEW_NOT_FOUND_MARKERS: Final = ("does not exist", "no such table", "undefined table")+# Markers for the inverse condition: another replica created the view between+# our existence probe and our CREATE.+_VIEW_ALREADY_EXISTS_MARKERS: Final = ("already exists", "duplicate object", "duplicate table")+++async def create_view_tolerating_race(db: _db, view_name: str, ddl: str) -> None:+ """+ Create a view, treating "a concurrent creator won" as success.++ Every replica booting against the same fresh database observes the view as+ absent and issues the CREATE; Postgres fails all but one with a+ duplicate-object error. The desired end state is still reached, so losing+ that race is success. Without this, the loser's exception propagates out of+ a detached startup task and the remaining views are never created.+ """+ try:+ await db.execute_raw(ddl)+ verbose_logger.debug("%s Created!", view_name)+ except Exception as e:+ if not any(marker in str(e).lower() for marker in _VIEW_ALREADY_EXISTS_MARKERS):+ raise+ verbose_logger.debug("%s already created by a concurrent replica", view_name)+async def create_missing_views(db: _db):"""@@ -34,7 +57,10 @@ async def create_missing_views(db: _db):if not any(marker in error_msg for marker in _VIEW_NOT_FOUND_MARKERS):raise# If an error occurs, the view does not exist, so create it- await db.execute_raw("""+ await create_view_tolerating_race(+ db,+ "LiteLLM_VerificationTokenView",+ """CREATE VIEW "LiteLLM_VerificationTokenView" ASSELECTv.*,@@ -46,9 +72,8 @@ async def create_missing_views(db: _db):FROM "LiteLLM_VerificationToken" vLEFT JOIN "LiteLLM_TeamTable" t ON v.team_id = t.team_idLEFT JOIN "LiteLLM_ProjectTable" p ON v.project_id = p.project_id;- """)-- verbose_logger.debug("LiteLLM_VerificationTokenView Created!")+ """,+ )try:await db.query_raw("""SELECT 1 FROM "MonthlyGlobalSpend" LIMIT 1""")@@ -218,9 +243,7 @@ async def create_missing_views(db: _db):ORDER BY total_spend DESCLIMIT 100;"""- await db.execute_raw(query=sql_query)-- verbose_logger.debug("Last30dTopEndUsersSpend Created!")+ await create_view_tolerating_race(db, "Last30dTopEndUsersSpend", sql_query)async def should_create_missing_views(db: _db) -> bool:diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 8a1fae42789..ef0376ade84 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -106,6 +106,7 @@ from litellm.proxy.common_utils.config_sync_pubsub import publish_config_param_cfrom litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCachefrom litellm.proxy.db.create_views import (create_missing_views,+ create_view_tolerating_race,should_create_missing_views,)from litellm.proxy.db.db_spend_update_writer import DBSpendUpdateWriter@@ -3273,7 +3274,10 @@ class PrismaClient:## check if required view exists ##if ret[0]["view_names"] and required_view not in ret[0]["view_names"]:await self.health_check() # make sure we can connect to db- await self.db.execute_raw("""+ await create_view_tolerating_race(+ self.db,+ "LiteLLM_VerificationTokenView",+ """CREATE VIEW "LiteLLM_VerificationTokenView" ASSELECTv.*,@@ -3283,9 +3287,8 @@ class PrismaClient:t.rpm_limit AS team_rpm_limitFROM "LiteLLM_VerificationToken" vLEFT JOIN "LiteLLM_TeamTable" t ON v.team_id = t.team_id;- """)-- verbose_proxy_logger.info("LiteLLM_VerificationTokenView Created in DB!")+ """,+ )else:should_create_views: Final = await should_create_missing_views(db=self.db)if should_create_views:diff --git a/tests/test_litellm/proxy/db/test_create_views.py b/tests/test_litellm/proxy/db/test_create_views.pyindex c0c09d0137b..011203c4b5a 100644--- a/tests/test_litellm/proxy/db/test_create_views.py+++ b/tests/test_litellm/proxy/db/test_create_views.py@@ -189,3 +189,55 @@ async def test_create_views_creates_view_on_undefined_table_error():await create_missing_views(mock_db)mock_db.execute_raw.assert_called_once()+++async def test_create_views_tolerates_concurrent_creator_and_continues():+ """A replica that loses the CREATE race must not abort the remaining views.++ Regression: two proxy pods booting on a fresh DB both see every view as+ absent and both issue the CREATE. Postgres fails the loser with a+ duplicate-object error, which propagated out of create_missing_views and+ left every later view (MonthlyGlobalSpend, DailyTagSpend, ...) uncreated,+ so /global/spend* 500'd for the life of the deployment.+ """+ from litellm.proxy.db.create_views import create_missing_views++ mock_db = MagicMock()+ mock_db.query_raw = AsyncMock(side_effect=Exception("relation does not exist"))+ mock_db.execute_raw = AsyncMock(+ side_effect=[Exception('relation "LiteLLM_VerificationTokenView" already exists')]+ + [None] * 20+ )++ await create_missing_views(mock_db)++ assert mock_db.execute_raw.await_count > 1, (+ "lost the race on the first view and stopped; later views were never created"+ )+++async def test_create_views_reraises_genuine_ddl_error():+ """An already-exists guard must not swallow real DDL failures."""+ from litellm.proxy.db.create_views import create_missing_views++ mock_db = MagicMock()+ mock_db.query_raw = AsyncMock(side_effect=Exception("relation does not exist"))+ mock_db.execute_raw = AsyncMock(side_effect=Exception("syntax error at or near"))++ with pytest.raises(Exception, match="syntax error"):+ await create_missing_views(mock_db)+++async def test_create_view_tolerating_race_swallows_only_already_exists():+ from litellm.proxy.db.create_views import create_view_tolerating_race++ mock_db = MagicMock()+ mock_db.execute_raw = AsyncMock(side_effect=Exception("duplicate object"))+ await create_view_tolerating_race(mock_db, "SomeView", "CREATE VIEW ...")++ mock_db.execute_raw = AsyncMock(side_effect=Exception("permission denied"))+ with pytest.raises(Exception, match="permission denied"):+ await create_view_tolerating_race(mock_db, "SomeView", "CREATE VIEW ...")