mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-04 01:48:57 +00:00
* fix: drain shutdown callbacks and persist pending tag spend * fix: catch shutdown timeouts on Python 3.10 * fix: share shutdown callback budget with HTTP draining * fix: type shutdown cancellation tasks and document its clock * test: retain callbacks after bounded worker cancellation * test(proxy): inspect the lifespan body after the SIGTERM wrapper split Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(utils): keep the success callback enqueue on its own task The synchronous enqueue spawned the logging worker loop inside the awaited call and ran callbacks that per-call loops used to drop, which hung the SDK callback tests on the autouse worker flush. The shutdown worker flush covers the queued callback on its own, so the one-tick task is restored Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(logging_worker): keep the queue's unfinished count exact when a full queue rejects a callback The aggressive clear ran the rejected callback and marked it done against the queue it was never put in, so flush() could return while a real callback was still running and the shutdown drain cancelled it early. The rejected callback is now re-enqueued once the clear made room, and only runs uncounted when the queue is still full Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(logging_worker): build the aggressive-clear run set immutably Final tuple instead of an appended list, with the re-enqueue in a _requeue helper, and Final annotations on the overflow regression test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(logging): track overflow callbacks through shutdown * chore(logging): explain shared callback ownership * test(logging): isolate deferred callback completion --------- Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com> Co-authored-by: joshua <joshua@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
285 lines
10 KiB
Python
285 lines
10 KiB
Python
"""
|
|
Tests for GracefulShutdownManager.
|
|
|
|
These verify the drain logic that lets a pod terminate as soon as its real
|
|
in-flight work is done (bounded by GRACEFUL_SHUTDOWN_TIMEOUT) rather than
|
|
sleeping for a fixed worst-case duration.
|
|
"""
|
|
|
|
import time
|
|
|
|
import pytest
|
|
|
|
from litellm.proxy.shutdown.graceful_shutdown_manager import (
|
|
DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT,
|
|
GracefulShutdownManager,
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset():
|
|
GracefulShutdownManager.reset()
|
|
yield
|
|
GracefulShutdownManager.reset()
|
|
|
|
|
|
def _counter_that_drains_after(calls_before_zero: int):
|
|
"""Return a count_fn that reports N in-flight until it has been polled
|
|
`calls_before_zero` times, then reports 0."""
|
|
state = {"polls": 0}
|
|
|
|
def count_fn() -> int:
|
|
state["polls"] += 1
|
|
return 0 if state["polls"] > calls_before_zero else 3
|
|
|
|
return count_fn
|
|
|
|
|
|
# ── shutdown flag ───────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_not_shutting_down_by_default():
|
|
assert GracefulShutdownManager.is_shutting_down() is False
|
|
|
|
|
|
def test_start_shutdown_sets_flag():
|
|
GracefulShutdownManager.start_shutdown()
|
|
assert GracefulShutdownManager.is_shutting_down() is True
|
|
|
|
|
|
def test_start_shutdown_is_idempotent_and_does_not_reset_clock():
|
|
GracefulShutdownManager.start_shutdown()
|
|
first = GracefulShutdownManager._shutdown_started_at
|
|
time.sleep(0.01)
|
|
GracefulShutdownManager.start_shutdown()
|
|
assert GracefulShutdownManager._shutdown_started_at == first
|
|
|
|
|
|
def test_reset_clears_flag():
|
|
GracefulShutdownManager.start_shutdown()
|
|
GracefulShutdownManager.reset()
|
|
assert GracefulShutdownManager.is_shutting_down() is False
|
|
|
|
|
|
# ── timeout config ────────────────────────────────────────────────────────────
|
|
|
|
|
|
def test_timeout_defaults_when_unset(monkeypatch):
|
|
monkeypatch.delenv("GRACEFUL_SHUTDOWN_TIMEOUT", raising=False)
|
|
assert GracefulShutdownManager.get_timeout() == DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT
|
|
|
|
|
|
def test_timeout_reads_env(monkeypatch):
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "5")
|
|
assert GracefulShutdownManager.get_timeout() == 5.0
|
|
|
|
|
|
def test_timeout_falls_back_on_garbage(monkeypatch):
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "not-a-number")
|
|
assert GracefulShutdownManager.get_timeout() == DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT
|
|
|
|
|
|
# ── wait_for_drain ────────────────────────────────────────────────────────────
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_returns_immediately_when_already_drained():
|
|
start = time.monotonic()
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=10, count_fn=lambda: 0
|
|
)
|
|
assert drained == 0
|
|
assert time.monotonic() - start < 0.5
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_waits_until_counter_reaches_zero_then_returns_drained_count():
|
|
count_fn = _counter_that_drains_after(calls_before_zero=3)
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=10, count_fn=count_fn
|
|
)
|
|
assert drained == 3
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_times_out_when_counter_never_drains():
|
|
start = time.monotonic()
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=0.3, count_fn=lambda: 2
|
|
)
|
|
elapsed = time.monotonic() - start
|
|
assert 0.3 <= elapsed < 2.0
|
|
assert drained == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_zero_timeout_does_not_block():
|
|
start = time.monotonic()
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=0, count_fn=lambda: 5
|
|
)
|
|
assert time.monotonic() - start < 0.2
|
|
assert drained == 5
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_exclude_self_treats_one_inflight_as_drained():
|
|
"""The /health/drain request counts itself, so a steady count of 1 must be
|
|
treated as fully drained rather than timing out."""
|
|
start = time.monotonic()
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=5, exclude_self=True, count_fn=lambda: 1
|
|
)
|
|
assert time.monotonic() - start < 0.5
|
|
assert drained == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_without_exclude_self_one_inflight_blocks_until_timeout():
|
|
start = time.monotonic()
|
|
await GracefulShutdownManager.wait_for_drain(timeout=0.3, count_fn=lambda: 1)
|
|
assert time.monotonic() - start >= 0.3
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_defaults_to_get_timeout_and_live_counter(monkeypatch):
|
|
"""With no timeout/count_fn passed, it falls back to get_timeout() and the
|
|
live InFlightRequestsMiddleware counter."""
|
|
from litellm.proxy.middleware.in_flight_requests_middleware import (
|
|
InFlightRequestsMiddleware,
|
|
)
|
|
|
|
monkeypatch.delenv("GRACEFUL_SHUTDOWN_TIMEOUT", raising=False)
|
|
InFlightRequestsMiddleware._in_flight = 0
|
|
drained = await GracefulShutdownManager.wait_for_drain()
|
|
assert drained == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_second_drain_is_a_noop_so_window_is_not_doubled():
|
|
"""preStop /health/drain and the lifespan SIGTERM handler both drain; the
|
|
second call must return immediately rather than waiting another full
|
|
timeout (which would require doubling terminationGracePeriodSeconds)."""
|
|
await GracefulShutdownManager.wait_for_drain(timeout=0.2, count_fn=lambda: 1)
|
|
|
|
start = time.monotonic()
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=5, count_fn=lambda: 1
|
|
)
|
|
assert time.monotonic() - start < 0.1
|
|
assert drained == 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_emits_periodic_drain_waiting_log_while_waiting():
|
|
"""With a zero log interval, the periodic drain_waiting branch runs on each
|
|
poll until the counter finally drains."""
|
|
count_fn = _counter_that_drains_after(calls_before_zero=2)
|
|
drained = await GracefulShutdownManager.wait_for_drain(
|
|
timeout=10, count_fn=count_fn, poll_interval=0, log_interval=0
|
|
)
|
|
assert drained == 3
|
|
|
|
|
|
@pytest.mark.parametrize("elapsed, cap, expected", [(4, None, 26), (25, 2, 2), (29, 5, 1), (31, None, 0)])
|
|
def test_remaining_budget_includes_time_before_lifespan(
|
|
monkeypatch: pytest.MonkeyPatch, elapsed: float, cap: float | None, expected: float
|
|
) -> None:
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "30")
|
|
GracefulShutdownManager.start_shutdown(clock=lambda: 100.0)
|
|
GracefulShutdownManager.start_shutdown(clock=lambda: 100.0 + elapsed)
|
|
assert GracefulShutdownManager.remaining(cap, clock=lambda: 100.0 + elapsed) == expected
|
|
|
|
|
|
def test_remaining_budget_before_shutdown(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "30")
|
|
assert GracefulShutdownManager.remaining(clock=lambda: 100.0) == 30.0
|
|
assert GracefulShutdownManager.remaining(-1, clock=lambda: 100.0) == 0.0
|
|
|
|
|
|
@pytest.mark.parametrize("prestop", [False, True])
|
|
def test_sigterm_stamps_before_chaining_and_restores_server_handler(
|
|
monkeypatch: pytest.MonkeyPatch, prestop: bool
|
|
) -> None:
|
|
import signal
|
|
from queue import SimpleQueue
|
|
from types import FrameType
|
|
from typing import Final
|
|
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "30")
|
|
calls: Final[SimpleQueue[float]] = SimpleQueue()
|
|
|
|
def server_handler(signum: int, frame: FrameType | None) -> None:
|
|
assert signum == signal.SIGTERM
|
|
calls.put(GracefulShutdownManager.remaining(clock=lambda: 105.0))
|
|
|
|
original: Final = signal.signal(signal.SIGTERM, server_handler)
|
|
try:
|
|
if prestop:
|
|
GracefulShutdownManager.start_shutdown(clock=lambda: 95.0)
|
|
with GracefulShutdownManager.capture_sigterm(clock=lambda: 100.0):
|
|
installed: Final = signal.getsignal(signal.SIGTERM)
|
|
with GracefulShutdownManager.capture_sigterm(clock=lambda: 102.0):
|
|
assert signal.getsignal(signal.SIGTERM) is installed
|
|
signal.raise_signal(signal.SIGTERM)
|
|
signal.raise_signal(signal.SIGTERM)
|
|
assert calls.get_nowait() == (20.0 if prestop else 25.0)
|
|
assert calls.get_nowait() == (20.0 if prestop else 25.0)
|
|
assert calls.empty()
|
|
assert signal.getsignal(signal.SIGTERM) is server_handler
|
|
finally:
|
|
signal.signal(signal.SIGTERM, original)
|
|
|
|
|
|
def test_sigterm_capture_preserves_a_replacement_handler() -> None:
|
|
import signal
|
|
from types import FrameType
|
|
from typing import Final
|
|
|
|
def server_handler(signum: int, frame: FrameType | None) -> None:
|
|
pass
|
|
|
|
original: Final = signal.signal(signal.SIGTERM, server_handler)
|
|
try:
|
|
with GracefulShutdownManager.capture_sigterm():
|
|
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
|
assert signal.getsignal(signal.SIGTERM) is signal.SIG_IGN
|
|
finally:
|
|
signal.signal(signal.SIGTERM, original)
|
|
|
|
|
|
@pytest.mark.parametrize("handler", ["SIG_DFL", "SIG_IGN"])
|
|
def test_sigterm_capture_preserves_default_and_ignored_dispositions(handler: str) -> None:
|
|
import signal
|
|
from typing import Final
|
|
|
|
disposition: Final = signal.SIG_DFL if handler == "SIG_DFL" else signal.SIG_IGN
|
|
original: Final = signal.signal(signal.SIGTERM, disposition)
|
|
try:
|
|
with GracefulShutdownManager.capture_sigterm():
|
|
assert signal.getsignal(signal.SIGTERM) is disposition
|
|
finally:
|
|
signal.signal(signal.SIGTERM, original)
|
|
|
|
|
|
def test_sigterm_capture_in_worker_thread_leaves_signal_ownership_unchanged() -> None:
|
|
import signal
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from typing import Final
|
|
|
|
original: Final = signal.getsignal(signal.SIGTERM)
|
|
|
|
def run_lifespan() -> None:
|
|
with GracefulShutdownManager.capture_sigterm():
|
|
assert signal.getsignal(signal.SIGTERM) is original
|
|
|
|
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
executor.submit(run_lifespan).result()
|
|
assert signal.getsignal(signal.SIGTERM) is original
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lifespan_request_drain_does_not_restart_an_exhausted_budget(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setenv("GRACEFUL_SHUTDOWN_TIMEOUT", "30")
|
|
GracefulShutdownManager.start_shutdown(clock=lambda: 100.0)
|
|
assert await GracefulShutdownManager.wait_for_drain(count_fn=lambda: 2, clock=lambda: 130.0) == 2
|