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]

feat(proxy): bound DB statement and lock time via general_settings (#35496)

Yassin Kortam669bfd6c603c
diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py
index 8dc4a7b40c7..cdfacae0a5d 100644
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@ -3,6 +3,7 @@ import importlib
import json
import os
import random
+import re
import subprocess
import sys
import urllib.parse as urlparse
@@ -12,6 +13,7 @@ from typing import TYPE_CHECKING, Any, Iterable, Optional, Union
import click
import httpx
from dotenv import load_dotenv
+from pydantic import BaseModel, ConfigDict
import litellm
from litellm.constants import DEFAULT_NUM_WORKERS_LITELLM_PROXY
@@ -91,6 +93,72 @@ def _build_db_connection_url_params(
return params
+class DatabaseTimeoutSettings(BaseModel):
+ """The `general_settings` keys that bound how long a statement may hold locks.
+
+ Validated at the boundary so a mistyped value fails at startup with a clear
+ pydantic error instead of a TypeError deep inside URL assembly.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ database_statement_timeout: float | None = None
+ database_lock_timeout: float | None = None
+
+
+def _pg_options_with_timeouts(
+ existing_options: str,
+ statement_timeout: float | None,
+ lock_timeout: float | None,
+) -> str:
+ """Return the Postgres ``options`` value carrying the configured timeouts.
+
+ Prisma has no URL parameter for `statement_timeout` / `lock_timeout`; they are
+ server settings delivered through the standard libpq ``options`` parameter as
+ ``-c <name>=<value>``. Values arrive in seconds (matching the sibling
+ ``database_*_timeout`` settings) and are emitted as integer milliseconds,
+ which is the unit Postgres assumes for a unit-less value.
+
+ Both settings are bounds on how long a single statement may hold its locks.
+ Without them a batch that outlives the Prisma client's HTTP read timeout keeps
+ running server side, holding row locks for as long as the database takes,
+ while the client has already given up; every later flush queues behind it.
+ The query engine's own transaction timeout cannot end that wait, because it
+ cannot interrupt a statement that is already executing.
+
+ Any ``options`` the operator already pinned on the URL is preserved, and a
+ setting they pinned there wins over the configured one. Postgres applies the
+ last occurrence of a setting, so a pinned one is honoured by not appending
+ ours at all; it is matched in every spelling the backend accepts
+ (``-c name=``, ``-cname=``, ``--name=``). The result is applied to
+ ``DATABASE_URL`` only, never ``DIRECT_URL``: that one serves migrations,
+ which legitimately run long and must not be cancelled mid-way.
+ """
+ configured = tuple(
+ f"-c {name}={int(seconds * 1000)}"
+ for name, seconds in (
+ ("statement_timeout", statement_timeout),
+ ("lock_timeout", lock_timeout),
+ )
+ if seconds is not None and not re.search(rf"(?:-c\s*|--){re.escape(name)}=", existing_options)
+ )
+ return " ".join(part for part in (existing_options, *configured) if part)
+
+
+def _url_query_value(url: str | None, key: str) -> str:
+ """Return a single query-param value already present on ``url``, else ""."""
+ if not isinstance(url, str) or url == "":
+ return ""
+ return next(iter(urlparse.parse_qs(urlparse.urlparse(url).query).get(key) or ()), "")
+
+
+def _with_query_value(url: str, key: str, value: str) -> str:
+ """Return ``url`` with a single query param replaced by ``value``."""
+ parsed = urlparse.urlparse(url)
+ pairs = tuple((k, v) for k, v in urlparse.parse_qsl(parsed.query) if k != key) + ((key, value),)
+ return urlparse.urlunparse(parsed._replace(query=urlparse.urlencode(pairs)))
+
+
def append_query_params(url: Optional[str], params: dict) -> str:
from litellm._logging import verbose_proxy_logger
@@ -1007,6 +1075,8 @@ def run_server(
db_socket_timeout: Optional[Union[int, float]] = None
db_disable_prepared_statements: bool = False
db_extra_connection_params: Optional[dict] = None
+ db_statement_timeout: float | None = None
+ db_lock_timeout: float | None = None
general_settings = {}
### GET DB TOKEN FOR IAM AUTH ###
@@ -1117,6 +1187,9 @@ def run_server(
else:
db_disable_prepared_statements = bool(_disable_prepared_statements)
db_extra_connection_params = general_settings.get("database_extra_connection_params")
+ db_timeouts = DatabaseTimeoutSettings.model_validate(general_settings)
+ db_statement_timeout = db_timeouts.database_statement_timeout
+ db_lock_timeout = db_timeouts.database_lock_timeout
if database_url and database_url.startswith("os.environ/"):
original_dir = os.getcwd()
# set the working directory to where this script is
@@ -1176,8 +1249,19 @@ def run_server(
)
if os.getenv("DATABASE_URL", None) is not None:
database_url = get_secret("DATABASE_URL", default_value=None)
+ resolved_url: str | None = str(database_url) if database_url else None
+ pg_options: str = _pg_options_with_timeouts(
+ _url_query_value(resolved_url, "options"),
+ db_statement_timeout,
+ db_lock_timeout,
+ )
+ writer_url = (
+ _with_query_value(resolved_url, "options", pg_options)
+ if resolved_url and pg_options
+ else resolved_url
+ )
modified_url = append_query_params(
- str(database_url) if database_url else None,
+ writer_url,
connection_url_params,
)
os.environ["DATABASE_URL"] = modified_url
diff --git a/tests/test_litellm/proxy/test_proxy_cli.py b/tests/test_litellm/proxy/test_proxy_cli.py
index 5d2236fd918..2ccaa0df440 100644
--- a/tests/test_litellm/proxy/test_proxy_cli.py
+++ b/tests/test_litellm/proxy/test_proxy_cli.py
@@ -15,6 +15,7 @@ sys.path.insert(
import builtins
import types
+import urllib.parse as urlparse
import uvicorn
@@ -2072,3 +2073,207 @@ class TestWorkerStartupHooks:
assert _dummy_hook_called is True, "First hook was not called"
assert _dummy_async_hook_called is True, "Second hook was not called"
+
+
[email protected]_group("proxy_cli")
+class TestPostgresStatementTimeoutOptions:
+ """A batch that outlives the Prisma client's HTTP read timeout keeps running
+ server side and holds its row locks until the database finishes it. Postgres
+ `statement_timeout` / `lock_timeout` are the only bound that ends that wait,
+ so they must survive the trip from general_settings into the connection URL.
+ """
+
+ @pytest.mark.parametrize(
+ "existing, statement_timeout, lock_timeout, expected",
+ [
+ ("", 60, 15, "-c statement_timeout=60000 -c lock_timeout=15000"),
+ ("", 60, None, "-c statement_timeout=60000"),
+ ("", None, 15, "-c lock_timeout=15000"),
+ ("", None, None, ""),
+ ("", 0.25, None, "-c statement_timeout=250"),
+ (
+ "-c search_path=app",
+ 60,
+ 15,
+ "-c search_path=app -c statement_timeout=60000 -c lock_timeout=15000",
+ ),
+ (
+ "-c statement_timeout=5000",
+ 60,
+ 15,
+ "-c statement_timeout=5000 -c lock_timeout=15000",
+ ),
+ (
+ "-cstatement_timeout=5000",
+ 60,
+ 15,
+ "-cstatement_timeout=5000 -c lock_timeout=15000",
+ ),
+ (
+ "--statement_timeout=5000",
+ 60,
+ 15,
+ "--statement_timeout=5000 -c lock_timeout=15000",
+ ),
+ (
+ "-c statement_timeout=5000",
+ 60,
+ 15,
+ "-c statement_timeout=5000 -c lock_timeout=15000",
+ ),
+ ],
+ ids=[
+ "both",
+ "statement_only",
+ "lock_only",
+ "neither",
+ "fractional_seconds",
+ "preserves_unrelated_option",
+ "pinned_spaced_wins",
+ "pinned_compact_wins",
+ "pinned_double_dash_wins",
+ "pinned_extra_spaces_wins",
+ ],
+ )
+ def test_pg_options_with_timeouts(self, existing, statement_timeout, lock_timeout, expected):
+ from litellm.proxy.proxy_cli import _pg_options_with_timeouts
+
+ assert _pg_options_with_timeouts(existing, statement_timeout, lock_timeout) == expected
+
+ def test_timeouts_reach_the_database_url_from_general_settings(self, tmp_path):
+ """The whole point of the setting: it has to land on DATABASE_URL."""
+ import yaml
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(
+ yaml.dump(
+ {
+ "model_list": [],
+ "general_settings": {
+ "database_statement_timeout": 60,
+ "database_lock_timeout": 15,
+ },
+ }
+ )
+ )
+
+ modified_url = self._run_server_and_capture_database_url(str(config_path))
+
+ options = urlparse.parse_qs(urlparse.urlparse(modified_url).query)["options"][0]
+ assert "-c statement_timeout=60000" in options
+ assert "-c lock_timeout=15000" in options
+
+ def test_no_options_param_when_unset(self, tmp_path):
+ """Unset must mean today's behavior, not an empty options string."""
+ import yaml
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.dump({"model_list": [], "general_settings": {}}))
+
+ modified_url = self._run_server_and_capture_database_url(str(config_path))
+
+ assert "options" not in urlparse.parse_qs(urlparse.urlparse(modified_url).query)
+
+ def test_direct_url_is_never_bounded(self, tmp_path):
+ """DIRECT_URL serves migrations, which must not be cancelled mid-way."""
+ import yaml
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(
+ yaml.dump({"model_list": [], "general_settings": {"database_statement_timeout": 60}})
+ )
+
+ captured = self._run_server_and_capture_urls(
+ str(config_path), direct_url="postgresql://t:t@localhost:5432/t"
+ )
+
+ assert "options" in urlparse.parse_qs(urlparse.urlparse(captured["DATABASE_URL"]).query)
+ assert "options" not in urlparse.parse_qs(urlparse.urlparse(captured["DIRECT_URL"]).query)
+
+ def test_non_numeric_timeout_fails_fast(self, tmp_path):
+ """A mistyped value must fail at startup, not deep inside URL assembly."""
+ import yaml
+ from pydantic import ValidationError
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(
+ yaml.dump({"model_list": [], "general_settings": {"database_statement_timeout": "sixty"}})
+ )
+
+ with pytest.raises(ValidationError):
+ self._run_server_and_capture_database_url(str(config_path))
+
+ def test_operator_pinned_url_options_are_preserved(self, tmp_path):
+ """An operator's own `options` on DATABASE_URL must not be clobbered."""
+ import yaml
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(
+ yaml.dump(
+ {
+ "model_list": [],
+ "general_settings": {"database_statement_timeout": 60},
+ }
+ )
+ )
+
+ modified_url = self._run_server_and_capture_database_url(
+ str(config_path),
+ database_url="postgresql://t:t@localhost:5432/t?options=-c%20search_path%3Dapp",
+ )
+
+ options = urlparse.parse_qs(urlparse.urlparse(modified_url).query)["options"][0]
+ assert "-c search_path=app" in options
+ assert "-c statement_timeout=60000" in options
+
+ @classmethod
+ def _run_server_and_capture_database_url(
+ cls,
+ config_path: str,
+ database_url: str = "postgresql://t:t@localhost:5432/t",
+ ) -> str:
+ return cls._run_server_and_capture_urls(config_path, database_url=database_url)["DATABASE_URL"]
+
+ @staticmethod
+ def _run_server_and_capture_urls(
+ config_path: str,
+ database_url: str = "postgresql://t:t@localhost:5432/t",
+ direct_url: str | None = None,
+ ) -> dict:
+ from litellm.proxy.proxy_cli import run_server
+
+ import yaml
+
+ loaded_config = yaml.safe_load(Path(config_path).read_text())
+ mock_proxy_config = MagicMock()
+ mock_proxy_config.return_value.get_config = AsyncMock(return_value=loaded_config)
+ mock_proxy_module = MagicMock(
+ app=MagicMock(),
+ ProxyConfig=mock_proxy_config,
+ KeyManagementSettings=MagicMock(),
+ save_worker_config=MagicMock(),
+ )
+ clean_env = {k: v for k, v in os.environ.items() if k not in ("DATABASE_URL", "DIRECT_URL")}
+ clean_env["DATABASE_URL"] = database_url
+ if direct_url is not None:
+ clean_env["DIRECT_URL"] = direct_url
+
+ with (
+ patch.dict(os.environ, clean_env, clear=True),
+ patch.dict(
+ "sys.modules",
+ {
+ "proxy_server": mock_proxy_module,
+ "litellm.proxy.proxy_server": mock_proxy_module,
+ },
+ ),
+ patch("subprocess.run", return_value=MagicMock(returncode=0)),
+ patch("atexit.register"),
+ patch("litellm.proxy.db.prisma_client.should_update_prisma_schema", return_value=False),
+ patch("litellm.proxy.db.check_migration.check_prisma_schema_diff"),
+ ):
+ run_server.main(
+ ["--config", config_path, "--local", "--skip_server_startup"],
+ standalone_mode=False,
+ )
+ return {k: os.environ[k] for k in ("DATABASE_URL", "DIRECT_URL") if k in os.environ}