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(logging_worker): rescue dequeued logging tasks lost at event loop close
mateo-berri1ba1a8038c1b
diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.pyindex 77792671f6f..b5aca3bcdb9 100644--- a/litellm/litellm_core_utils/logging_worker.py+++ b/litellm/litellm_core_utils/logging_worker.py@@ -4,6 +4,7 @@import asyncioimport atexitimport contextvars+import inspectimport loggingfrom collections.abc import Coroutine, Iteratorfrom typing import Final@@ -53,6 +54,7 @@ class LoggingWorker:self._queue: asyncio.Queue[LoggingTask] | None = Noneself._worker_task: asyncio.Task | None = Noneself._running_tasks: set[asyncio.Task] = set()+ self._dequeued_tasks: dict[int, LoggingTask] = {} # mutable-ok: refs so flush can rescue never-started tasksself._sem: asyncio.Semaphore | None = Noneself._bound_loop: asyncio.AbstractEventLoop | None = Noneself._last_aggressive_clear_time: float = 0.0@@ -61,6 +63,27 @@ class LoggingWorker:# Register cleanup handler to flush remaining events on exitatexit.register(self._flush_on_exit)+ def _track_dequeued(self, task: LoggingTask) -> None:+ self._dequeued_tasks[id(task)] = task++ def _untrack_dequeued(self, task: LoggingTask) -> None:+ self._dequeued_tasks.pop(id(task), None)++ def _unstarted_dequeued_tasks(self) -> tuple[LoggingTask, ...]:+ return tuple(+ task+ for task in self._dequeued_tasks.values()+ if inspect.getcoroutinestate(task["coroutine"]) == inspect.CORO_CREATED+ )++ @staticmethod+ def _run_coroutine_silently(loop: asyncio.AbstractEventLoop, coroutine: Coroutine) -> bool:+ try:+ loop.run_until_complete(coroutine)+ except Exception: # noqa: BLE001 # atexit flush must never break the user's program+ return False+ return True+@staticmethoddef _drain_pending(queue: "asyncio.Queue[LoggingTask]") -> tuple[LoggingTask, ...]:"""Pop every task still queued, without awaiting them, so they can be moved to another queue."""@@ -129,6 +152,7 @@ class LoggingWorker:except Exception as e:verbose_logger.exception("LoggingWorker error: %s", e)finally:+ self._untrack_dequeued(task)self._queue.task_done()finally:# Always release semaphore, even if queue is None@@ -146,6 +170,7 @@ class LoggingWorker:await self._sem.acquire()try:task = await self._queue.get()+ self._track_dequeued(task)# Track each spawned coroutine so we can cancel on shutdown.processing_task = asyncio.create_task(self._process_log_task(task, self._sem))self._running_tasks.add(processing_task)@@ -298,9 +323,10 @@ class LoggingWorker:extracted_tasks: Final = []for _ in range(items_to_extract):try:- extracted_tasks.append(self._queue.get_nowait())+ extracted_tasks.append(extracted := self._queue.get_nowait())except asyncio.QueueEmpty:break+ self._track_dequeued(extracted)return extracted_tasks@@ -318,6 +344,7 @@ class LoggingWorker:# Add new task to extracted tasks to process directlyif new_task is not None:+ self._track_dequeued(new_task)extracted_tasks.append(new_task)# Process extracted tasks directly@@ -343,6 +370,7 @@ class LoggingWorker:# Suppress errors during processing to ensure we keep goingpassfinally:+ self._untrack_dequeued(task)self._queue.task_done()async def _process_extracted_tasks(self, tasks: list[LoggingTask]) -> None:@@ -486,11 +514,12 @@ class LoggingWorker:self._safe_log("debug", "[LoggingWorker] atexit: No queue initialized")return- if self._queue.empty():+ unstarted_dequeued: Final = self._unstarted_dequeued_tasks()+ if self._queue.empty() and not unstarted_dequeued:self._safe_log("debug", "[LoggingWorker] atexit: Queue is empty")return- queue_size: Final = self._queue.qsize()+ queue_size: Final = self._queue.qsize() + len(unstarted_dequeued)self._safe_log("info", f"[LoggingWorker] atexit: Flushing {queue_size} remaining events...")# Create a new event loop since the original is closed@@ -509,6 +538,16 @@ class LoggingWorker:previous_raise_exceptions: Final = logging.raiseExceptionslogging.raiseExceptions = Falsetry:+ for pending in unstarted_dequeued:+ if (+ processed >= MAX_ITERATIONS_TO_CLEAR_QUEUE+ or loop.time() - start_time >= MAX_TIME_TO_CLEAR_QUEUE+ ):+ break+ if self._run_coroutine_silently(loop, pending["coroutine"]):+ processed += 1+ self._untrack_dequeued(pending)+while not self._queue.empty() and processed < MAX_ITERATIONS_TO_CLEAR_QUEUE:if loop.time() - start_time >= MAX_TIME_TO_CLEAR_QUEUE:self._safe_log(@@ -525,15 +564,10 @@ class LoggingWorker:# Run the coroutine synchronously in new loop# Note: We run the coroutine directly, not via create_task,# since we're in a new event loop context- try:- loop.run_until_complete(task["coroutine"])+ if self._run_coroutine_silently(loop, task["coroutine"]):processed += 1- except Exception:- # Silent failure to not break user's program- pass- finally:- # Clear reference to prevent memory leaks- task = None+ # Clear reference to prevent memory leaks+ task = Nonefinally:logging.raiseExceptions = previous_raise_exceptionsdiff --git a/ruff-strict-budget.json b/ruff-strict-budget.jsonindex d5d24904a71..b24335ad112 100644--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@ -57,7 +57,7 @@"limit": 3},"BLE001": {- "limit": 2918+ "limit": 2917},"C401": {"limit": 8@@ -189,7 +189,7 @@"limit": 0},"S110": {- "limit": 218+ "limit": 217},"S112": {"limit": 22diff --git a/tests/test_litellm/litellm_core_utils/test_logging_worker.py b/tests/test_litellm/litellm_core_utils/test_logging_worker.pyindex 80c9585dae9..3c7945f1611 100644--- a/tests/test_litellm/litellm_core_utils/test_logging_worker.py+++ b/tests/test_litellm/litellm_core_utils/test_logging_worker.py@@ -97,6 +97,32 @@ class TestLoggingWorker:logging.raiseExceptions = previous_raise_exceptionslogger.removeHandler(handler)+ def test_flush_on_exit_rescues_dequeued_coroutine_never_started(self):+ """+ Regression test for cache-hit success callbacks lost in short-lived SDK scripts:+ the worker loop dequeues the task, then ``asyncio.run`` cancels the processing+ task before it ever runs, so the coroutine leaves the queue without being+ awaited and the atexit flush used to find an empty queue and rescue nothing.+ """+ worker = LoggingWorker(timeout=1.0, max_queue_size=10)+ fired = []++ async def marker():+ fired.append(True)++ async def short_lived_script():+ worker.ensure_initialized_and_enqueue(marker())++ asyncio.run(short_lived_script())++ assert worker._queue is not None+ assert worker._queue.qsize() == 0, "precondition: the worker loop dequeued the task before loop close"+ assert fired == [], "precondition: the callback never ran before loop close"++ worker._flush_on_exit()++ assert fired == [True]+def test_flush_on_exit_swallows_errors_and_drains_remaining(self):"""A failing queued coroutine must not abort the atexit drain of later events."""worker = LoggingWorker(timeout=1.0, max_queue_size=10)