Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(session-turns): read a recovered starting Turn's owner off the controller loop (#2772)
Call White6a6909048801
diff --git a/core/session_turns.py b/core/session_turns.pyindex e098ffb4e..206978f0e 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -23,8 +23,9 @@ import weakreffrom contextlib import contextmanagerfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezone+from functools import partialfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Awaitable, Callable, ContextManager, Iterator, Literal, Optional+from typing import TYPE_CHECKING, Any, Awaitable, Callable, ContextManager, Iterator, Literal, Optional, TypeVarfrom sqlalchemy import and_, exists, literal, or_, select, updatefrom sqlalchemy.engine import Connection, Engine@@ -97,6 +98,7 @@ if TYPE_CHECKING:from modules.im import MessageContextlogger = logging.getLogger(__name__)+_T = TypeVar("_T")@dataclass@@ -4399,46 +4401,81 @@ class SessionTurnManager:}return receipt_result- async def _start_persisted_turn(+ def _read_start_owner(self,turn_id: str,- *,- context: Optional["MessageContext"] = None,- expected_start_attempt_id: str | None = None,- ) -> bool:- with self._sqlite_engine().begin() as conn:- reserve_write_lock(conn)+ expected_start_attempt_id: str | None,+ ) -> tuple[dict[str, Any], list[dict[str, Any]]] | None:+ """The starting Turn and its initial Deliveries; None when it is not this start's to make.++ A plain read, safe on any thread: it writes nothing, and the start's own+ write transaction re-validates every field it reads, under SQLite's+ writer, before the native dispatch.+ """++ with self._sqlite_engine().connect() as conn:turn = delivery_store.get_turn(conn, turn_id)if turn is None or turn["state"] != "starting":- return False+ return Noneif (expected_start_attempt_id is not Noneand str(turn.get("start_attempt_id") or "")!= expected_start_attempt_id):- return False- backend = str(turn.get("backend") or "").strip()- if backend in self._draining_backends:- self._deferred_restart_sessions.setdefault(backend, set()).add(- str(turn["session_id"])- )- return False- deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)- delivery = deliveries[0] if deliveries else None- if (- delivery is None- or any(row["state"] != "claimed" for row in deliveries)- or not turn.get("start_attempt_id")- or not turn.get("dispatch_sha256")- ):- logger.error("durable Turn has no exact start-attempt owner: %s", turn_id)- return False- attempt_id = str(turn["start_attempt_id"])- # The row stays ``starting`` until native acceptance, so the live- # projection is the launch fence for concurrent resume callers.- projected = self.in_flight.get(str(turn["session_id"]))- if projected is not None and not projected.task.done():- return projected.logical_turn_id == turn_id+ return None+ return turn, delivery_store.initial_deliveries_for_turn(conn, turn_id)++ async def _run_off_loop(self, operation: Callable[[], _T]) -> _T:+ from core.runtime_work import RuntimeWorkSupervisor++ supervisor = getattr(self.controller, "runtime_work_supervisor", None)+ if isinstance(supervisor, RuntimeWorkSupervisor):+ return await supervisor.run_sync(operation)+ return await asyncio.to_thread(operation)++ async def _start_persisted_turn(+ self,+ turn_id: str,+ *,+ context: Optional["MessageContext"] = None,+ expected_start_attempt_id: str | None = None,+ read_owner_off_loop: bool = False,+ ) -> bool:+ # The runtime-work lane's re-entry reads its owner off the loop: on a+ # slow state disk this read held the loop for 3 s (#2706). That Turn+ # was already ``starting`` with no live projection when the lane found+ # it, so the yield exposes nothing new. The other callers keep reading+ # on the loop: most start a Turn they have just committed, in the same+ # synchronous step, and a yield there would let other loop sections+ # see it ``starting`` without a projection.+ read = partial(self._read_start_owner, turn_id, expected_start_attempt_id)+ owner = await self._run_off_loop(read) if read_owner_off_loop else read()+ if owner is None:+ return False+ turn, deliveries = owner+ backend = str(turn.get("backend") or "").strip()+ if backend in self._draining_backends:+ self._deferred_restart_sessions.setdefault(backend, set()).add(+ str(turn["session_id"])+ )+ return False+ delivery = deliveries[0] if deliveries else None+ if (+ delivery is None+ or any(row["state"] != "claimed" for row in deliveries)+ or not turn.get("start_attempt_id")+ or not turn.get("dispatch_sha256")+ ):+ logger.error("durable Turn has no exact start-attempt owner: %s", turn_id)+ return False+ attempt_id = str(turn["start_attempt_id"])+ # The row stays ``starting`` until native acceptance, so the live+ # projection is the launch fence for concurrent resume callers. It is+ # read on the loop, after any off-loop read, and nothing below yields+ # before ``_run`` projects this Turn.+ projected = self.in_flight.get(str(turn["session_id"]))+ if projected is not None and not projected.task.done():+ return projected.logical_turn_id == turn_idtry:resolved = (self._delivery_context(str(turn["session_id"]))@@ -6476,6 +6513,7 @@ class SessionTurnManager:return await self._start_persisted_turn(str(turn["id"]),expected_start_attempt_id=str(turn.get("start_attempt_id") or ""),+ read_owner_off_loop=True,)if turn is not None and turn["state"] == "waiting":if predecessor is None:diff --git a/tests/test_runtime_recovery.py b/tests/test_runtime_recovery.pyindex d848a2887..5864649bb 100644--- a/tests/test_runtime_recovery.py+++ b/tests/test_runtime_recovery.py@@ -194,6 +194,7 @@ async def test_hfr_149_session_lane_recovers_only_current_exact_observation(manager._start_persisted_turn.assert_awaited_once_with("turn-current",expected_start_attempt_id="attempt-current",+ read_owner_off_loop=True,)engine.dispose()diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex e56fdbede..2730faba9 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -8766,3 +8766,49 @@ async def test_a_turn_end_after_its_terminal_write_takes_no_writer(managers) ->assert released["changed"] is False and drained is Falseassert writers == [], f"a Turn end took SQLite's writer {len(writers)} more time(s) to change nothing"+++def test_runtime_recovery_reads_a_starting_turns_owner_off_the_controller_loop(managers, monkeypatch) -> None:+ """#2706: the runtime-work lane's re-entry of a ``starting`` Turn reads its owner off the loop.++ On a slow state disk that read held the controller loop for 3 s, and every+ Session with it. The Turn still starts exactly as before.+ """++ first, restarted, engine, _engine_b, starts = managers+ admitted = asyncio.run(+ first.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="recover me"),+ context=_context(),+ )+ )+ turn_id = str(admitted.turn_id)+ with engine.connect() as conn:+ assert delivery_store.get_turn(conn, turn_id)["state"] == "starting"+ observations, _ = restarted.scan_runtime_delivery_recovery(limit=10, occupied=frozenset())+ observation = next(item for item in observations if item.turn_id == turn_id)++ reading = threading.Event()+ loop_answered = threading.Event()+ answered_during_read: list[bool] = []+ real_initial_deliveries = delivery_store.initial_deliveries_for_turn++ def slow_initial_deliveries(conn, requested_turn_id):+ if requested_turn_id == turn_id and not reading.is_set():+ reading.set()+ answered_during_read.append(loop_answered.wait(2))+ return real_initial_deliveries(conn, requested_turn_id)++ monkeypatch.setattr(delivery_store, "initial_deliveries_for_turn", slow_initial_deliveries)++ async def scenario() -> bool:+ recovery = asyncio.create_task(restarted.recover_runtime_delivery_observation(observation))+ while not reading.is_set():+ await asyncio.sleep(0.01)+ # The loop serves other work while the read waits on the disk.+ loop_answered.set()+ return await recovery++ assert asyncio.run(asyncio.wait_for(scenario(), 10))+ assert answered_during_read == [True]+ assert [started for started, _text in starts] == [turn_id, turn_id]