Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(turns): let a session blocked by a dead turn clear itself

Bingxi Zhao (Frank)9feec62215e0
diff --git a/deeptutor/app/service.py b/deeptutor/app/service.py
index 54887f54f..153adf833 100644
--- a/deeptutor/app/service.py
+++ b/deeptutor/app/service.py
@@ -9,7 +9,7 @@ import time
from typing import Any
from deeptutor.runtime.coordination import RuntimeCoordinator
-from deeptutor.services.session.protocol import SessionStoreProtocol
+from deeptutor.services.session.protocol import ActiveTurnConflict, SessionStoreProtocol
from deeptutor.services.session.turn_runtime import TurnRuntimeManager
from .contracts import TurnRequest
@@ -38,7 +38,15 @@ class TurnApplicationService:
)
payload = request.to_payload()
store, runtime = self._resolve()
- session, turn = await runtime.start_turn(payload)
+ try:
+ session, turn = await runtime.start_turn(payload)
+ except ActiveTurnConflict:
+ # Retry once, and only after something was actually reclaimed, so a
+ # session busy with a live turn still gets its conflict.
+ session_id = str(payload.get("session_id") or "")
+ if not session_id or not await self._reclaim_unowned_active_turn(session_id):
+ raise
+ session, turn = await runtime.start_turn(payload)
await store.update_session_preferences(
session["id"],
{
@@ -56,7 +64,12 @@ class TurnApplicationService:
overrides: dict[str, Any] | None = None,
) -> tuple[dict[str, Any], dict[str, Any]]:
_store, runtime = self._resolve()
- return await runtime.regenerate_last_turn(session_id, overrides=overrides)
+ try:
+ return await runtime.regenerate_last_turn(session_id, overrides=overrides)
+ except ActiveTurnConflict:
+ if not await self._reclaim_unowned_active_turn(session_id):
+ raise
+ return await runtime.regenerate_last_turn(session_id, overrides=overrides)
# How long to keep reading after DONE before closing the stream.
#
@@ -252,6 +265,48 @@ class TurnApplicationService:
)
return True
+ async def _reclaim_unowned_active_turn(self, session_id: str) -> bool:
+ """Clear the rows blocking this session that nothing is executing.
+
+ ``_begin_turn_sync`` refuses a new turn while the session owns any row
+ in ``queued``/``running``/``waiting_input``. That is right while a turn
+ is alive and catastrophic once one is not: a single row left behind by
+ a lost worker or a restart blocks *every* later message, with no way
+ 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.
+
+ Doing it here rather than on a timer is what makes it safe: the only
+ rows ever considered are ones already blocking a real request, so
+ there is no window in which a just-inserted turn can be swept before
+ its first renewal — the hazard that kept the periodic version out.
+
+ Returns ``True`` when something was reaped and the caller should retry.
+ """
+ store, _runtime = self._resolve()
+ try:
+ active = await store.list_active_turns(session_id)
+ except Exception:
+ return False
+ reclaimed = False
+ for row in active:
+ 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.
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index 08286527a..ef277f4a0 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -25,6 +25,8 @@ import time
from typing import Any
import uuid
+from deeptutor.services.session.protocol import ActiveTurnConflict
+
from .ask_user_trace import filter_ask_user_events
from .event_preview import MAX_TRACE_PREVIEW_EVENTS, compact_trace_preview
from .provider_response_state import redact_private_message_metadata
@@ -815,7 +817,10 @@ class PocketBaseSessionStore:
if getattr(record, "status", "") in _ACTIVE_TURN_STATUSES
]
if active:
- raise RuntimeError(f"Session already has an active turn: {active[0].turn_id}")
+ raise ActiveTurnConflict(
+ f"Session already has an active turn: {active[0].turn_id}",
+ turn_id=str(active[0].turn_id),
+ )
return (
_pb()
.collection("turns")
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index 8e4491691..d13da4c4e 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -10,6 +10,24 @@ from __future__ import annotations
from typing import Any, Protocol, runtime_checkable
+class ActiveTurnConflict(RuntimeError):
+ """A session already owns a turn that has not reached a terminal state.
+
+ Named rather than a bare ``RuntimeError`` so a caller can tell "this
+ session is busy" from any other runtime failure without matching on the
+ message. Subclasses ``RuntimeError`` because every existing handler
+ catches that, and the message is unchanged for the same reason.
+
+ ``turn_id`` is the row that blocks the session, when the store knows it;
+ the unique-index race reports the session instead, having lost the race
+ to read it.
+ """
+
+ def __init__(self, message: str, *, turn_id: str = "") -> None:
+ super().__init__(message)
+ self.turn_id = turn_id
+
+
@runtime_checkable
class SessionRepository(Protocol):
async def migrate_workspace_preferences(self) -> int: ...
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 53420b9e0..ebb6fefaa 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -23,6 +23,7 @@ except ImportError: # pragma: no cover - exercised only on Windows
fcntl = None # type: ignore[assignment]
from deeptutor.services.path_service import get_path_service
+from deeptutor.services.session.protocol import ActiveTurnConflict
from deeptutor.utils.secret_files import ensure_private_directory, ensure_private_file
from .ask_user_trace import select_ask_user_events
@@ -859,7 +860,10 @@ class SQLiteSessionStore:
(session_id,),
).fetchone()
if active is not None:
- raise RuntimeError(f"Session already has an active turn: {active['id']}")
+ raise ActiveTurnConflict(
+ f"Session already has an active turn: {active['id']}",
+ turn_id=str(active["id"]),
+ )
conn.execute(
"""
INSERT INTO turns (
@@ -881,7 +885,7 @@ class SQLiteSessionStore:
except sqlite3.IntegrityError as exc:
# The partial unique index wins races where another process inserts
# after our read but before our insert.
- raise RuntimeError(f"Session already has an active turn: {session_id}") from exc
+ raise ActiveTurnConflict(f"Session already has an active turn: {session_id}") from exc
return {
"id": resolved_turn_id,
"turn_id": resolved_turn_id,
diff --git a/tests/app/test_blocked_session_reclaims_itself.py b/tests/app/test_blocked_session_reclaims_itself.py
new file mode 100644
index 000000000..fcd861aed
--- /dev/null
+++ b/tests/app/test_blocked_session_reclaims_itself.py
@@ -0,0 +1,151 @@
+"""A session blocked by a dead turn must unblock itself on the next message.
+
+``_begin_turn_sync`` refuses a new turn while the session owns any row in
+``queued``/``running``/``waiting_input``. Correct while a turn is alive, and
+catastrophic once one is not: a row left behind by a lost worker or a restart
+made every later message raise "Session already has an active turn", with no
+way out from the UI. Reporters described exactly that — one window, no
+refresh, a conversation that never accepted another word (#1297, #1359).
+
+Reclaiming at the point of conflict, rather than on a timer, is what makes it
+safe. The only rows ever considered are ones already blocking a real request,
+so a turn that was just inserted cannot be swept before its first lease
+renewal — the hazard that kept a periodic sweep out of v1.6.7.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from deeptutor.app.service import TurnApplicationService
+from deeptutor.runtime.coordination import MemoryCoordinator
+from deeptutor.services.session.protocol import ActiveTurnConflict
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+
+
+class _Runtime:
+ """Enough runtime to make the store's real active-turn conflict happen."""
+
+ def __init__(self, store: SQLiteSessionStore) -> None:
+ self._store = store
+ self.attempts = 0
+
+ async def start_turn(self, payload: dict[str, Any]) -> tuple[dict, dict]:
+ self.attempts += 1
+ session_id = str(payload["session_id"])
+ turn = await self._store.begin_turn(session_id, capability="chat")
+ session = await self._store.get_session(session_id)
+ return session or {"id": session_id}, turn
+
+
+def _payload(session_id: str) -> dict[str, Any]:
+ return {
+ "session_id": session_id,
+ "content": "hello",
+ "capability": "chat",
+ "tools": [],
+ "knowledge_bases": [],
+ "attachments": [],
+ "language": "en",
+ "config": {},
+ }
+
+
+async def _blocked_session(store: SQLiteSessionStore, status: str) -> tuple[str, str]:
+ session = await store.create_session("Blocked")
+ session_id = session["id"]
+ turn = await store.begin_turn(session_id, capability="chat")
+ if status != "running":
+ assert await store.transition_turn(turn["id"], status, expected_status="running")
+ return session_id, turn["id"]
+
+
+def _application(
+ store: SQLiteSessionStore, runtime: _Runtime, coordinator
+) -> TurnApplicationService:
+ return TurnApplicationService(
+ SimpleNamespace(get=lambda: store),
+ SimpleNamespace(get=lambda _store: runtime),
+ coordinator,
+ )
+
+
[email protected]("status", ["waiting_input", "running", "queued"])
+async def test_a_message_clears_a_turn_nothing_is_executing(tmp_path, status: str) -> None:
+ """Every status ``_begin_turn_sync`` calls active blocks the session equally."""
+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")
+ session_id, blocking_id = await _blocked_session(store, status)
+ runtime = _Runtime(store)
+ application = _application(store, runtime, MemoryCoordinator(lease_ttl_seconds=5))
+
+ _session, turn = await application.start_turn(_payload(session_id))
+
+ assert turn["id"] != blocking_id, "the new message must get its own turn"
+ blocking = await store.get_turn(blocking_id)
+ assert blocking is not None
+ assert blocking["status"] == "failed"
+ assert blocking["failure_code"] == "worker_lost"
+ assert runtime.attempts == 2, "one conflict, one reclamation, one retry — no loop"
+
+
+async def test_a_turn_something_is_still_executing_is_left_alone(tmp_path) -> None:
+ """The conflict is real while a worker holds the lease, and must surface.
+
+ This is the assertion that keeps the fix from becoming a way to start two
+ turns on one session: liveness is the lease, and a live lease wins.
+ """
+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")
+ session_id, blocking_id = await _blocked_session(store, "waiting_input")
+ coordinator = MemoryCoordinator(lease_ttl_seconds=30)
+ assert await coordinator.acquire_turn(blocking_id, session_id, "worker-1") is not None
+ runtime = _Runtime(store)
+ application = _application(store, runtime, coordinator)
+
+ with pytest.raises(ActiveTurnConflict):
+ await application.start_turn(_payload(session_id))
+
+ blocking = await store.get_turn(blocking_id)
+ assert blocking is not None
+ assert blocking["status"] == "waiting_input", "a live turn must not be reaped"
+ assert runtime.attempts == 1, "no retry when nothing was reclaimed"
+
+
+async def test_a_parked_turn_whose_lease_expired_is_reclaimed(tmp_path) -> None:
+ """A worker that stopped renewing is gone, however recently it ran.
+
+ Age of the row cannot decide this: a turn parked on an ``ask_user`` card
+ emits no events, so its ``updated_at`` stops advancing while a person is
+ simply taking their time to answer.
+ """
+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")
+ session_id, blocking_id = await _blocked_session(store, "waiting_input")
+ coordinator = MemoryCoordinator(lease_ttl_seconds=-1) # already expired
+ assert await coordinator.acquire_turn(blocking_id, session_id, "worker-1") is not None
+ runtime = _Runtime(store)
+ application = _application(store, runtime, coordinator)
+
+ _session, turn = await application.start_turn(_payload(session_id))
+
+ assert turn["id"] != blocking_id
+ blocking = await store.get_turn(blocking_id)
+ assert blocking is not None and blocking["status"] == "failed"
+
+
+async def test_a_session_with_no_blocking_row_is_untouched(tmp_path) -> None:
+ """The happy path must not pay for any of this."""
+ store = SQLiteSessionStore(tmp_path / "s.sqlite3")
+ session = await store.create_session("Fresh")
+ runtime = _Runtime(store)
+ application = _application(store, runtime, MemoryCoordinator(lease_ttl_seconds=5))
+
+ _session, turn = await application.start_turn(_payload(session["id"]))
+
+ assert turn["status"] == "running"
+ assert runtime.attempts == 1
diff --git a/tests/services/session/test_turn_repository.py b/tests/services/session/test_turn_repository.py
index f590158da..b521cddfb 100644
--- a/tests/services/session/test_turn_repository.py
+++ b/tests/services/session/test_turn_repository.py
@@ -125,7 +125,11 @@ async def test_only_one_process_can_begin_an_active_turn_per_session(tmp_path) -
assert errors == []
results = [stdout.strip().splitlines()[-1] for stdout, _stderr in completed]
assert sum(result.startswith("ok:") for result in results) == 1, results
- assert results.count("error:RuntimeError") == 7, results
+ # The loser reports the named conflict, not a bare RuntimeError: callers
+ # that can clear a stale row need to tell "this session is busy" from any
+ # other failure without matching on the message. It still subclasses
+ # RuntimeError, so every existing handler keeps working.
+ assert results.count("error:ActiveTurnConflict") == 7, results
@pytest.mark.asyncio