mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 11:32:59 +08:00
fix(logs): deliver a retrieval progress event logged off the event loop
A record logged from a worker thread reaches the handler with no running loop in that thread. `ProcessLogHandler.emit` asked for one, caught the `RuntimeError`, and returned — dropping the coroutine an async sink had already created. The reader lost the event and the only trace was `RuntimeWarning: coroutine 'RAGService._emit_tool_event' was never awaited` (#1435). Retrieval does its heavy work off-loop, so this is where its progress lines come from: the turn sat on a generic "reasoning…" for a minute or two with nothing to say what stage it was in, which is what the reporter actually felt. `rag/service.py` already knew the answer — its own raw-log handler falls back to `run_coroutine_threadsafe` on the loop it captured at setup. That is the same decision stated twice, and the generic handler, which every other caller goes through, had the wrong half of it. The rule moves into `ProcessLogHandler` and the RAG copy becomes one of its users; the duplicate handler class goes away. An event with nowhere left to go is closed explicitly rather than abandoned, so "the capture outlived its loop" no longer surfaces as a never-awaited warning pointing at a coroutine the reader cannot place. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
a7df6ca65d
commit
df1615778a
@@ -66,8 +66,37 @@ class ProcessLogHandler(logging.Handler):
|
||||
self._emit = emit
|
||||
self._task_id = task_id
|
||||
self._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 = None
|
||||
self.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):
|
||||
return
|
||||
result = 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)
|
||||
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import importlib
|
||||
import inspect
|
||||
import logging
|
||||
import os
|
||||
from 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 ProcessLogHandler
|
||||
|
||||
def 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.contextmanager
|
||||
def 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:
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import threading
|
||||
import warnings
|
||||
|
||||
from 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)] == []
|
||||
|
||||
Reference in New Issue
Block a user