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
test(e2e): event_loop_stalls perf case fails on a gateway event-loop hold over 100 ms that is not on its allowlist (#46974)
Kerry Lu0a051efba763
diff --git a/litellm/proxy/common_utils/slow_gc_logger.py b/litellm/proxy/common_utils/slow_gc_logger.pynew file mode 100644index 00000000000..63400341426--- /dev/null+++ b/litellm/proxy/common_utils/slow_gc_logger.py@@ -0,0 +1,35 @@+"""Garbage collection passes long enough to count as event-loop holds, logged next to asyncio's own+`Executing <Task ...> took X seconds` lines so a reader can tell a collector pause from code that held the loop+(asyncio charges the pause to whichever task was running). Registered only when the loop runs in debug mode."""++from __future__ import annotations++import gc+import time+from collections.abc import Callable, Mapping+from typing import Final, Literal+++class SlowGcLogger:+ def __init__(+ self, threshold_seconds: float, log: Callable[[str], None], clock: Callable[[], float] = time.monotonic+ ) -> None:+ self._threshold_seconds: Final = threshold_seconds+ self._log: Final = log+ self._clock: Final = clock+ self._started = clock()++ def __call__(self, phase: Literal["start", "stop"], info: Mapping[str, int]) -> None:+ if phase == "start":+ self._started = self._clock()+ return+ seconds: Final = self._clock() - self._started+ if seconds < self._threshold_seconds:+ return+ self._log(+ f"Garbage collection gen={info['generation']} collected={info['collected']} took {seconds:.3f} seconds"+ )+++def log_slow_gc_passes(threshold_seconds: float, log: Callable[[str], None]) -> None:+ gc.callbacks.append(SlowGcLogger(threshold_seconds=threshold_seconds, log=log))diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.pyindex 3c5f55d87a8..7f68b72a522 100644--- a/litellm/proxy/proxy_cli.py+++ b/litellm/proxy/proxy_cli.py@@ -713,6 +713,8 @@ class ProxyInitializationHelpers:"""Helper function to determine the event loop type based on platform"""if sys.platform in ("win32", "cygwin", "cli"):return None # Let uvicorn choose the default loop on Windows+ if os.environ.get("LITELLM_EVENT_LOOP") == "asyncio":+ return "asyncio"return "uvloop"_get_loop_type = get_loop_typediff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 7d45b99ebb3..27bfd03d7f8 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -512,6 +512,7 @@ from litellm.proxy.common_utils.scheduled_job_stagger import (parse_stagger_settings,stagger_trigger,)+from litellm.proxy.common_utils.slow_gc_logger import log_slow_gc_passesfrom litellm.proxy.common_utils.swagger_utils import ERROR_RESPONSESfrom litellm.proxy.common_utils.timezone_utils import (get_budget_reset_settings,@@ -1382,6 +1383,10 @@ async def proxy_startup_event(app: FastAPI) -> AsyncGenerator[ProxyLifespanStateinit_verbose_loggers()+ running_loop: Final = asyncio.get_running_loop()+ if isinstance(running_loop, asyncio.BaseEventLoop) and running_loop.get_debug():+ log_slow_gc_passes(threshold_seconds=running_loop.slow_callback_duration, log=verbose_proxy_logger.warning)+prometheus_multiproc_dir: Final = os.environ.get("PROMETHEUS_MULTIPROC_DIR")if prometheus_multiproc_dir:mark_dead_workers(prometheus_multiproc_dir)diff --git a/tests/e2e/e2e_http.py b/tests/e2e/e2e_http.pyindex 9198f6c54d6..90a9e9367eb 100644--- a/tests/e2e/e2e_http.py+++ b/tests/e2e/e2e_http.py@@ -499,6 +499,29 @@ def get_external[R: BaseModel](return classify(resp, response_type)+def get_text_external(+ url: str,+ *,+ headers: BaseModel | None = None,+ timeout: float = 30.0,+ ca_bundle: str | None = None,+) -> str | NetworkError:+ """GET an absolute URL outside the proxy whose body is plain text (e.g. a pod log), not JSON.+ A non-2xx status is reported as a NetworkError so the caller can fail loudly."""+ try:+ resp = requests.get(+ url,+ headers={"Accept": "text/plain", **(_headers(headers) if headers is not None else {})},+ timeout=timeout,+ verify=ca_bundle if ca_bundle is not None else True,+ )+ except requests.RequestException as exc:+ return NetworkError(message=str(exc))+ if not (200 <= resp.status_code < 300):+ return NetworkError(message=f"{resp.status_code} from {url}: {resp.text[:300]}")+ return resp.text++def post_external[R: BaseModel](url: str,*,diff --git a/tests/e2e/perf/cases/event_loop_stalls.py b/tests/e2e/perf/cases/event_loop_stalls.pynew file mode 100644index 00000000000..66c99686151--- /dev/null+++ b/tests/e2e/perf/cases/event_loop_stalls.py@@ -0,0 +1,48 @@+"""Where the gateway holds its event loop for 100 ms or more: the mixed case's callers, model groups, guardrails+and body mix (short chats, 300k to 1M-token contexts, tool calls, half streamed) at 1 rps for 120 requests against+a gateway running the stdlib asyncio loop in debug mode, which logs every loop step over 0.1 s with the task that+ran it. No latency, CPU or datastore ceilings: the one check is that no step over 0.1 s comes from a location that+is not on the allowlist below, and that the listed ones do not show up more often than they do today. A stream+that stops yielding (the 46925 fix), a provider handler that re-walks a 1M-token body on the loop (46967), or a+new hook that deep-copies the request inline all land here as a new row. Runs on its own stack: the gateway needs+`PYTHONASYNCIODEBUG=1` and `LITELLM_EVENT_LOOP=asyncio` (uvloop reports nothing and crashed under debug locally),+and the runner `E2E_PERF_EVENT_LOOP=1`, so the nightly build, which sets neither, skips it. The allowlist counts+are twice the highest count any of ten back-to-back local runs showed on that row (rows that showed nothing in+those ten but did in the earlier before/after legs for 46925 and 46967 get 2), so each run sits at or under half+of every cap and a listed location doubling in frequency is a failure, not a flake. The+`garbage collection` bucket is the gen-2 passes the collector logs in debug mode (0.6 to 0.7 s each, one every+minute or two of this traffic, plus the ramp while the heap fills on a local whole-file run), which asyncio would+otherwise charge to a random task; its count is the signal for a change that makes much more garbage."""++from __future__ import annotations++from dataclasses import replace+from typing import Final++from setup.event_loop import EventLoopStalls, KnownStall++from cases.mixed_size_requests_2rps import CASE as MIXED++CASE: Final = replace(+ MIXED,+ name="event_loop_stalls",+ traffic=replace(MIXED.traffic, rps=1.0, total_requests=120, concurrency=10),+ limits=(),+ event_loop=EventLoopStalls(+ allowlist=(+ KnownStall("garbage collection", max_count=4),+ KnownStall("LifespanOn.main", max_count=4),+ KnownStall("RequestResponseCycle.run_asgi", max_count=6),+ KnownStall("with_proxy_compaction_executor", max_count=2),+ KnownStall("Logging.async_success_handler", max_count=2),+ KnownStall("Logging.dispatch_success_handlers", max_count=2),+ KnownStall("_TrackedPrismaEngine", max_count=2),+ KnownStall("prisma/actions.py", max_count=2),+ KnownStall("SpendCounterReseed", max_count=2),+ KnownStall("Subscriber._run", max_count=2),+ KnownStall("RedisBatch.flush", max_count=2),+ KnownStall("run_coroutine_job", max_count=2),+ KnownStall("user_api_key_auth.py", max_count=2),+ ),+ ),+)diff --git a/tests/e2e/perf/setup/event_loop.py b/tests/e2e/perf/setup/event_loop.pynew file mode 100644index 00000000000..00d05c79f73--- /dev/null+++ b/tests/e2e/perf/setup/event_loop.py@@ -0,0 +1,248 @@+"""Event-loop holds, read from the gateway's own asyncio debug output. A gateway started with+`PYTHONASYNCIODEBUG=1` on the stdlib loop (`LITELLM_EVENT_LOOP=asyncio`, uvloop never reports them) logs every+callback or task step over `slow_callback_duration` (0.1 s) as+`Executing <Task ... coro=<name() running at file:line> ...> took X seconds`. A case with `event_loop` set reads+the gateway log for its traffic window, groups those lines by coroutine and location, and fails on a location that+is not on its allowlist of known holds or shows up more often than the allowlist gives it. asyncio names the task,+not the frame that held the loop, so every request handler lands under `RequestResponseCycle.run_asgi`; the+allowlist caps how often a known location may appear instead of ignoring it. The log comes from the gateway pods+(`pods/log` with the runner's service account, pods picked by `E2E_PERF_GATEWAY_POD_SELECTOR`) or, on a local run,+from the whole file named by `E2E_PERF_GATEWAY_LOG_FILE` (no time window, so startup holds are in it too).+A garbage collection pass pauses the loop too, and asyncio charges it to whatever task was running, so the gateway+logs every pass over the same threshold (`Garbage collection gen=2 collected=N took X seconds`, debug mode only);+a hold that such a pass accounts for is reported under `garbage collection` instead of the task it landed on."""++from __future__ import annotations++import os+import re+from collections.abc import Iterable+from dataclasses import dataclass, replace+from datetime import datetime+from itertools import groupby+from pathlib import Path+from typing import Final+from urllib.parse import quote++from e2e_http import AuthHeaders, NetworkError, Success, get_external, get_text_external+from pydantic import BaseModel++from setup.podcpu import SELECTOR_ENV, in_cluster++OPT_IN_ENV: Final = "E2E_PERF_EVENT_LOOP"+LOG_FILE_ENV: Final = "E2E_PERF_GATEWAY_LOG_FILE"+_API: Final = "https://kubernetes.default.svc/api/v1/namespaces"+_LINE: Final = re.compile(r"Executing <(?P<desc>.*?)> took (?P<seconds>[0-9.]+) seconds")+_CORO: Final = re.compile(r"coro=<(?P<name>[^ ]+)")+_AT: Final = re.compile(r" at (?P<where>[^ >]+:\d+)")+_GC_LINE: Final = re.compile(+ r"Garbage collection gen=(?P<generation>\d+) collected=\d+ took (?P<seconds>[0-9.]+) seconds"+)+GC_BUCKET: Final = "garbage collection"+++@dataclass(frozen=True, slots=True)+class KnownStall:+ """A hold the gateway has today: `where` is a substring of the coroutine name or its file:line, `max_count` the+ most times it may show up in one run before the case fails."""++ where: str+ max_count: int+++@dataclass(frozen=True, slots=True)+class EventLoopStalls:+ allowlist: tuple[KnownStall, ...]+ max_hold_seconds: float = 0.1+++@dataclass(frozen=True, slots=True)+class GcPass:+ generation: int+ seconds: float+++@dataclass(frozen=True, slots=True)+class Stall:+ coroutine: str+ where: str+ seconds: float+ gc_seconds: float = 0.0+ gc_generation: int | None = None+++@dataclass(frozen=True, slots=True)+class StallRow:+ coroutine: str+ where: str+ count: int+ total_seconds: float+ max_seconds: float+ allowed_by: KnownStall | None++ @property+ def offending(self) -> bool:+ return self.allowed_by is None or self.count > self.allowed_by.max_count+++def _short(path: str) -> str:+ if "site-packages/" in path:+ return path.rsplit("site-packages/", 1)[1]+ if "/litellm/" in path:+ return "litellm/" + path.rsplit("/litellm/", 1)[1]+ return path+++def _parse_line(line: str) -> Stall | None:+ match: Final = _LINE.search(line)+ if match is None:+ return None+ desc: Final = match.group("desc")+ coro: Final = _CORO.search(desc)+ at: Final = _AT.search(desc)+ return Stall(+ coroutine=coro.group("name") if coro else desc[:80],+ where=_short(at.group("where")) if at else "",+ seconds=float(match.group("seconds")),+ )+++def _parse_event(line: str) -> Stall | GcPass | None:+ match: Final = _GC_LINE.search(line)+ if match is None:+ return _parse_line(line)+ return GcPass(generation=int(match.group("generation")), seconds=float(match.group("seconds")))+++def _with_passes(stall: Stall, passes: tuple[GcPass, ...]) -> Stall:+ if not passes:+ return stall+ return replace(+ stall,+ gc_seconds=sum(gc_pass.seconds for gc_pass in passes),+ gc_generation=max(gc_pass.generation for gc_pass in passes),+ )+++def parse_stalls(lines: Iterable[str]) -> tuple[Stall, ...]:+ """Holds in log order, each carrying the collector passes logged since the previous hold: a pass runs inside the+ task asyncio then blames and is only logged when it is itself over the threshold, so its hold line follows it."""+ events: Final = tuple(event for event in map(_parse_event, lines) if event is not None)+ holds: Final = tuple((index, event) for index, event in enumerate(events) if isinstance(event, Stall))+ return tuple(+ _with_passes(stall, tuple(event for event in events[previous + 1 : index] if isinstance(event, GcPass)))+ for previous, (index, stall) in zip((-1, *(index for index, _ in holds)), holds)+ )+++def _reported(spec: EventLoopStalls, stall: Stall) -> Stall:+ """A hold the collector accounts for, what is left under the threshold, is the collector's, not the task's."""+ if stall.gc_generation is None or stall.gc_seconds > stall.seconds:+ return stall+ if stall.seconds - stall.gc_seconds >= spec.max_hold_seconds:+ return stall+ return Stall(coroutine=GC_BUCKET, where=f"gen={stall.gc_generation}", seconds=stall.seconds)+++def _allowed_by(spec: EventLoopStalls, coroutine: str, where: str) -> KnownStall | None:+ return next((known for known in spec.allowlist if known.where in coroutine or known.where in where), None)+++def summarize(spec: EventLoopStalls, stalls: Iterable[Stall]) -> tuple[StallRow, ...]:+ """One row per (coroutine, location) over the hold threshold, worst total first."""+ reported: Final = tuple(_reported(spec, stall) for stall in stalls)+ over: Final = sorted(+ (stall for stall in reported if stall.seconds >= spec.max_hold_seconds), key=lambda s: (s.coroutine, s.where)+ )+ rows: Final = tuple(+ StallRow(+ coroutine=coroutine,+ where=where,+ count=len(group),+ total_seconds=sum(stall.seconds for stall in group),+ max_seconds=max(stall.seconds for stall in group),+ allowed_by=_allowed_by(spec, coroutine, where),+ )+ for (coroutine, where), group in (+ (key, tuple(items)) for key, items in groupby(over, key=lambda s: (s.coroutine, s.where))+ )+ )+ return tuple(sorted(rows, key=lambda row: -row.total_seconds))+++def offenders(rows: Iterable[StallRow]) -> tuple[str, ...]:+ return tuple(+ f"{row.coroutine} {row.where}: {row.count}x, max {row.max_seconds:.2f} s"+ + (+ f" (allowlist {row.allowed_by.where} permits {row.allowed_by.max_count})"+ if row.allowed_by+ else " (not on the allowlist)"+ )+ for row in rows+ if row.offending+ )+++def render_stalls(spec: EventLoopStalls, rows: Iterable[StallRow]) -> str:+ header: Final = (+ f" event-loop holds >= {spec.max_hold_seconds:.2f} s in the gateway log (count total_s max_s where)"+ )+ body: Final = tuple(+ f" {'FAIL' if row.offending else 'ok '} {row.count:5d} {row.total_seconds:8.2f} {row.max_seconds:6.2f} "+ f"{row.coroutine} {row.where}"+ for row in rows+ )+ return "\n".join((header, *body)) if body else header + "\n none"+++class _PodName(BaseModel):+ name: str+++class _Pod(BaseModel):+ metadata: _PodName+++class _PodList(BaseModel):+ items: list[_Pod]+++def _pod_log_lines(url: str, headers: AuthHeaders, ca_bundle: str) -> tuple[str, ...]:+ text: Final = get_text_external(url, headers=headers, timeout=60.0, ca_bundle=ca_bundle)+ if isinstance(text, NetworkError):+ raise RuntimeError(f"gateway pod log unreadable: {text.message}")+ return tuple(text.splitlines())+++def _pod_logs(since: datetime) -> tuple[str, ...] | None:+ cluster: Final = in_cluster()+ selector: Final = os.environ.get(SELECTOR_ENV, "")+ if cluster is None or not selector:+ return None+ token, ca_bundle, namespace = cluster+ headers: Final = AuthHeaders(authorization=f"Bearer {token}")+ pods: Final = get_external(+ f"{_API}/{namespace}/pods?labelSelector={quote(selector)}",+ response_type=_PodList,+ headers=headers,+ timeout=60.0,+ ca_bundle=ca_bundle,+ )+ if not isinstance(pods, Success):+ raise RuntimeError(f"gateway pod list unreadable: {pods}")+ since_param: Final = quote(since.strftime("%Y-%m-%dT%H:%M:%SZ"))+ return tuple(+ line+ for pod in pods.data.items+ for line in _pod_log_lines(+ f"{_API}/{namespace}/pods/{pod.metadata.name}/log?sinceTime={since_param}", headers, ca_bundle+ )+ )+++def read_gateway_log(since: datetime) -> tuple[str, ...] | None:+ """Gateway log lines for the traffic window, or None when neither a pod nor a local file is reachable."""+ local: Final = os.environ.get(LOG_FILE_ENV, "")+ if local:+ return tuple(Path(local).read_text(errors="replace").splitlines())+ return _pod_logs(since)diff --git a/tests/e2e/perf/setup/performance_test_case.py b/tests/e2e/perf/setup/performance_test_case.pyindex 37ad640db62..2879866f85b 100644--- a/tests/e2e/perf/setup/performance_test_case.py+++ b/tests/e2e/perf/setup/performance_test_case.py@@ -13,6 +13,8 @@ from collections.abc import Mappingfrom dataclasses import dataclass, fieldfrom typing import Final, Literal+from setup.event_loop import EventLoopStalls+Endpoint = Literal["chat_completions", "responses", "messages"]MockProvider = Literal["openai", "anthropic", "bedrock"]GuardrailMode = Literal["pre_call", "post_call"]@@ -153,6 +155,7 @@ class PerformanceTestCase:background_cap_exempt_tables: frozenset[str] = frozenset()"""Tables whose background write is one upsert per writer flush and, at this case's request rate, landsabove the `postgres_max_background_statement_per_request` cap without being per request."""+ event_loop: EventLoopStalls | None = Nonedef team(self, name: str) -> Team:return next(team for team in self.teams if team.name == name)diff --git a/tests/e2e/perf/setup/podcpu.py b/tests/e2e/perf/setup/podcpu.pyindex c2402b38b71..400e5b7d38b 100644--- a/tests/e2e/perf/setup/podcpu.py+++ b/tests/e2e/perf/setup/podcpu.py@@ -103,7 +103,7 @@ class NoSampler:return None-def _in_cluster() -> tuple[str, str, str] | None:+def in_cluster() -> tuple[str, str, str] | None:token: Final = _SERVICE_ACCOUNT / "token"ca: Final = _SERVICE_ACCOUNT / "ca.crt"namespace: Final = _SERVICE_ACCOUNT / "namespace"@@ -115,7 +115,7 @@ def _in_cluster() -> tuple[str, str, str] | None:@contextmanagerdef gateway_cpu_sampler() -> Generator[GatewayCpuSampler | NoSampler]:selector: Final = os.environ.get(SELECTOR_ENV, "")- cluster: Final = _in_cluster()+ cluster: Final = in_cluster()sampler: Final = (GatewayCpuSampler(selector, cluster[2], cluster[0], cluster[1]) if selector and cluster else NoSampler())diff --git a/tests/e2e/perf/test_perf_cases.py b/tests/e2e/perf/test_perf_cases.pyindex d89a8634ab3..902483f8a2f 100644--- a/tests/e2e/perf/test_perf_cases.py+++ b/tests/e2e/perf/test_perf_cases.py@@ -5,7 +5,9 @@ clients saw, what the mocks received and how the workers' memory moved."""from __future__ import annotations+import osimport time+from datetime import UTC, datetimefrom typing import Finalimport pytest@@ -16,6 +18,16 @@ from memory_readings import read_rss_everywherefrom models import SpendLogsParamsfrom proxy_client import ProxyClientfrom setup.datastore import read_db_counters, read_redis_counters, redis_monitor+from setup.event_loop import (+ LOG_FILE_ENV,+ OPT_IN_ENV,+ StallRow,+ offenders,+ parse_stalls,+ read_gateway_log,+ render_stalls,+ summarize,+)from setup.observe import (Observation,evaluate,@@ -48,6 +60,17 @@ def _spend_logged_share(proxy: ProxyClient, call_ids: tuple[str, ...]) -> floatreturn found / len(call_ids)+def _event_loop_rows(case: PerformanceTestCase, since: datetime) -> tuple[StallRow, ...]:+ """The gateway's asyncio debug holds for the traffic window; a case that asks for them cannot pass without a log."""+ assert case.event_loop is not None+ lines: Final = read_gateway_log(since)+ assert lines is not None, (+ f"{case.name} needs the gateway log: run in the perf lane (pods/log with the runner service account) or set "+ f"{LOG_FILE_ENV} to the gateway's log file"+ )+ return summarize(case.event_loop, parse_stalls(lines))++@pytest.mark.parametrize("case", CASES, ids=[case.name for case in CASES])def test_perf_case(case: PerformanceTestCase,@@ -56,6 +79,11 @@ def test_perf_case(resources: ResourceManager,request: pytest.FixtureRequest,) -> None:+ if case.event_loop is not None and not os.environ.get(OPT_IN_ENV):+ pytest.skip(+ f"{case.name} reads asyncio debug output: deploy the gateway with PYTHONASYNCIODEBUG=1 and "+ f"LITELLM_EVENT_LOOP=asyncio, then set {OPT_IN_ENV}=1"+ )plan: Final = build_plan(case)mock_urls: Final = {provider: mock_url(provider) for provider in MOCK_PROVIDERS}for url in (*mock_urls.values(), guardrail_url()):@@ -68,6 +96,7 @@ def test_perf_case(db_before: Final = read_db_counters()redis_before: Final = read_redis_counters()run_started: Final = time.monotonic()+ traffic_started_at: Final = datetime.now(tz=UTC)with gateway_cpu_sampler() as cpu, redis_monitor() as monitor:outcome: Final = run_plan(case, plan, setup)run_finished: Final = time.monotonic()@@ -102,6 +131,7 @@ def test_perf_case(gateway_cpu_seconds=cpu.seconds,)rows, exceeded_limits = evaluate(case, observation)+ stall_rows: Final = _event_loop_rows(case, traffic_started_at) if case.event_loop is not None else ()item: Final = request.node # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType] # pytest: untypedassert isinstance(item, pytest.Item)item.user_properties[:] = [@@ -109,6 +139,8 @@ def test_perf_case(] # rebind-ok: a --reruns retry replaces the first attempt's numbers instead of appending a second setitem.user_properties.extend(junit_properties(rows))print(render(case, observation, rows))+ if case.event_loop is not None:+ print(render_stalls(case.event_loop, stall_rows))print(f" phases: setup {run_started - setup_started:.0f}s, locust {run_finished - run_started:.0f}s, "f"observe {time.monotonic() - run_finished:.0f}s (rss {rss_read - run_finished:.0f}s, spend sample "@@ -118,3 +150,4 @@ def test_perf_case(f"{len(plan)} planned, {len(outcome.records)} recorded; locust said:\n{outcome.locust_output}")assert not exceeded_limits, "limits exceeded (observed > max):\n" + "\n".join(exceeded_limits)+ assert not offenders(stall_rows), "event-loop holds over the threshold:\n" + "\n".join(offenders(stall_rows))diff --git a/tests/e2e_harness/perf/setup/test_event_loop.py b/tests/e2e_harness/perf/setup/test_event_loop.pynew file mode 100644index 00000000000..4728003db7f--- /dev/null+++ b/tests/e2e_harness/perf/setup/test_event_loop.py@@ -0,0 +1,87 @@+from __future__ import annotations++from typing import Final++from setup.event_loop import EventLoopStalls, KnownStall, offenders, parse_stalls, summarize++_HANDLER: Final = (+ "Executing <Task pending name='Task-9' coro=<RequestResponseCycle.run_asgi() running at "+ "/usr/local/lib/python3.12/site-packages/uvicorn/protocols/http/h11_impl.py:416> wait_for=<Future pending "+ "cb=[Task.task_wakeup()]> created at /usr/local/lib/python3.12/asyncio/base_events.py:448> took 0.731 seconds"+)+_STREAM: Final = (+ "Executing <Task pending name='Task-31' coro=<TaskHandle._run_coro() running at "+ "/usr/local/lib/python3.12/site-packages/anyio/_core/_tasks.py:275> created at "+ "/usr/local/lib/python3.12/asyncio/tasks.py:420> took 0.412 seconds"+)+_STARTUP: Final = (+ "Executing <Task pending name='Task-2' coro=<LifespanOn.main() running at "+ "/usr/local/lib/python3.12/site-packages/uvicorn/lifespan/on.py:86> created at "+ "/usr/local/lib/python3.12/asyncio/base_events.py:448> took 0.302 seconds"+)+_GC_PASS: Final = (+ "2026-10-17 04:46:02,101 - LiteLLM Proxy - WARNING - Garbage collection gen=2 collected=98608 took 0.711 seconds"+)+_SPEC: Final = EventLoopStalls(+ allowlist=(+ KnownStall("LifespanOn.main", max_count=3),+ KnownStall("RequestResponseCycle.run_asgi", max_count=2),+ KnownStall("garbage collection", max_count=1),+ )+)+++def test_parse_keeps_the_coroutine_its_location_and_the_hold() -> None:+ (stall,) = parse_stalls(("INFO: plain log line", _HANDLER))+ assert stall.coroutine == "RequestResponseCycle.run_asgi()"+ assert stall.where == "uvicorn/protocols/http/h11_impl.py:416"+ assert stall.seconds == 0.731+++def test_a_location_off_the_allowlist_offends_once_however_often_it_appears() -> None:+ rows: Final = summarize(_SPEC, parse_stalls((_STARTUP, _STREAM, _STREAM, _HANDLER)))+ assert [(row.coroutine, row.count, row.offending) for row in rows] == [+ ("TaskHandle._run_coro()", 2, True),+ ("RequestResponseCycle.run_asgi()", 1, False),+ ("LifespanOn.main()", 1, False),+ ]+ assert offenders(rows) == (+ "TaskHandle._run_coro() anyio/_core/_tasks.py:275: 2x, max 0.41 s (not on the allowlist)",+ )+++def test_a_known_location_offends_only_past_its_count() -> None:+ within: Final = summarize(_SPEC, parse_stalls((_HANDLER, _HANDLER)))+ assert offenders(within) == ()+ past: Final = summarize(_SPEC, parse_stalls((_HANDLER, _HANDLER, _HANDLER)))+ assert offenders(past) == (+ "RequestResponseCycle.run_asgi() uvicorn/protocols/http/h11_impl.py:416: 3x, max 0.73 s "+ "(allowlist RequestResponseCycle.run_asgi permits 2)",+ )+++def test_holds_under_the_threshold_are_not_rows() -> None:+ short: Final = _HANDLER.replace("took 0.731 seconds", "took 0.099 seconds")+ assert summarize(_SPEC, parse_stalls((short,))) == ()+++def test_a_hold_the_collector_pass_before_it_accounts_for_is_the_collectors_not_the_tasks() -> None:+ rows: Final = summarize(_SPEC, parse_stalls((_GC_PASS, _STREAM.replace("0.412", "0.731"))))+ assert [(row.coroutine, row.where, row.max_seconds, row.offending) for row in rows] == [+ ("garbage collection", "gen=2", 0.731, False)+ ]+++def test_a_hold_well_past_its_collector_pass_stays_on_the_task() -> None:+ short_pass: Final = _GC_PASS.replace("0.711", "0.200")+ rows: Final = summarize(_SPEC, parse_stalls((short_pass, _STREAM.replace("0.412", "0.731"))))+ assert [(row.coroutine, row.offending) for row in rows] == [("TaskHandle._run_coro()", True)]+++def test_a_collector_pass_explains_only_the_next_hold_and_only_one_at_least_as_long() -> None:+ rows: Final = summarize(_SPEC, parse_stalls((_GC_PASS, _STARTUP, _HANDLER)))+ assert sorted((row.coroutine, row.offending) for row in rows) == [+ ("LifespanOn.main()", False),+ ("RequestResponseCycle.run_asgi()", False),+ ]+ assert summarize(_SPEC, parse_stalls((_GC_PASS,))) == ()diff --git a/tests/unit/proxy/common_utils/test_slow_gc_logger.py b/tests/unit/proxy/common_utils/test_slow_gc_logger.pynew file mode 100644index 00000000000..4bc78789b59--- /dev/null+++ b/tests/unit/proxy/common_utils/test_slow_gc_logger.py@@ -0,0 +1,31 @@+from __future__ import annotations++import gc+import re+from itertools import count+from typing import Final++from litellm.proxy.common_utils.slow_gc_logger import SlowGcLogger+++def _collect_once(step_seconds: float) -> tuple[str, ...]:+ ticks: Final = count(step=step_seconds)+ lines: Final[list[str]] = [] # mutable-ok: collects what the logger emits during one real gc.collect()+ logger: Final = SlowGcLogger(threshold_seconds=0.1, log=lines.append, clock=lambda: next(ticks))+ gc.callbacks.append(logger)+ try:+ gc.collect()+ finally:+ gc.callbacks.remove(logger)+ return tuple(lines)+++def test_a_full_collection_past_the_threshold_is_logged_with_its_generation_and_length() -> None:+ lines: Final = _collect_once(step_seconds=0.25)+ assert any(re.fullmatch(r"Garbage collection gen=2 collected=\d+ took 0\.250 seconds", line) for line in lines), (+ lines+ )+++def test_a_collection_under_the_threshold_is_not_logged() -> None:+ assert _collect_once(step_seconds=0.01) == ()diff --git a/tests/unit/proxy/test_proxy_cli.py b/tests/unit/proxy/test_proxy_cli.pyindex ff45610ac72..89a35923be0 100644--- a/tests/unit/proxy/test_proxy_cli.py+++ b/tests/unit/proxy/test_proxy_cli.py@@ -526,6 +526,12 @@ class TestProxyInitializationHelpers:with patch("sys.platform", "linux"):assert ProxyInitializationHelpers._get_loop_type() == "uvloop"+ @pytest.mark.parametrize(("env_value", "expected"), [("asyncio", "asyncio"), ("uvloop", "uvloop"), ("", "uvloop")])+ def test_get_loop_type_honors_litellm_event_loop_env(self, env_value: str, expected: str, monkeypatch) -> None:+ monkeypatch.setattr("sys.platform", "linux")+ monkeypatch.setenv("LITELLM_EVENT_LOOP", env_value)+ assert ProxyInitializationHelpers._get_loop_type() == expected+def test_selected_loop_factory_imports_on_this_interpreter(self):loop_type = ProxyInitializationHelpers._get_loop_type()if loop_type is None: