DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(logs): deliver a retrieval progress event logged off the event loop
Bingxi Zhao (Frank)df1615778a53
diff --git a/deeptutor/logging/process_stream.py b/deeptutor/logging/process_stream.pyindex ae6f4f432..3b8dbad12 100644--- a/deeptutor/logging/process_stream.py+++ b/deeptutor/logging/process_stream.py@@ -66,8 +66,37 @@ class ProcessLogHandler(logging.Handler):self._emit = emitself._task_id = task_idself._turn_id = turn_id+ # The loop that owns this capture, remembered while we are still on+ # it. A record logged from a worker thread has no running loop of its+ # own, and that is where an async ``emit`` used to be dropped (#1435).+ try:+ self._loop: asyncio.AbstractEventLoop | None = asyncio.get_running_loop()+ except RuntimeError:+ self._loop = Noneself.addFilter(ContextFilter())+ def _schedule(self, coro: Any) -> None:+ """Run an async ``emit`` on the loop that owns this capture.++ Retrieval does its heavy work in worker threads, so its log records+ arrive off-loop. ``ensure_future`` needs a loop running in *this*+ thread; the owning loop is the one that can always take the call.+ """+ try:+ running = asyncio.get_running_loop()+ except RuntimeError:+ running = None+ if running is not None:+ asyncio.ensure_future(coro, loop=running)+ return+ if self._loop is not None and self._loop.is_running():+ asyncio.run_coroutine_threadsafe(coro, self._loop)+ return+ # Nothing is left to deliver to — the capture outlived its loop.+ # Close it explicitly so an undeliverable event does not also+ # surface as a "never awaited" warning with no context.+ coro.close()+def emit(self, record: logging.LogRecord) -> None:try:if getattr(record, PROCESS_LOG_PRIVATE_ATTR, False):@@ -79,11 +108,7 @@ class ProcessLogHandler(logging.Handler):returnresult = self._emit(event)if inspect.isawaitable(result):- try:- loop = asyncio.get_running_loop()- except RuntimeError:- return- asyncio.ensure_future(result, loop=loop)+ self._schedule(result)except Exception:self.handleError(record)diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.pyindex 97f01a6f7..f54eca91e 100644--- a/deeptutor/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -2,10 +2,8 @@from __future__ import annotations-import asyncioimport contextlibimport importlib-import inspectimport loggingimport osfrom pathlib import Path@@ -199,12 +197,7 @@ class RAGService:return contextlib.nullcontext()from deeptutor.logging import ProcessLogEvent, capture_process_logs- from deeptutor.logging.formatters import ContextFilter-- try:- target_loop = asyncio.get_running_loop()- except RuntimeError:- target_loop = None+ from deeptutor.logging.process_stream import ProcessLogHandlerdef should_skip_noisy_retrieve_log(event: ProcessLogEvent) -> bool:if event.level != "INFO":@@ -242,26 +235,6 @@ class RAGService:},)- class _NamedRawLogHandler(logging.Handler):- def __init__(self) -> None:- super().__init__(logging.INFO)- self.addFilter(ContextFilter())-- def emit(self, record: logging.LogRecord) -> None:- try:- result = emit(ProcessLogEvent.from_record(record))- if not inspect.isawaitable(result):- return- try:- loop = asyncio.get_running_loop()- except RuntimeError:- if target_loop and target_loop.is_running():- asyncio.run_coroutine_threadsafe(result, target_loop)- return- asyncio.ensure_future(result, loop=loop)- except Exception:- self.handleError(record)-@contextlib.contextmanagerdef capture_non_propagating_logs():handlers: list[tuple[logging.Logger, logging.Handler]] = []@@ -272,7 +245,7 @@ class RAGService:source_logger = logging.getLogger(logger_name)if source_logger.propagate:continue- handler = _NamedRawLogHandler()+ handler = ProcessLogHandler(emit, min_level=logging.INFO)source_logger.addHandler(handler)handlers.append((source_logger, handler))try:diff --git a/tests/logging/test_process_logs.py b/tests/logging/test_process_logs.pyindex b7af73549..b518e6a28 100644--- a/tests/logging/test_process_logs.py+++ b/tests/logging/test_process_logs.py@@ -1,4 +1,7 @@+import asyncioimport logging+import threading+import warningsfrom deeptutor.logging import (PROCESS_LOG_PRIVATE_ATTR,@@ -57,3 +60,40 @@ def test_capture_process_logs_excludes_server_only_diagnostics():)assert events == []+++def test_async_emit_from_a_worker_thread_still_reaches_the_stream():+ """Retrieval logs from worker threads; its progress events must survive.++ KB indexing and retrieval run their heavy work off the event loop, so the+ records they log arrive on a thread with no loop of its own. The handler+ used to drop the coroutine an async sink returned in exactly that case —+ the event never reached the reader and Python reported only+ ``coroutine '...' was never awaited`` (#1435).+ """+ seen: list[str] = []++ async def scenario() -> None:+ async def emit(event: ProcessLogEvent) -> None:+ seen.append(event.message)++ logger = logging.getLogger("deeptutor.tests.process")+ original_level = logger.level+ logger.setLevel(logging.INFO)+ try:+ with capture_process_logs(emit, min_level=logging.INFO):+ worker = threading.Thread(target=lambda: logger.info("retrieving chunk 3/8"))+ worker.start()+ worker.join()+ # Hand the loop a turn so the cross-thread call can run.+ await asyncio.sleep(0)+ await asyncio.sleep(0)+ finally:+ logger.setLevel(original_level)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ asyncio.run(scenario())++ assert seen == ["retrieving chunk 3/8"]+ assert [w for w in caught if "never awaited" in str(w.message)] == []