Architecture optimization: unify turn recovery across request and background paths (#3099)

This commit is contained in:
Bingxi Zhao (Frank)
2026-12-02 05:32:24 -05:00
3 changed files with 33 additions and 63 deletions

View File

@@ -4,14 +4,13 @@ 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.core.turn_status import ACTIVE_TURN_STATUSES, TERMINAL_TURN_STATUSES
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
@@ -439,11 +438,6 @@ class TurnApplicationService:
if turn is None or turn.get("status") not in ACTIVE_TURN_STATUSES:
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
@@ -503,13 +497,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(
@@ -530,13 +517,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
@@ -554,54 +534,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)
except Exception:
return False
if turn is None or str(turn.get("status") or "") not in ACTIVE_TURN_STATUSES:
return False
error = "The worker executing this turn was lost; resend your answer as a new message"
try:
transitioned = await store.transition_turn(
outcome = await TurnRecoveryService(self.coordinator, store).recover_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,
error="The worker executing this turn was lost; resend your answer as a new message",
)
if not transitioned:
# A recovery pass or a late executor write beat us to it.
return False
events = (await store.get_events(turn_id))[-2:]
return outcome is True
except Exception:
return False
for event in events:
with contextlib.suppress(Exception):
await self.coordinator.publish_event(turn_id, event)
return True
async def submit_user_input(
self,

View File

@@ -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
@@ -92,14 +98,17 @@ 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,
)
if not transitioned:
return False
for event in (await self.repository.get_events(turn_id))[-2:]:
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

View File

@@ -2,13 +2,16 @@ from __future__ import annotations
import asyncio
import sqlite3
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
@@ -257,10 +260,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.stdin.write("\n")