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): swallow cancellation in exit flush and revive dequeued tasks on loop change
mateo-berrief7ba3e54b11
diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.pyindex e1501ce5325..1d74595781a 100644--- a/litellm/litellm_core_utils/logging_worker.py+++ b/litellm/litellm_core_utils/logging_worker.py@@ -76,10 +76,22 @@ class LoggingWorker:if inspect.getcoroutinestate(task["coroutine"]) == inspect.CORO_CREATED)+ def _requeue_unstarted_dequeued(self, new_queue: "asyncio.Queue[LoggingTask]") -> int:+ revived: Final = self._unstarted_dequeued_tasks()+ self._dequeued_tasks.clear()+ for index, revived_task in enumerate(revived):+ try:+ new_queue.put_nowait(revived_task)+ except asyncio.QueueFull:+ for leftover in revived[index:]:+ self._track_dequeued(leftover)+ return index+ return len(revived)+def _run_coroutine_silently(self, loop: asyncio.AbstractEventLoop, coroutine: Coroutine) -> bool:try:loop.run_until_complete(asyncio.wait_for(coroutine, timeout=self.timeout))- except Exception: # noqa: BLE001 # atexit flush must never break the user's program+ except (Exception, asyncio.CancelledError): # noqa: BLE001 # atexit flush must never break the user's programreturn Falsereturn True@@ -112,10 +124,12 @@ class LoggingWorker:new_queue: Final[asyncio.Queue[LoggingTask]] = asyncio.Queue(maxsize=self.max_queue_size)for carried_task in carried_over:new_queue.put_nowait(carried_task)- if carried_over:+ revived_count: Final = self._requeue_unstarted_dequeued(new_queue)+ if carried_over or revived_count:verbose_logger.warning(- "LoggingWorker: event loop changed; carried %d pending logging task(s) onto the new loop",+ "LoggingWorker: event loop changed; carried %d pending and revived %d dequeued logging task(s) onto the new loop",len(carried_over),+ revived_count,)else:verbose_logger.debug("LoggingWorker: Event loop changed, reinitializing queue and worker")diff --git a/tests/test_litellm/litellm_core_utils/test_logging_worker.py b/tests/test_litellm/litellm_core_utils/test_logging_worker.pyindex 3c7945f1611..eb4e893adb8 100644--- a/tests/test_litellm/litellm_core_utils/test_logging_worker.py+++ b/tests/test_litellm/litellm_core_utils/test_logging_worker.py@@ -144,6 +144,53 @@ class TestLoggingWorker:assert processed == ["ran"]assert worker._queue.empty()+ def test_loop_change_revives_dequeued_coroutine_on_new_loop(self):+ """+ A callback dequeued but never started before its loop closed must run on the+ next event loop's worker instead of staying stranded until process exit.+ """+ worker = LoggingWorker(timeout=1.0, max_queue_size=10)+ fired = []++ async def marker(name):+ fired.append(name)++ async def first_script():+ worker.ensure_initialized_and_enqueue(marker("first"))++ asyncio.run(first_script())+ assert fired == [], "precondition: the callback was dequeued but never ran before loop close"++ async def second_script():+ worker.ensure_initialized_and_enqueue(marker("second"))+ assert worker._queue is not None+ await asyncio.wait_for(worker._queue.join(), timeout=5)++ asyncio.run(second_script())++ assert sorted(fired) == ["first", "second"]++ def test_flush_on_exit_swallows_cancellation_and_drains_remaining(self):+ """A callback raising CancelledError must not abort the atexit flush of later events."""+ worker = LoggingWorker(timeout=1.0, max_queue_size=10)+ worker._queue = asyncio.Queue(maxsize=10)++ processed = []++ async def cancels_during_flush():+ raise asyncio.CancelledError()++ async def records_during_flush():+ processed.append("ran")++ worker.enqueue(cancels_during_flush())+ worker.enqueue(records_during_flush())++ worker._flush_on_exit()++ assert processed == ["ran"]+ assert worker._queue.empty()+@pytest.mark.asyncioasync def test_worker_handles_cancellation_gracefully(self, logging_worker):"""Test that the worker handles cancellation without throwing exceptions."""