From 04d75f7a965b6b8a1b77d46b51096f2df8dd1f48 Mon Sep 17 00:00:00 2001 From: Qiuner Date: Mon, 30 Nov 2026 06:54:39 -0300 Subject: [PATCH] refactor(runtime): unify foreground and background turn recovery --- deeptutor/app/service.py | 96 ++----------------- deeptutor/runtime/coordination/recovery.py | 19 +++- .../coordination/test_journal_recovery.py | 17 +++- 3 files changed, 36 insertions(+), 96 deletions(-) diff --git a/deeptutor/app/service.py b/deeptutor/app/service.py index 9cae0f1e1..a99b6dc9b 100644 --- a/deeptutor/app/service.py +++ b/deeptutor/app/service.py @@ -4,13 +4,12 @@ from __future__ import annotations import asyncio from collections.abc import AsyncIterator -import contextlib import hashlib import json import time from typing import Any -from deeptutor.runtime.coordination import RuntimeCoordinator +from deeptutor.runtime.coordination import RuntimeCoordinator, TurnRecoveryService from deeptutor.services.session.protocol import ActiveTurnConflict, SessionStoreProtocol from deeptutor.services.session.turn_runtime import TurnRuntimeManager from deeptutor.services.workspace.activity import workspace_writer @@ -442,11 +441,6 @@ class TurnApplicationService: }: return False if await self.coordinator.get_lease(turn_id) is None: - # 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 @@ -506,13 +500,6 @@ class TurnApplicationService: if await store.get_turn(turn_id) is None: return False if await self.coordinator.get_lease(turn_id) is None: - # Nobody owns the turn: a queued command would never be read. If - # the durable row still says ``waiting_input`` it is a zombie — - # the worker that owned the waiter is gone, and without this the - # session is blocked forever while the card sits on screen - # (#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_live_turn(turn_id) return False await self.coordinator.submit_command( @@ -533,13 +520,6 @@ class TurnApplicationService: out from the UI (#1297, #1359). Users reported exactly that — one window, no refresh, and a conversation that never accepts another word. - Liveness is the lease, never the row's age: a turn parked on an - ``ask_user`` card emits no events, so ``updated_at`` stops advancing - while it legitimately waits for a person to type. A sweep on age would - cancel that reader mid-answer. A live worker renews its lease every few - seconds whether or not it is producing output, so "no lease" is the one - signal that separates a zombie from a slow human. - This synchronous path avoids waiting for the background recovery pass when a new request is already blocked. Admission acquires its lease before inserting a turn, so a live new row is protected even @@ -557,84 +537,20 @@ class TurnApplicationService: turn_id = str(row.get("id") or row.get("turn_id") or "") if not turn_id: continue - if await self.coordinator.get_lease(turn_id) is not None: - # Something is genuinely executing it. The conflict is real and - # the caller should see it. - continue if await self._reap_unowned_live_turn(turn_id): reclaimed = True return reclaimed 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 status - with the fencing token, ``worker_lost`` failure code, error+done - events) so whatever raced us wins cleanly and subscribed clients - stop deterministically. Returns ``True`` when a zombie was reaped. - """ store, _runtime = self._resolve() try: - turn = await store.get_turn(turn_id) + outcome = await TurnRecoveryService(self.coordinator, store).recover_turn( + turn_id, + error="The worker executing this turn was lost; resend your answer as a new message", + ) + return outcome is True except Exception: return False - if turn is None or str(turn.get("status") or "") not in { - "queued", - "running", - "waiting_input", - }: - return False - error = "The worker executing this turn was lost; resend your answer as a new message" - metadata = { - "turn_terminal": True, - "status": "failed", - "error_code": "worker_lost", - "retryable": True, - } - reap_event: dict[str, Any] = { - "type": "error", - "source": "turn_recovery", - "stage": "recovery", - "content": error, - "metadata": metadata, - "session_id": turn.get("session_id", ""), - } - done_event: dict[str, Any] = { - "type": "done", - "source": "turn_recovery", - "stage": "recovery", - "content": "", - "metadata": {"status": "failed", "error_code": "worker_lost", "retryable": True}, - "session_id": turn.get("session_id", ""), - } - try: - transitioned = await store.transition_turn( - turn_id, - "failed", - expected_status=str(turn["status"]), - fencing_token=int(turn.get("fencing_token") or 0), - error=error, - failure_code="worker_lost", - retryable=True, - ) - if not transitioned: - # A recovery pass or a late executor write beat us to it. - return False - await store.append_events( - turn_id, - [reap_event, done_event], - fencing_token=int(turn.get("fencing_token") or 0), - ) - except Exception: - return False - for event in (reap_event, done_event): - with contextlib.suppress(Exception): - await self.coordinator.publish_event(turn_id, event) - return True async def submit_user_input( self, diff --git a/deeptutor/runtime/coordination/recovery.py b/deeptutor/runtime/coordination/recovery.py index fcea79bca..f4724aef8 100644 --- a/deeptutor/runtime/coordination/recovery.py +++ b/deeptutor/runtime/coordination/recovery.py @@ -44,7 +44,7 @@ class TurnRecoveryService: recovered = 0 for turn_id in turn_ids: try: - outcome = await self._recover_turn(turn_id) + outcome = await self.recover_turn(turn_id) # An expired id can belong to a different user repository. # Do not globally acknowledge it until the leader finds the # repository that owns the turn. @@ -58,7 +58,13 @@ class TurnRecoveryService: self.backlog = max(0, self.backlog - recovered) return recovered - async def _recover_turn(self, turn_id: str) -> bool | None: + async def recover_turn( + self, + turn_id: str, + *, + error: str = "The worker executing this turn was lost; regenerate to retry", + ) -> bool | None: + """Return True for recovery, False for a terminal row, None for a live or missing turn.""" turn = await self.repository.get_turn(turn_id) if turn is None: return None @@ -89,7 +95,7 @@ class TurnRecoveryService: TurnStatus.FAILED.value, expected_status=str(turn["status"]), fencing_token=token, - error="The worker executing this turn was lost; regenerate to retry", + error=error, failure_code=TurnFailureCode.WORKER_LOST.value, retryable=True, ) @@ -104,7 +110,7 @@ class TurnRecoveryService: "type": "error", "source": "turn_recovery", "stage": "recovery", - "content": "The worker executing this turn was lost; regenerate to retry", + "content": error, "metadata": { "turn_terminal": True, "status": TurnStatus.FAILED.value, @@ -129,7 +135,10 @@ class TurnRecoveryService: fencing_token=token, ) for event in events: - await self.coordinator.publish_event(turn_id, event) + try: + await self.coordinator.publish_event(turn_id, event) + except Exception: + logger.exception("Failed to notify subscribers of recovery for turn %s", turn_id) return True diff --git a/tests/runtime/coordination/test_journal_recovery.py b/tests/runtime/coordination/test_journal_recovery.py index 1b966b66e..2482295e6 100644 --- a/tests/runtime/coordination/test_journal_recovery.py +++ b/tests/runtime/coordination/test_journal_recovery.py @@ -1,13 +1,16 @@ from __future__ import annotations import asyncio +from types import SimpleNamespace from unittest.mock import AsyncMock import pytest +from deeptutor.app.service import TurnApplicationService from deeptutor.runtime.coordination import MemoryCoordinator from deeptutor.runtime.coordination.journal import TurnEventJournal from deeptutor.runtime.coordination.recovery import TurnRecoveryService +from deeptutor.services.session.protocol import ActiveTurnConflict from deeptutor.services.session.sqlite_store import SQLiteSessionStore @@ -248,10 +251,22 @@ asyncio.run(run()) ready = await asyncio.wait_for(asyncio.to_thread(process.stdout.readline), 15) assert ready == "ready\n", process.stderr.read() if not ready else ready store = SQLiteSessionStore(db) - recovery = TurnRecoveryService(MemoryCoordinator(), store) + coordinator = MemoryCoordinator() + recovery = TurnRecoveryService(coordinator, store) + runtime = AsyncMock() + runtime.start_turn.side_effect = ActiveTurnConflict("Session already has an active turn") + application = TurnApplicationService( + SimpleNamespace(get=lambda: store), SimpleNamespace(get=lambda _: runtime), coordinator + ) original = await store.get_events("cli-turn") for _ in range(3): assert await recovery.recover_once() == 0 + assert not await application.cancel_turn("cli-turn") + assert not await application.submit_user_reply("cli-turn", text="continue") + session_id = (await store.get_turn("cli-turn"))["session_id"] + with pytest.raises(ActiveTurnConflict): + await application.start_turn({"session_id": session_id, "content": "next"}) + runtime.start_turn.assert_awaited_once() assert (await store.get_turn("cli-turn"))["status"] == status assert await store.get_events("cli-turn") == original process.terminate()