DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
follow-up to #1361: reclaim turns parked in waiting_input
Bingxi Zhao (Frank)491a5a15cbb9
diff --git a/deeptutor/app/service.py b/deeptutor/app/service.pyindex f0cc7110e..54887f54f 100644--- a/deeptutor/app/service.py+++ b/deeptutor/app/service.py@@ -214,7 +214,12 @@ class TurnApplicationService:}:return Falseif await self.coordinator.get_lease(turn_id) is None:- return False+ # Nobody owns it, so a queued cancel would never be read. Stopping+ # a turn nothing is executing is what the learner asked for, and+ # the row is what blocks the session — reap it here for the same+ # reason ``submit_user_reply`` does, and report the stop as done+ # rather than as a refusal the UI cannot act on.+ return await self._reap_unowned_live_turn(turn_id)await self.coordinator.submit_command(turn_id, "cancel", {}, command_id=command_id)# A duplicate command ID means the mutation was already accepted. The# WebSocket adapter must acknowledge that retry as success so a client@@ -237,7 +242,7 @@ class TurnApplicationService:# (#1297). Reap it synchronously (the background recovery pass# would only sweep it on its next tick) so the client's ack# rejection comes with a terminal state to recover from.- await self._reap_unowned_waiting_turn(turn_id)+ await self._reap_unowned_live_turn(turn_id)return Falseawait self.coordinator.submit_command(turn_id,@@ -247,8 +252,12 @@ class TurnApplicationService:)return True- async def _reap_unowned_waiting_turn(self, turn_id: str) -> bool:- """Fail a persisted ``waiting_input`` turn that has no live lease.+ async def _reap_unowned_live_turn(self, turn_id: str) -> bool:+ """Fail a persisted live turn that has no live lease.++ ``queued``, ``running`` and ``waiting_input`` are all rows+ ``_begin_turn_sync`` counts as active, so any of them left behind by a+ lost worker blocks the whole session, not just the card on screen.Mirrors :class:`TurnRecoveryService`'s terminal write (CAS on statuswith the fencing token, ``worker_lost`` failure code, error+done@@ -260,7 +269,11 @@ class TurnApplicationService:turn = await store.get_turn(turn_id)except Exception:return False- if turn is None or turn.get("status") != "waiting_input":+ if turn is None or str(turn.get("status") or "") not in {+ "queued",+ "running",+ "waiting_input",+ }:return Falseerror = "The worker executing this turn was lost; resend your answer as a new message"metadata = {diff --git a/deeptutor/services/session/turns/lifecycle.py b/deeptutor/services/session/turns/lifecycle.pyindex f2855b7de..665220c92 100644--- a/deeptutor/services/session/turns/lifecycle.py+++ b/deeptutor/services/session/turns/lifecycle.py@@ -197,15 +197,31 @@ class TurnLifecycle:failure_code: str = "",retryable: bool = False,) -> bool:- return await self.store.transition_turn(- execution.turn_id,- status,- expected_status="running",- fencing_token=(execution.lease.fencing_token if execution.lease is not None else None),- error=error,- failure_code=failure_code,- retryable=retryable,- )+ # A turn parked on ``ask_user`` sits at ``waiting_input``, and the+ # waiter's ``finally`` fires its restore to ``running`` through+ # ``asyncio.shield`` — fire-and-forget, so on a cancellation it races+ # this write and loses about as often as it wins. A terminal write+ # that accepts only ``running`` therefore no-ops on exactly the turns+ # a learner stopped mid-question: no terminal row, no ``done`` event,+ # and a durable ``waiting_input`` row that ``_begin_turn_sync`` counts+ # as active — every later message in that session is refused with+ # "Session already has an active turn" (#1297, #1359). Both are live+ # states owned by this execution, so both are valid predecessors of+ # its terminal state; the fencing token is what proves ownership, and+ # it is unchanged.+ fencing_token = execution.lease.fencing_token if execution.lease is not None else None+ for expected in ("running", "waiting_input"):+ if await self.store.transition_turn(+ execution.turn_id,+ status,+ expected_status=expected,+ fencing_token=fencing_token,+ error=error,+ failure_code=failure_code,+ retryable=retryable,+ ):+ return True+ return Falseasync def _coordinate_execution(self, execution: _TurnExecution) -> None:"""Renew ownership and consume commands addressed to this worker."""diff --git a/tests/app/test_turn_parked_on_ask_user_is_reclaimable.py b/tests/app/test_turn_parked_on_ask_user_is_reclaimable.pynew file mode 100644index 000000000..9c4b4db7a--- /dev/null+++ b/tests/app/test_turn_parked_on_ask_user_is_reclaimable.py@@ -0,0 +1,112 @@+"""A turn stopped while parked on ``ask_user`` must not block its session.++Two halves of the same report (#1297, #1359):++* The terminal write on cancellation CAS'd on ``expected_status="running"``+ only. A turn parked on ``ask_user`` sits at ``waiting_input``, and the+ waiter's restore to ``running`` is fired through ``asyncio.shield`` — so it+ races that write. When it lost, nothing terminal was written and the row+ stayed ``waiting_input`` forever.+* ``_begin_turn_sync`` counts ``waiting_input`` as active, so that row made+ every later message in the session raise "Session already has an active+ turn" — the chat window looked dead until the row was edited by hand.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from deeptutor.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.session.turn_runtime import TurnRuntimeManager+++async def _park_a_turn(store: SQLiteSessionStore) -> tuple[str, str]:+ session = await store.create_session("Parked")+ session_id = session["id"]+ turn = await store.begin_turn(session_id, capability="chat")+ turn_id = turn["id"]+ assert await store.transition_turn(turn_id, "waiting_input", expected_status="running")+ return session_id, turn_id+++async def test_terminal_write_settles_a_turn_parked_on_ask_user(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")+ session_id, turn_id = await _park_a_turn(store)+ manager = TurnRuntimeManager(store)++ settled = await manager._transition_execution(+ SimpleNamespace(turn_id=turn_id, lease=None), "cancelled", "Turn cancelled"+ )++ assert settled is True, "a waiting_input row must be a valid predecessor of a terminal state"+ row = await store.get_turn(turn_id)+ assert row is not None and row["status"] == "cancelled"++ # The session is usable again: this is the assertion the report was about.+ following = await store.begin_turn(session_id, capability="chat")+ assert following["id"] != turn_id+++async def test_a_running_turn_still_settles(tmp_path) -> None:+ """The pre-existing predecessor keeps working, and is still tried first."""+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")+ session = await store.create_session("Running")+ turn = await store.begin_turn(session["id"], capability="chat")+ manager = TurnRuntimeManager(store)++ settled = await manager._transition_execution(+ SimpleNamespace(turn_id=turn["id"], lease=None), "failed", "boom"+ )++ assert settled is True+ row = await store.get_turn(turn["id"])+ assert row is not None and row["status"] == "failed"+++async def test_an_already_terminal_turn_is_left_alone(tmp_path) -> None:+ """Neither predecessor matches a finished row, so a late write is a no-op+ rather than a resurrection."""+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")+ session = await store.create_session("Done")+ turn = await store.begin_turn(session["id"], capability="chat")+ assert await store.transition_turn(turn["id"], "completed", expected_status="running")+ manager = TurnRuntimeManager(store)++ settled = await manager._transition_execution(+ SimpleNamespace(turn_id=turn["id"], lease=None), "cancelled", "Turn cancelled"+ )++ assert settled is False+ row = await store.get_turn(turn["id"])+ assert row is not None and row["status"] == "completed"+++async def test_cancelling_an_unowned_parked_turn_frees_the_session(tmp_path) -> None:+ """Stop on a card whose worker is gone: no lease means a queued cancel+ would never be read, so the row has to be settled here."""+ from deeptutor.app.service import TurnApplicationService+ from deeptutor.runtime.coordination import MemoryCoordinator++ store = SQLiteSessionStore(tmp_path / "s.sqlite3")+ session_id, turn_id = await _park_a_turn(store)+ runtime = TurnRuntimeManager(store)+ application = TurnApplicationService(+ SimpleNamespace(get=lambda: store),+ SimpleNamespace(get=lambda _store: runtime),+ MemoryCoordinator(lease_ttl_seconds=5),+ )++ assert await application.cancel_turn(turn_id) is True++ row = await store.get_turn(turn_id)+ assert row is not None+ assert row["status"] == "failed"+ assert row["failure_code"] == "worker_lost"+ following = await store.begin_turn(session_id, capability="chat")+ assert following["id"] != turn_id