DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(runtime): cancel the capability when a turn's consumer stops (#1413)
Hyeonsang Cho3fab0de80d54
diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pyindex 2693e9cd8..887e982bf 100644--- a/deeptutor/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -9,6 +9,7 @@ All consumers (CLI, WebSocket, SDK) call the orchestrator.from __future__ import annotationsimport asyncio+import contextlibimport loggingfrom typing import Any, AsyncIteratorimport uuid@@ -168,11 +169,21 @@ class ChatOrchestrator:stream = bus.subscribe()task = asyncio.create_task(_run())+ try:+ async for event in stream:+ yield event+ await task+ finally:+ # The capability runs in its own task, so a consumer that stops+ # reading — a cancelled turn, or a stream closed early — does not+ # stop it. Left running, it keeps calling the model and tools for a+ # turn already reported as stopped; left parked on ``ask_user``, it+ # is collected mid-await and ``_run`` never unregisters the bus.+ if not task.done():+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await task- async for event in stream:- yield event-- await taskawait self._publish_completion(context, cap_name)async def _publish_completion(self, context: UnifiedContext, cap_name: str) -> None:diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.pyindex 94e50fec3..aba74b61a 100644--- a/tests/runtime/test_orchestrator.py+++ b/tests/runtime/test_orchestrator.py@@ -11,7 +11,7 @@ from deeptutor.core.capability_protocol import CapabilityManifest, TurnCapabilitfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.runtime.orchestrator import ChatOrchestrator-from deeptutor.runtime.stream_bus import StreamBus+from deeptutor.runtime.stream_bus import StreamBus, get_bus@pytest.fixture(autouse=True)@@ -53,6 +53,24 @@ class _FailingCapability(TurnCapability):raise RuntimeError("intentional failure")+class _ParkedCapability(TurnCapability):+ """Capability that streams once, then waits until it is cancelled."""++ manifest = CapabilityManifest(name="parked", description="Waits after its first event.")++ def __init__(self) -> None:+ self.cancelled = asyncio.Event()++ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:+ await stream.content("thinking", source=self.name)+ try:+ # Stands in for a long model round or an ``ask_user`` pause.+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ self.cancelled.set()+ raise++def _make_orchestrator(capabilities: dict[str, TurnCapability] | None = None,) -> ChatOrchestrator:@@ -200,6 +218,59 @@ class TestOrchestratorErrorHandling:}+# ---------------------------------------------------------------------------+# Cancellation+# ---------------------------------------------------------------------------+++class TestOrchestratorCancellation:+ @pytest.mark.asyncio+ async def test_cancelling_the_consumer_cancels_the_capability(self) -> None:+ """Stopping a turn must stop the capability, not only the event stream."""+ parked = _ParkedCapability()+ orch = _make_orchestrator({"parked": parked})+ ctx = UnifiedContext(+ user_message="hi",+ active_capability="parked",+ metadata={"turn_id": "turn-cancelled"},+ )+ first_content = asyncio.Event()++ async def _consume() -> None:+ async for event in orch.handle(ctx):+ if event.type == StreamEventType.CONTENT:+ first_content.set()++ consumer = asyncio.create_task(_consume())+ await asyncio.wait_for(first_content.wait(), timeout=1)+ consumer.cancel()+ with pytest.raises(asyncio.CancelledError):+ await consumer++ assert parked.cancelled.is_set()+ assert get_bus("turn-cancelled") is None++ @pytest.mark.asyncio+ async def test_closing_the_stream_early_cancels_the_capability(self) -> None:+ """A consumer that stops reading takes the capability down with it."""+ parked = _ParkedCapability()+ orch = _make_orchestrator({"parked": parked})+ ctx = UnifiedContext(+ user_message="hi",+ active_capability="parked",+ metadata={"turn_id": "turn-closed"},+ )++ stream = orch.handle(ctx)+ async for event in stream:+ if event.type == StreamEventType.CONTENT:+ break+ await stream.aclose()++ assert parked.cancelled.is_set()+ assert get_bus("turn-closed") is None++# ---------------------------------------------------------------------------# Session ID management# ---------------------------------------------------------------------------