Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(turns): keep terminal writer contention off the controller loop (#2952)

Call White5e1f57ad7e62
diff --git a/core/controller.py b/core/controller.py
index 8bc9975be..6df70229a 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1978,9 +1978,9 @@ class Controller:
**({"citations": citations} if citations else {}),
**({"hosted": hosted} if hosted else {}),
)
- # The dispatcher's terminal commit already ran this write beside the Turn's
- # signal (#2714), which makes this call a no-op. It still covers a dispatcher
- # that did not reach that commit.
+ # The dispatcher's terminal commit already handed off this write beside
+ # the Turn's signal (#2714 / #2706), which makes this call a no-op even if
+ # its completion is pending. Still cover a dispatcher that skipped it.
manager = getattr(self, "session_turns", None)
complete = getattr(manager, "on_terminal_delivery_complete", None)
if callable(complete):
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index a7f4ba2c8..9cfc7f991 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -536,9 +536,10 @@ class ConsolidatedMessageDispatcher:
On every exit, including a cancellation in a surface, the processing
indicator is finished and the armed commit then runs with no await
inside it: the signal, the emit's post-signal steps, the runtime release
- and the Turn's evidence write. Neither the runner nor a cancellation can
- get between the signal and that write (#2714). An emit that never armed
- only releases the runtime, as before.
+ and the Turn's initial evidence-write attempt. On writer contention the
+ manager owns a pending completion before control yields; the runner joins
+ that fence before cleanup (#2706 B2). An emit that never armed only
+ releases the runtime, as before.
"""
commit = _TerminalCommit(output_semantics)
@@ -566,7 +567,7 @@ class ConsolidatedMessageDispatcher:
def _commit_terminal_turn(
self, context: MessageContext, commit: _TerminalCommit
) -> BaseException | None:
- """Run an armed commit synchronously; return the post-signal step's error."""
+ """Run the signal/release/write attempt synchronously; hold a post-signal error."""
if commit.signal is None:
self._release_runtime_turn(context, commit.output_semantics)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 59256c8f7..e96c5d13f 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -9693,7 +9693,8 @@ class ScheduledTaskService:
execution_ids: Sequence[str],
*,
settled_by: str,
- ) -> None:
+ retire_job: bool = True,
+ ) -> list[str]:
"""Settle runs whose turn ended without a terminal result, on the TURN lane.
``_execute_agent_run`` can only settle the runs it dispatched itself. An
@@ -9703,9 +9704,11 @@ class ScheduledTaskService:
i18n text as the drain lane — the only difference is who noticed.
A settled run's terminal callback is delivered by the drain, so mark it dirty
- rather than waiting up to a full tick.
+ rather than waiting up to a full tick. Executor callers pass ``retire_job=False``
+ and retire the returned definition ids on the loop after this store step lands.
"""
+ retired_jobs: list[str] = []
settled_any = False
error_text = self._t(
SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT])
@@ -9722,17 +9725,21 @@ class ScheduledTaskService:
if settled is None:
continue
settled_any = True
- self._project_terminal_definition_result(
+ retired = self._project_terminal_definition_result(
self.request_store.get_run(execution_id),
execution_id=execution_id,
expected_status=settled,
+ retire_job=retire_job,
)
+ if retired is not None:
+ retired_jobs.append(retired)
if settled_any:
self._wake_runtime_work(
RuntimeWorkLane.REQUESTS,
RuntimeWorkLane.RUN_CALLBACKS,
RuntimeWorkLane.FAILURE_NOTICES,
)
+ return retired_jobs
def settle_agent_runs_from_terminal_turn(
self,
@@ -9743,18 +9750,25 @@ class ScheduledTaskService:
settled_by: str | None,
evidence_kind: str | None,
evidence: Mapping[str, Any],
- ) -> None:
- """Settle late accepted Runs from their immutable Turn snapshot."""
+ retire_job: bool = True,
+ ) -> list[str]:
+ """Settle late accepted Runs from their immutable Turn snapshot.
+
+ With ``retire_job=False``, return one-shot ids for loop-owned job retirement.
+ Only the resultless branch is safe on a worker: output evidence also consults
+ the loop-owned Activity registry.
+ """
+ retired_jobs: list[str] = []
if settled_by in SETTLEMENTS_WITHOUT_RESULT:
normalized_settlement = str(settled_by)
store = self.request_store.sqlite_backend
if store is None:
- self.settle_agent_runs_without_result(
+ return self.settle_agent_runs_without_result(
execution_ids,
settled_by=normalized_settlement,
+ retire_job=retire_job,
)
- return
normalized_execution_ids = list(
dict.fromkeys(
execution_id
@@ -9807,34 +9821,37 @@ class ScheduledTaskService:
transitioned = True
run = result.get("run")
expected_status = str((run or {}).get("status") or terminal_status)
- self._project_terminal_definition_result(
+ retired = self._project_terminal_definition_result(
run,
execution_id=execution_id,
expected_status=expected_status,
+ retire_job=retire_job,
)
+ if retired is not None:
+ retired_jobs.append(retired)
if transitioned or repaired_ids:
self._wake_runtime_work(
RuntimeWorkLane.REQUESTS,
RuntimeWorkLane.RUN_CALLBACKS,
RuntimeWorkLane.FAILURE_NOTICES,
)
- return
+ return retired_jobs
if evidence.get("settles_run") is not True:
- return
+ return []
store = self.request_store.sqlite_backend
if store is None:
logger.warning(
"cannot settle late accepted Agent Runs for Turn=%s without SQLite",
turn_id,
)
- return
+ return []
terminal_status = {
"completed": "succeeded",
"failed": "failed",
"canceled": "canceled",
}.get(outcome)
if terminal_status is None:
- return
+ return []
result_text = str(evidence.get("result_text") or "")
terminal_error = evidence.get("terminal_error")
message_id = str(evidence.get("message_id") or "").strip() or None
@@ -9890,6 +9907,7 @@ class ScheduledTaskService:
RuntimeWorkLane.RUN_CALLBACKS,
RuntimeWorkLane.FAILURE_NOTICES,
)
+ return retired_jobs
def _retract_escalation_of_stopped_fire(self, execution_id: str) -> None:
"""Take back the Agent turn a fire queued, once the user stops that fire.
diff --git a/core/session_turns.py b/core/session_turns.py
index 70f09b2c7..3e2bb274a 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -653,6 +653,26 @@ class TurnSubmissionResult:
delivery_owner_transferred: bool = False
+@dataclass
+class _PendingDurableTerminal:
+ """One delivered outcome, retained while its non-waiting commit finishes."""
+
+ session_id: str
+ turn_id: str
+ outcome: str
+ settled_by: str | None
+ evidence_kind: str
+ evidence: dict[str, Any] | None
+ resume_successors: bool = True
+ task: asyncio.Task[dict[str, Any]] | None = None
+ result: dict[str, Any] | None = None
+ settle_runs: Callable[[], list[str]] | None = None
+ publish: Callable[[], None] | None = None
+ # Accepted receipts must survive a bounded join that returns before B lands.
+ # Key by the exact attempt, never merely the Delivery that may be reused.
+ accepted_steers: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)
+
+
@dataclass(frozen=True)
class _RuntimeStartOwner:
"""Proof that one exact Session runtime boundary owns this transaction."""
@@ -710,6 +730,10 @@ class SessionTurnManager:
# period.
RESTART_RECOVERY_RETRY_DELAYS: tuple[float, ...] = (5.0, 30.0, 120.0)
RESTART_RECOVERY_RETRY_PERIOD: float = 600.0
+ # Match one SQLite busy attempt, without making the controller loop wait.
+ # A failed attempt retains its evidence for the runner / recovery's retry.
+ TERMINAL_WRITE_RETRY_SECONDS: float = 5.0
+ TERMINAL_WRITE_RETRY_DELAY: float = 0.05
def __init__(
self,
@@ -721,6 +745,7 @@ class SessionTurnManager:
self._build_context = build_context
self._engine: Engine | None = None
self.in_flight: dict[str, Turn] = {}
+ self._pending_terminals: dict[str, _PendingDurableTerminal] = {}
self._draining_backends: set[str] = set()
self._deferred_restart_sessions: dict[str, set[str]] = {}
self._queue_recovery_locks: dict[str, asyncio.Lock] = {}
@@ -931,12 +956,14 @@ class SessionTurnManager:
self,
run_ids: set[str] | list[str],
settled_by: Optional[str],
- ) -> None:
+ *,
+ retire_job: bool = True,
+ ) -> list[str]:
if settled_by not in SETTLEMENTS_WITHOUT_RESULT or not run_ids:
- return
+ return []
normalized = sorted({str(run_id) for run_id in run_ids if str(run_id).strip()})
if not normalized:
- return
+ return []
service = (
getattr(self.controller, "scheduled_task_service", None)
if self.controller
@@ -945,9 +972,10 @@ class SessionTurnManager:
settle = getattr(service, "settle_agent_runs_without_result", None)
if not callable(settle):
logger.debug("turn settlement: no harness settlement writer available")
- return
+ return []
try:
- settle(normalized, settled_by=settled_by)
+ options = {} if retire_job else {"retire_job": False}
+ return settle(normalized, settled_by=settled_by, **options) or []
except Exception:
logger.warning(
"turn settlement: failed to settle runs %s as %s",
@@ -955,12 +983,15 @@ class SessionTurnManager:
settled_by,
exc_info=True,
)
+ return []
def _settle_agent_run_ids_from_terminal_turn(
self,
run_ids: set[str] | list[str],
turn: dict[str, Any],
- ) -> None:
+ *,
+ retire_job: bool = True,
+ ) -> list[str]:
turn_id = str(turn.get("id") or "").strip()
durable_ids = self.accepted_agent_run_ids_for_turn(turn_id) if turn_id else []
normalized = sorted(
@@ -971,7 +1002,7 @@ class SessionTurnManager:
}
)
if not normalized:
- return
+ return []
service = (
getattr(self.controller, "scheduled_task_service", None)
if self.controller
@@ -979,8 +1010,7 @@ class SessionTurnManager:
)
settle = getattr(service, "settle_agent_runs_from_terminal_turn", None)
if not callable(settle):
- self._settle_agent_run_ids(normalized, turn.get("settled_by"))
- return
+ return self._settle_agent_run_ids(normalized, turn.get("settled_by"), retire_job=retire_job)
try:
evidence = json.loads(str(turn.get("terminal_evidence_json") or "{}"))
if not isinstance(evidence, dict):
@@ -988,14 +1018,16 @@ class SessionTurnManager:
except (TypeError, ValueError, json.JSONDecodeError):
evidence = {}
try:
- settle(
+ options = {} if retire_job else {"retire_job": False}
+ return settle(
normalized,
turn_id=str(turn["id"]),
outcome=str(turn.get("terminal_outcome") or "completed"),
settled_by=str(turn.get("settled_by") or "") or None,
evidence_kind=str(turn.get("terminal_evidence_kind") or "") or None,
evidence=evidence,
- )
+ **options,
+ ) or []
except Exception:
logger.warning(
"turn settlement: failed to settle late accepted runs %s from Turn=%s",
@@ -1003,6 +1035,7 @@ class SessionTurnManager:
turn.get("id"),
exc_info=True,
)
+ return []
def _settle_turn_owned_agent_runs(self, context: "MessageContext", settled_by: Optional[str]) -> None:
"""Settle the ``agent_runs`` rows this turn owned when no result arrived.
@@ -2933,6 +2966,7 @@ class SessionTurnManager:
raise ValueError("Session delivery requires a Session id")
if request.priority not in {"p0", "p1", "p3"}:
raise ValueError(f"unsupported delivery priority: {request.priority}")
+ await self._join_session_terminal(request.session_id)
content_present = (
request.has_content
if request.has_content is not None
@@ -3506,6 +3540,25 @@ class SessionTurnManager:
terminal_target: dict[str, Any] | None = None
session_id = ""
try:
+ with self._sqlite_engine().connect() as conn:
+ observed = delivery_store.get_delivery(conn, delivery_id)
+ pending = self._pending_terminals.get(str((observed or {}).get("current_target_turn_id") or ""))
+ if pending is not None and pending.result is None and outcome_value == SteerOutcome.ACCEPTED.value:
+ from core.runtime_work import land_step, rearm_caught_cancellation
+
+ attempt_id = str((observed or {}).get("current_attempt_id") or "")
+ if attempt_id and (expected_attempt_id is None or expected_attempt_id == attempt_id):
+ # Retain proof before yielding. If this join expires, B writes
+ # the accepted recovery fence in its eventual transaction;
+ # recovery need not ask an ended native Turn to remember it.
+ pending.accepted_steers.setdefault((delivery_id, attempt_id), body)
+ step, cancelled = await land_step(self._ensure_terminal_completion(pending))
+ step.result()
+ if cancelled:
+ # The receipt used to commit before this caller's next await.
+ rearm_caught_cancellation()
+ if self._pending_terminals.get(pending.turn_id) is pending:
+ return DeliveryResult(delivery_id, None, "reconciling_steer", reason="terminal_commit_pending")
with self._sqlite_engine().begin() as conn:
reserve_write_lock(conn)
delivery = delivery_store.get_delivery(conn, delivery_id)
@@ -4460,6 +4513,8 @@ class SessionTurnManager:
if owner is None:
return False
turn, deliveries = owner
+ if self._defer_for_pending_terminal(str(turn["session_id"])):
+ return False
backend = str(turn.get("backend") or "").strip()
if backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(
@@ -4946,6 +5001,8 @@ class SessionTurnManager:
expected_head_id: str | None = None,
expected_head_version: int | None = None,
) -> bool:
+ if self._defer_for_pending_terminal(session_id):
+ return False
turn_id: str | None = None
with self._sqlite_engine().connect() as conn:
# Most drains find nothing to claim -- every Turn end asks. Those answer
@@ -4996,6 +5053,112 @@ class SessionTurnManager:
evidence=evidence,
)
+ def _pending_terminal_for_session(self, session_id: str) -> _PendingDurableTerminal | None:
+ return next(
+ (pending for pending in self._pending_terminals.values() if pending.session_id == session_id),
+ None,
+ )
+
+ def _defer_for_pending_terminal(self, session_id: str) -> bool:
+ pending = self._pending_terminal_for_session(session_id)
+ if pending is None:
+ return False
+ # A failed post-commit store step retains its result and fence. Recovery
+ # must re-drive that owner, not permanently refuse a claimed successor.
+ self._ensure_terminal_completion(pending)
+ return True
+
+ def _ensure_terminal_completion(self, pending: _PendingDurableTerminal) -> asyncio.Task[dict[str, Any]]:
+ if pending.task is None or pending.task.done():
+ pending.task = asyncio.create_task(
+ self._complete_pending_terminal(pending),
+ name=f"durable-terminal:{pending.turn_id}",
+ )
+ return pending.task
+
+ async def _join_session_terminal(self, session_id: str) -> None:
+ pending = self._pending_terminal_for_session(session_id)
+ if pending is None:
+ return
+ # Admission is cancellable; cancellation must not cancel the delivered
+ # outcome it was waiting for. Never steer into the released native Turn.
+ await asyncio.shield(self._ensure_terminal_completion(pending))
+ if self._pending_terminals.get(pending.turn_id) is pending:
+ raise RuntimeError(f"durable terminal completion is unresolved: {pending.turn_id}")
+
+ async def _join_terminal_cleanup(self, turn_id: str | None) -> dict[str, Any]:
+ pending = self._pending_terminals.get(str(turn_id or ""))
+ if pending is None:
+ return {}
+ from core.handlers.model_hub.async_owner import await_owned_task
+
+ return await await_owned_task(self._ensure_terminal_completion(pending))
+
+ def _resume_delivered_terminal(self, session_id: str, turn_id: str, result: dict[str, Any]) -> None:
+ current = self.in_flight.get(session_id)
+ should_resume = bool(result.get("successor_turn_id")) or not result.get("defer_queue_resume")
+ if (
+ result.get("changed")
+ and should_resume
+ and (current is None or current.logical_turn_id != turn_id)
+ ):
+ asyncio.create_task(
+ self._resume_after_native_terminal(session_id, turn_id),
+ name=f"durable-result-resume:{session_id}",
+ )
+
+ async def _complete_pending_terminal(self, pending: _PendingDurableTerminal) -> dict[str, Any]:
+ """Retry only contention, with no boundary or transaction across an await.
+
+ The latch outlives a failed attempt. A runner, shutdown or recovery that
+ subsequently terminalizes this Turn must still use the delivered evidence.
+ """
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + self.TERMINAL_WRITE_RETRY_SECONDS
+ try:
+ while self._pending_terminals.get(pending.turn_id) is pending:
+ if pending.result is not None:
+ if pending.settle_runs is not None:
+ from core.runtime_work import land_step
+
+ step, _cancelled = await land_step(self._run_off_loop(pending.settle_runs))
+ retired_jobs = step.result() or []
+ pending.settle_runs = None
+ service = getattr(self.controller, "scheduled_task_service", None)
+ for task_id in retired_jobs:
+ service._retire_one_shot_job(task_id)
+ if pending.publish is not None:
+ pending.publish()
+ pending.publish = None
+ self._pending_terminals.pop(pending.turn_id, None)
+ result = pending.result
+ else:
+ result = self._terminalize_durable_turn(
+ pending.turn_id, pending.outcome,
+ settled_by=pending.settled_by,
+ evidence_kind=pending.evidence_kind,
+ evidence=pending.evidence,
+ resume_successors=pending.resume_successors,
+ )
+ if result.get("contended"):
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ logger.error("durable terminal writer remains busy for Turn=%s", pending.turn_id)
+ return {"defer_queue_resume": True}
+ await asyncio.sleep(min(self.TERMINAL_WRITE_RETRY_DELAY, remaining))
+ continue
+ if result.get("completion_pending"):
+ continue
+ if pending.resume_successors:
+ self._resume_delivered_terminal(pending.session_id, pending.turn_id, result)
+ return result
+ # Another owner already made the row terminal, or this attempt
+ # could not prove start acceptance. Do not invent a second resume.
+ return pending.result or {"changed": False, "defer_queue_resume": False}
+ except Exception:
+ logger.exception("durable terminal completion deferred for Turn=%s", pending.turn_id)
+ return {"defer_queue_resume": True}
+
def _terminalize_durable_turn(
self,
turn_id: str,
@@ -5018,6 +5181,20 @@ class SessionTurnManager:
"delivery_id": None,
"defer_queue_resume": False,
}
+ pending = self._pending_terminals.get(turn_id)
+ if pending is not None:
+ # Competing terminal writers inherit the delivered evidence, but
+ # retain their own stricter shutdown/cancellation resume decision.
+ pending.resume_successors = pending.resume_successors and resume_successors
+ if pending.result is not None:
+ self._ensure_terminal_completion(pending)
+ return {"changed": False, "defer_queue_resume": True, "completion_pending": True}
+ outcome, settled_by = pending.outcome, pending.settled_by
+ evidence_kind, evidence = pending.evidence_kind, pending.evidence
+ expected_start_attempt_id = None
+ replay_unknown_start = abandon_unaccepted_start = False
+ retire_unwritten_delivery_ids = None
+ resume_successors = pending.resume_successors
result: dict[str, Any]
materialized_id: str | None = None
terminal_run_ids: list[str] = []
@@ -5033,7 +5210,12 @@ class SessionTurnManager:
linked_activation_deferred = False
with self._sqlite_engine().connect() as conn:
observed_turn = delivery_store.get_turn(conn, turn_id)
- if observed_turn is None or observed_turn["state"] == "terminal":
+ if observed_turn is None or (
+ observed_turn["state"] == "terminal" and not (pending is not None and pending.accepted_steers)
+ ):
+ if pending is not None:
+ pending.result = {"changed": False, "defer_queue_resume": False}
+ self._pending_terminals.pop(turn_id, None)
# Terminal is final, and a missing Turn stays missing: the answer the
# recheck under the writer would give, without the boundary or the writer.
# A Turn end reaches here again after its terminal write (#2706).
@@ -5045,8 +5227,33 @@ class SessionTurnManager:
}
owner_session_id = str((observed_turn or {}).get("session_id") or "")
owner_backend = str((observed_turn or {}).get("backend") or "")
+ if pending is None and evidence_kind in {"terminal_result", "agent_initiated_terminal"}:
+ pending = _PendingDurableTerminal(
+ session_id=owner_session_id, turn_id=turn_id, outcome=outcome,
+ settled_by=settled_by, evidence_kind=evidence_kind,
+ evidence=dict(evidence) if evidence is not None else None,
+ resume_successors=resume_successors,
+ )
+ self._pending_terminals[turn_id] = pending
with self._runtime_start_owner(owner_session_id, owner_backend) as start_owner, self._sqlite_engine().begin() as conn:
- reserve_write_lock(conn)
+ if pending is not None:
+ if not _try_reserve_write_lock(conn):
+ self._ensure_terminal_completion(pending)
+ return {"changed": False, "contended": True, "defer_queue_resume": True}
+ else:
+ reserve_write_lock(conn)
+ if pending is not None:
+ for (delivery_id, attempt_id), receipt in pending.accepted_steers.items():
+ delivery = delivery_store.get_delivery(conn, delivery_id)
+ if (
+ delivery is not None
+ and delivery.get("current_attempt_id") == attempt_id
+ and delivery.get("current_target_turn_id") == turn_id
+ ):
+ delivery_store.mark_attempt_receipt_batch(
+ conn, leader_delivery_id=delivery_id,
+ outcome="accepted", receipt=receipt,
+ )
turn = delivery_store.get_turn(conn, turn_id)
if (
turn is None
@@ -5093,6 +5300,8 @@ class SessionTurnManager:
and not unknown_start_reconciliation
and not abandoned_start
):
+ if pending is not None:
+ self._pending_terminals.pop(turn_id, None)
return {
"changed": False,
"successor_turn_id": None,
@@ -5480,45 +5689,61 @@ class SessionTurnManager:
.values(agent_status=projected_status)
)
status_changed = bool(projected.rowcount)
- if result.get("changed"):
- run_settled_by = (
- SETTLED_BY_NO_TERMINAL_RESULT
- if result.get("unknown_start_exhausted")
- else settled_by
- )
- if (
- terminal_turn_snapshot is not None
- and run_settled_by in SETTLEMENTS_WITHOUT_RESULT
- ):
- terminal_turn_snapshot = {
- **terminal_turn_snapshot,
- "settled_by": run_settled_by,
- }
- self._settle_agent_run_ids_from_terminal_turn(
+ run_settled_by = (
+ SETTLED_BY_NO_TERMINAL_RESULT
+ if result.get("unknown_start_exhausted")
+ else settled_by
+ )
+
+ def settle_runs(*, retire_job: bool = True) -> list[str]:
+ if not result.get("changed"):
+ return []
+ if terminal_turn_snapshot is not None and run_settled_by in SETTLEMENTS_WITHOUT_RESULT:
+ return self._settle_agent_run_ids_from_terminal_turn(
terminal_run_ids,
- terminal_turn_snapshot,
- )
- else:
- self._settle_agent_run_ids(terminal_run_ids, run_settled_by)
- if materialized_id:
- self._publish_materialized_delivery(materialized_id)
- if result.get("changed"):
- if requeued_input:
- self._publish_queue_update(session_id)
- self._publish_terminal_inbox_update(session_id)
- waiting = self._restart_recovery_wakes.get(session_id)
- if waiting is not None:
- # A cut Turn open for a restart retry has no runtime for a Stop to reach: its
- # retry runs now, so T2 ends the command of a canceled Turn as live.
- with suppress(RuntimeError): # its loop has closed
- waiting[0].call_soon_threadsafe(waiting[1].set)
- if status_changed and projected_status is not None:
- from core.inbox_events import bus
+ {**terminal_turn_snapshot, "settled_by": run_settled_by},
+ retire_job=retire_job,
+ )
+ return self._settle_agent_run_ids(terminal_run_ids, run_settled_by, retire_job=retire_job)
+
+ def publish() -> None:
+ if materialized_id:
+ self._publish_materialized_delivery(materialized_id)
+ if result.get("changed"):
+ if requeued_input:
+ self._publish_queue_update(owner_session_id)
+ self._publish_terminal_inbox_update(owner_session_id)
+ waiting = self._restart_recovery_wakes.get(owner_session_id)
+ if waiting is not None:
+ with suppress(RuntimeError): # its loop has closed
+ waiting[0].call_soon_threadsafe(waiting[1].set)
+ if status_changed and projected_status is not None:
+ from core.inbox_events import bus
- bus.publish(
- "session.status",
- {"session_id": session_id, "agent_status": projected_status},
- )
+ bus.publish(
+ "session.status",
+ {"session_id": owner_session_id, "agent_status": projected_status},
+ )
+
+ if pending is not None:
+ pending.result = result
+ if result.get("changed") and terminal_run_ids and run_settled_by in SETTLEMENTS_WITHOUT_RESULT:
+ # This tail reserves another writer. Keep the completion fence
+ # until it lands, but never hold the activation boundary on its worker.
+ pending.settle_runs = lambda: settle_runs(retire_job=False)
+ pending.publish = publish
+ self._ensure_terminal_completion(pending)
+ return {"changed": False, "defer_queue_resume": True, "completion_pending": True}
+ settle_runs()
+ publish()
+ if pending is not None:
+ if pending.task is not None and pending.task is not asyncio.current_task():
+ # A synchronous competitor may land B, but does not take its
+ # resume ownership. Some such callers return only a bool and
+ # have no resume tail at all. The pending task owns that tail.
+ self._ensure_terminal_completion(pending)
+ return {"changed": False, "defer_queue_resume": True, "completion_pending": True}
+ self._pending_terminals.pop(turn_id, None)
return result
def reconcile_start_attempt_not_written(
@@ -7909,6 +8134,8 @@ class SessionTurnManager:
observation: RuntimeDeliveryObservation | None = None,
) -> str | None:
"""Start only the exact replacement linked from a settled control Turn."""
+ if self._defer_for_pending_terminal(session_id):
+ return None
start_attempt_id = ""
with self._sqlite_engine().connect() as conn:
observed_terminal = delivery_store.get_turn(conn, terminal_turn_id)
@@ -8314,6 +8541,7 @@ class SessionTurnManager:
logger.exception("internal async dispatch failed for session=%s", session_id)
finally:
if isinstance(session_id, str):
+ await self._join_terminal_cleanup(logical_turn_id)
durable_terminal_result: dict[str, Any] = {}
prewrite_refused = prewrite_refused or (
settled_by == SETTLED_BY_REFUSED_CONCURRENT_TURN
@@ -8349,8 +8577,8 @@ class SessionTurnManager:
)
reconciled = False
- def reconcile_release() -> dict[str, Any]:
- return self._reconcile_durable_runner_release(
+ async def reconcile_release() -> dict[str, Any]:
+ result = self._reconcile_durable_runner_release(
logical_turn_id,
cancelled=cancelled,
failed=failed,
@@ -8362,12 +8590,15 @@ class SessionTurnManager:
failure_evidence=prewrite_failure_evidence(context),
terminal_commit=terminal_commit,
)
+ if result.get("contended") or result.get("completion_pending"):
+ return await self._join_terminal_cleanup(logical_turn_id)
+ return result
if terminal_commit is not None and logical_turn_id and durable_turn_registered:
# The emit's own Turn write failed (#2714); this write stands in
# for it, so it lands where that one would have: before Hub
# finalization, which relies on the row being terminal (#2735).
- durable_terminal_result = reconcile_release()
+ durable_terminal_result = await reconcile_release()
# A write that failed again carries no ``changed``; it gets the
# attempt after finalization that it would have had on its own.
reconciled = "changed" in durable_terminal_result
@@ -8379,14 +8610,14 @@ class SessionTurnManager:
await await_owned_task(asyncio.ensure_future(completion))
except Exception:
logger.warning("Model Hub turn finalization failed", exc_info=True)
- # Durable output may already have marked the old row terminal.
- # _start_persisted_turn still fences its successor on this live
- # runner, so release the projection only after Hub finalization.
+ # Keep the live runner through both Hub and any fallback
+ # completion. Otherwise the retry task can also own resume
+ # when earlier attempts expired before Hub finalized.
+ if not reconciled and logical_turn_id and durable_turn_registered:
+ durable_terminal_result = await reconcile_release()
released_projection = turn is not None and self.in_flight.get(session_id) is turn
if released_projection:
self.in_flight.pop(session_id, None)
- if not reconciled and logical_turn_id and durable_turn_registered:
- durable_terminal_result = reconcile_release()
if released_projection:
# After the terminal write, so its session.status precedes
# turn.end as it does when the emit's own write lands (#2735).
@@ -8428,7 +8659,7 @@ class SessionTurnManager:
durable_turn_registered
and durable_terminal_result.get("defer_queue_resume")
)
- should_flush = not defer_durable_resume
+ should_flush = not (defer_durable_resume or cancel_defers_queue_resume)
backend = self._context_backend(context)
if should_flush and backend in self._draining_backends:
self._deferred_restart_sessions.setdefault(backend, set()).add(session_id)
@@ -8439,6 +8670,7 @@ class SessionTurnManager:
await self.flush_queue(session_id)
elif (
durable_turn_registered
+ and not cancel_defers_queue_resume
and settled_by != SETTLED_BY_RESTARTED
):
# Stop may persist the old Turn's terminal snapshot before
@@ -8907,6 +9139,17 @@ class SessionTurnManager:
)
return owners
+ pending_tasks = []
+ for pending in list(self._pending_terminals.values()):
+ pending.resume_successors = False
+ projected = self.in_flight.get(pending.session_id)
+ if projected is not None and projected.logical_turn_id == pending.turn_id:
+ projected.cancel_defers_queue_resume = True
+ pending_tasks.append(self._ensure_terminal_completion(pending))
+ if pending_tasks:
+ # Each write retry is bounded; do not cancel its evidence owner if
+ # shutdown's flush window expires. The runners below still join it.
+ await asyncio.wait(pending_tasks, timeout=self.TERMINAL_WRITE_RETRY_SECONDS)
owners = live_owners()
done_tasks: list[asyncio.Task] = []
for owner in owners.values():
@@ -8983,7 +9226,10 @@ class SessionTurnManager:
"""
if not backend or not base_session_ids:
return 0
-
+ delivered_turns = {
+ pending.turn_id for pending in self._pending_terminals.values()
+ if pending.session_id in base_session_ids
+ }
released_sessions: set[str] = set()
legacy_projection_sessions: set[str] = set()
tasks_to_settle: list[asyncio.Task] = []
@@ -9002,7 +9248,12 @@ class SessionTurnManager:
backend,
base_session_ids,
)
- for session_id, turn in list(self.in_flight.items()):
+ projected_owners = list(self.in_flight.items())
+ for turn_id in delivered_turns:
+ await self._join_terminal_cleanup(turn_id)
+ for session_id, turn in projected_owners:
+ if self.in_flight.get(session_id) is not turn:
+ continue
if session_id not in base_session_ids:
continue
spec = getattr(turn.context, "platform_specific", None) or {}
@@ -9020,7 +9271,10 @@ class SessionTurnManager:
# it off the Turn when it pops it. An outcome already decided, by a
# Stop in flight or a result already delivered, keeps its own cause
# and needs no refresh notice.
- refresh_owns_outcome = not self._turn_outcome_decided(turn)
+ refresh_owns_outcome = (
+ turn.logical_turn_id not in delivered_turns
+ and not self._turn_outcome_decided(turn)
+ )
if refresh_owns_outcome:
turn.cancel_settled_by = settled_by
turn.cancel_defers_queue_resume = True
@@ -9101,7 +9355,12 @@ class SessionTurnManager:
released_restored.add(str(owner["session_id"]))
# Starting or active, the refresh retired this conversation's
# input. The user's own stop needs no explanation.
- if not owned_by_run and self.controller is not None and settled_by != SETTLED_BY_STOPPED:
+ if (
+ not owned_by_run
+ and self.controller is not None
+ and settled_by != SETTLED_BY_STOPPED
+ and owner_id not in delivered_turns
+ ):
self._notify_backend_refresh(
str(owner["session_id"]), origin_message_id, owner_id, backend, settled_by=settled_by
)
@@ -9205,6 +9464,7 @@ class SessionTurnManager:
A Run whose input may have reached the live Turn stops that whole Turn,
exactly like Session Stop; a Run still outside it is canceled alone.
"""
+ await self._join_session_terminal(session_id)
normalized_agent_run_id = (
str(agent_run_id).strip() if agent_run_id is not None else None
)
@@ -9572,19 +9832,7 @@ class SessionTurnManager:
logical_turn_id,
)
return
- current = self.in_flight.get(session_id)
- should_resume = bool(terminal.get("successor_turn_id")) or not bool(
- terminal.get("defer_queue_resume")
- )
- if (
- terminal.get("changed")
- and should_resume
- and (current is None or current.logical_turn_id != logical_turn_id)
- ):
- asyncio.create_task(
- self._resume_after_native_terminal(session_id, logical_turn_id),
- name=f"durable-result-resume:{session_id}",
- )
+ self._resume_delivered_terminal(session_id, logical_turn_id, terminal)
def on_terminal_result(
self,
@@ -9869,6 +10117,7 @@ class SessionTurnManager:
cancelled = True
raise
finally:
+ await self._join_terminal_cleanup(turn_token)
sink = self.get_turn_sink(session_key)
settled_by = str((sink or {}).get("settled_by") or "")
current = self.in_flight.get(session_id)
@@ -9896,8 +10145,6 @@ class SessionTurnManager:
cancel_defers_queue_resume
or effective_settled_by == SETTLED_BY_RESTARTED
)
- if turn is not None:
- self.in_flight.pop(session_id, None)
if durable_turn_registered:
try:
durable_terminal_result = self._terminalize_durable_turn(
@@ -9925,6 +10172,8 @@ class SessionTurnManager:
),
resume_successors=not queue_resume_deferred,
)
+ if durable_terminal_result.get("contended") or durable_terminal_result.get("completion_pending"):
+ durable_terminal_result = await self._join_terminal_cleanup(turn_token)
if queue_resume_deferred:
durable_terminal_result["defer_queue_resume"] = True
except Exception:
@@ -9935,6 +10184,8 @@ class SessionTurnManager:
)
durable_terminal_result = {"defer_queue_resume": True}
if turn is not None:
+ if self.in_flight.get(session_id) is turn:
+ self.in_flight.pop(session_id, None)
# After the terminal write, so its session.status precedes
# turn.end (#2735).
bus.publish(
@@ -9955,6 +10206,7 @@ class SessionTurnManager:
logger.debug("agent-initiated turn: queue resume failed", exc_info=True)
elif (
durable_turn_registered
+ and not cancel_defers_queue_resume
and effective_settled_by != SETTLED_BY_RESTARTED
):
await self._resume_linked_control_successor(
diff --git a/docs/plans/controller-loop-sqlite-writers.md b/docs/plans/controller-loop-sqlite-writers.md
index 5f2c3f4ab..93a79825b 100644
--- a/docs/plans/controller-loop-sqlite-writers.md
+++ b/docs/plans/controller-loop-sqlite-writers.md
@@ -1,6 +1,8 @@
# SQLite writers on the controller loop: terminal, record and recovery paths (#2706)
-Status: design note, proposed. No code yet.
+Status: paths A, C and B step 1 shipped. B step 2 is implemented by the
+[terminal-completion synchronization design](terminal-completion-synchronization.md):
+keep its atomic transaction on the loop, but never wait for SQLite's writer there.
## Background
@@ -182,5 +184,5 @@ Each move needs the check this note applies to A. Does a loop section rely on th
- [x] C: bound the recovery reads (start from live Runs and pending legacy notices, with a pinned plan; read-only transactions; mismatch-only status projection).
- [x] A: record the Turn's Run terminal through the runtime-work door with `land_step`, keeping the cancellation point it had on the loop; make the blocking-Activity check on the loop and re-read the durable Activity rows inside the write's transaction; build the store off the loop. The IM network tail is #2714.
-- [ ] B, step 1: skip the writer for redundant terminalization, the post-terminal read and an empty drain.
-- [ ] B, step 2: a design note for B's remaining write that keeps terminalization and successor selection atomic with respect to admission (orderings 1–5).
+- [x] B, step 1: skip the writer for redundant terminalization, the post-terminal read and an empty drain (#2718).
+- [x] B, step 2: [non-waiting terminal completion](terminal-completion-synchronization.md), with exact-Turn cleanup/admission fences and the original atomic successor selection (orderings 1–5).
diff --git a/docs/plans/terminal-completion-synchronization.md b/docs/plans/terminal-completion-synchronization.md
new file mode 100644
index 000000000..5f2450409
--- /dev/null
+++ b/docs/plans/terminal-completion-synchronization.md
@@ -0,0 +1,201 @@
+# Path B step 2: non-waiting terminal completion (#2706)
+
+Status: implemented in this change. The transaction stays on the controller loop;
+only waiting for its writer becomes asynchronous. No persisted shape changes.
+
+## Change contract
+
+Remove SQLite's writer wait from the evidence-carrying terminal path while keeping:
+
+1. the delivered terminal evidence ahead of a runner/native/recovery fallback;
+2. one atomic predecessor terminalization and linked P0 / start replay / FIFO selection;
+3. exactly one post-terminal resume;
+4. runtime-generation admission and Model Hub finalization fences;
+5. terminal inbox / status publication before the runner's `turn.end`;
+6. first-writer-wins Run settlement and existing recovery;
+7. a responsive controller loop under writer contention;
+8. Stop, backend refresh, shutdown and admission priorities.
+
+Message persistence (#2725), other writer sites, provider behavior and deployment
+are not part of this change. Paths A, C and B step 1 already shipped.
+
+## Concrete ordering
+
+Suppose the native result has been delivered, a linked P0 replacement is waiting,
+and another process holds SQLite's writer. The dispatcher still signals and releases
+the native Turn, records its delivered-evidence marker, and attempts B without
+suspending. The attempt now returns immediately on contention. Before control can
+yield, the manager owns one pending completion keyed by the exact logical Turn.
+
+The runner may wake, but it joins that completion before Hub finalization, removing
+`in_flight`, `turn.end`, or resuming the queue. A new P1 or Stop also joins it before
+examining the active owner: the old durable row still says `active`, but its native
+Turn has ended, so steering or stopping that native would be wrong.
+
+Once the writer is available, one synchronous transaction commits the evidence,
+settles pending-steer dispositions, selects the linked P0 before replay/FIFO, and
+updates the projection. No admission can see an ownerless gap. Terminal events
+are published before the pending completion releases the runner. The runner then
+finishes Hub, releases its projection and resumes the selected successor once.
+
+## Synchronization design
+
+### Keep both existing transaction boundaries
+
+`_terminalize_durable_turn` retains its entire SQLite transaction and its
+`_runtime_start_owner` / `hold_if_current` section. Delivered terminal attempts use
+the existing `_try_reserve_write_lock`, which temporarily sets a zero busy timeout.
+On contention, both contexts exit before any await. A retry resolves and acquires
+the runtime identity afresh. No activation RLock is held across an await or on a
+worker doing I/O.
+
+This fixes the measured `reserve_write_lock` wait, not all possible slow-disk cost.
+The transaction's bounded work remains on the loop. A full off-loop transaction
+would require a different generation-admission contract: `commit_then_confirm`
+cannot undo a linked P0 activation, FIFO claim or consumed replay budget. Splitting
+the terminal CAS from successor selection would instead need a durable admission
+fence. Neither mechanism is necessary for the measured writer wait.
+
+### One exact-Turn completion owner
+
+`_PendingDurableTerminal` retains the outcome, settlement, evidence and the strictest
+resume decision. The manager retains the retry Task strongly. The uncontended
+ordinary-result path still finishes synchronously and removes its temporary record.
+The pending registry is controller-local; all runtime terminal callbacks already
+reach this controller-owned manager. SQLite, not this registry, still serializes
+admissions from other connections.
+
+A competing terminalizer uses the pending evidence at the existing chokepoint,
+not its own `runner_release`, absent-start, refresh or shutdown evidence. Its own
+`resume_successors=False` can restrict resume; it cannot turn an earlier restriction
+back on. Negative start/replay flags cannot reinterpret an already delivered outcome.
+
+If that competitor lands the write, the pending Task still owns completion and
+resume. The competitor receives `completion_pending`, not permission to run a
+second resume. This matters for synchronous boolean-returning callers that have
+no resume tail of their own. If a live runner/agent-initiated holder still owns the
+Turn, the completion Task does not resume: the runner/holder is the complementary
+owner. The holder now keeps `in_flight` until after the terminal commit, like the
+ordinary runner. The ordinary runner also keeps its projection through a fallback
+write after Hub finalization, so an expired early retry cannot give both the runner
+and completion Task the resume decision.
+
+The existing sink-to-dispatch-context `TERMINAL_COMMIT_KEY` handoff remains. It
+covers a B attempt that fails before creating the pending record, and cancellation
+where dispatch returns no outcome. It is not replaced by the pre-delivery latch,
+which does not prove delivery reached the terminal block.
+
+### Admissions, late receipts and native starts
+
+- `deliver` and `cancel` await the Session's pending completion before observing
+ ownership. Their wait is cancellable without canceling the completion owner.
+- A late accepted steer receipt joins its exact target Turn's pending write before
+ materializing acceptance. Otherwise it could miss the terminal snapshot and leave
+ its Run without the already recorded result. Before yielding, the pending owner
+ latches the receipt by exact Delivery/attempt. If the join expires, B's eventual
+ transaction also stores that accepted recovery fence. A fresh manager can then
+ materialize acceptance and settle from the snapshot without asking the ended
+ backend. Definitive acceptance can upgrade an earlier UNKNOWN fence, never the
+ reverse. Once the terminal snapshot is committed, the receipt needs no further
+ wait for B's resultless tail. Negative/UNKNOWN receipts keep their existing path.
+ A caught cancellation is rearmed after the join.
+- Queue drain, linked-control resume and persisted native start do not enter while
+ the Session has pending completion work. In particular, a committed successor
+ cannot start while the post-commit Run settlement is still pending. These gates
+ re-drive a finished/deferred completion Task before refusing the start, so a
+ transient executor/read failure does not strand an already claimed successor.
+- Terminal/no-op prechecks from B step 1 remain unchanged when no completion is pending.
+
+### Resultless Run settlement and publication
+
+B's resultless settlement tail is another SQLite writer, after the main transaction.
+For a delivered resultless outcome with accepted Runs, the pending owner sends that
+tail through `_run_off_loop` (the runtime-work door, with the existing test fallback).
+`land_step` keeps the store step owned through cancellation. The activation boundary
+has already been released. The resultless settlement branch does not take the
+Activity registry lock; the ordinary positive-result/late-Activity behavior is not
+moved here. The worker requests `retire_job=False` and returns any one-shot
+scheduler ids; the completion owner retires those jobs on the loop, before events
+or fence release. Scheduler maps and APScheduler job mutation never move to the worker.
+
+Only after that step lands does the owner publish inbox/status events, clear the
+pending fence and permit resume. Existing guarded settlement methods continue to
+own first-writer-wins and recovery if a store operation itself fails. The immutable
+Turn snapshot and the first committed successor decision are retained across this
+tail; retrying it never replaces the committed result with a terminal no-op.
+
+### Failure, refresh and shutdown
+
+One retry Task has a five-second writer-attempt budget, matching the configured
+SQLite busy wait without blocking the loop. It retries only contention, with a
+short asynchronous backoff. An ordinary error or an exhausted budget is logged
+and returned as deferred completion, not success. The pending evidence remains
+available to the runner, a subsequent admission retry, or recovery; another
+terminalizer cannot erase it. A new admission that still cannot finish that
+completion fails closed rather than steering into the ended native Turn.
+
+The runner's existing fallback attempts can retry the retained evidence. Persistent
+storage failure remains unresolved, as before; this does not invent an empty result,
+pretend that a write landed, or make one retry Task wait forever. A process crash
+before B commits leaves the durable owner for ordinary startup recovery, as in the
+existing gap between path A and B. The in-memory latch is not a new crash journal.
+
+Backend refresh snapshots the generation's durable and projected owners before
+joining pending completions. A successor selected during that join is not silently
+added to the old generation's teardown set. A delivered predecessor does not gain
+a spurious refresh interruption notice, including when its join exhausts the retry
+budget and the durable row has not landed yet. A refresh without a drain also
+excludes the successor from its pre-join ownership snapshot.
+
+Shutdown marks pending completions and their projected runners as queue-deferred
+before flushing them with a bounded wait. It does not restore a synchronous writer
+wait on expiry. Their ordinary cleanup owners still join finite attempts; the
+existing shutdown owner retains responsibility for finishing store workers. Neither
+the pending Task nor the runner/holder starts a successor during this flush.
+
+## Validation
+
+The regression probe uses a separate spawned process holding `BEGIN IMMEDIATE`.
+That process releases its writer only after a queued controller callback reaches
+it, or a watchdog bounds the failure. On baseline `d4c37f082`, the callback arrives
+only after the watchdog releases SQLite: the probe fails for the writer wait while
+the eventual evidence assertions still pass. With this change it passes. There is
+no expected-failure marker in the delivered tests.
+
+Owning-boundary evidence:
+
+- `test_terminal_successor_selection_excludes_a_competing_admission`: a second
+ connection requests admission between the predecessor CAS and successor selection;
+ linked P0, start replay and FIFO each retain their intended owner.
+- `test_contended_terminal_keeps_cleanup_fenced_until_evidence_commits`: real
+ dispatcher, ordinary runner and agent-initiated holder, with and without backlog;
+ repeated cancellation, refresh and shutdown; Hub observes a terminal row, terminal
+ events precede end, and successor launch is exactly once or explicitly deferred.
+- `test_admission_joins_delivered_terminal_instead_of_the_ended_native`: concurrent
+ P1 starts as new input after B; Stop does not target the ended native.
+- The existing late-accepted Run/Activity settlement test now also runs under B
+ contention, with the receipt arriving before the writer is released. Expiry cases
+ let the caller return before B commits, then prove a fresh manager consumes the
+ accepted recovery fence without backend reconciliation, including after UNKNOWN.
+- `test_pending_terminal_evidence_survives_timeout_and_competing_terminalizer`:
+ native terminal, absent-start proof, refresh and shutdown cannot replace B's
+ evidence, including after a bounded attempt expires.
+- `test_terminal_retry_rechecks_retired_generation_without_holding_its_boundary`:
+ retirement between attempts succeeds; the predecessor commits but backlog stays
+ queued and no off-loop boundary holder is used.
+- `test_resultless_terminal_run_settlement_lands_off_loop_before_completion`: a
+ competing writer at the *second* transaction leaves the loop responsive and the
+ completion fence in place; an owned worker survives cancellation and settles the Run.
+ A real one-shot definition proves its store projection is off-loop but scheduler
+ job retirement returns to the loop.
+- `test_recovery_redrives_a_failed_post_commit_terminal_tail`: each runtime start,
+ drain and linked-resume gate re-arms a failed tail without a new user admission.
+- `test_refresh_does_not_relabel_delivered_evidence_after_retry_expiry`: the sink
+ is absent and B remains busy through refresh's join, but no interruption replaces
+ the delivered result or produces a notice.
+- `test_expired_terminal_retries_keep_the_runner_as_the_only_resume_owner`: two
+ exhausted pre-Hub attempts followed by a successful fallback still resume once.
+
+Existing FSM, Model Hub finalization, synchronous emit ordering, no-op writer,
+unknown-start, restart and delivery-recovery tests remain part of validation.
+Manual service / local Incus verification is deliberately not performed in this lane.
diff --git a/docs/plans/terminal-emit-durable-first.md b/docs/plans/terminal-emit-durable-first.md
index 58767ddd9..622a26113 100644
--- a/docs/plans/terminal-emit-durable-first.md
+++ b/docs/plans/terminal-emit-durable-first.md
@@ -2,6 +2,16 @@
Status: implemented (#2714). The runner's fallback order is #2735.
+**B step 2 amendment (#2706):** the signal, runtime release and initial B attempt
+still run without an await. B now tries SQLite's writer without waiting. On
+contention, an exact-Turn pending completion fences cleanup, admissions and late
+receipts until the evidence and successor decision land; resultless Run settlement
+finishes through the runtime-work door before terminal events. See
+[terminal-completion synchronization](terminal-completion-synchronization.md) for
+the current retry, cancellation and shutdown contract. The rest of this note
+records the original #2714 placement decision; its synchronous B-write assumption
+is superseded only by that explicit completion fence.
+
## Background
A terminal result reaches its durable Turn through two writers:
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index 7721460ca..0795ae4f1 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -1868,7 +1868,11 @@ def mark_attempt_receipt(
conn,
delivery_id,
expected_version=expected_version,
- expected_states=("steering",),
+ expected_states=(
+ ("steering", "reconciling_steer")
+ if outcome == "accepted" and delivery.get("current_receipt_outcome") == "unknown"
+ else ("steering",)
+ ),
values={
"state": "reconciling_steer",
"current_receipt_outcome": outcome,
@@ -1917,13 +1921,16 @@ def mark_attempt_receipt_batch(
or (
row["state"] == "reconciling_steer"
and row.get("current_receipt_outcome") != outcome
+ # Definitive acceptance upgrades an earlier UNKNOWN reconciliation,
+ # never the reverse. Both still belong to this exact current attempt.
+ and not (outcome == "accepted" and row.get("current_receipt_outcome") == "unknown")
)
for row in rows
):
return []
saved_rows: list[dict[str, Any]] = []
for row in rows:
- if row["state"] == "reconciling_steer":
+ if row["state"] == "reconciling_steer" and row.get("current_receipt_outcome") == outcome:
saved_rows.append(row)
continue
saved = mark_attempt_receipt(
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index c3452123c..d7edecff2 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -2275,6 +2275,119 @@ def test_terminal_transaction_claims_fifo_and_projects_running_atomically(manage
assert status == "running"
[email protected]("successor_kind", ["linked_p0", "start_replay", "fifo"])
+def test_terminal_successor_selection_excludes_a_competing_admission(
+ managers, monkeypatch, successor_kind,
+) -> None:
+ """#2706 B2: no connection can admit into a terminal/selection gap.
+
+ The existing atomic projection test checks only the final state. Here a
+ second manager actually requests SQLite's writer after the predecessor CAS,
+ before selection of its intended successor. Splitting those writes into
+ separate transactions would let that admission steal the next owner.
+ """
+ from sqlalchemy import event
+
+ manager, contender, engine, contender_engine, _starts = managers
+
+ async def prepare():
+ if successor_kind == "start_replay":
+ initial = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="replay"),
+ context=_context(),
+ )
+ turn_id = str(initial.turn_id)
+ with engine.begin() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert delivery_store.mark_start_unknown(
+ conn, turn_id, expected_version=int(turn["version"]),
+ receipt={"reason": "test_unknown_start"},
+ ) is not None
+ expected_delivery = str(initial.delivery_id)
+ else:
+ turn_id, context = await _activate(manager)
+ expected_delivery = None
+ if successor_kind == "linked_p0":
+ holder = asyncio.create_task(asyncio.Event().wait())
+ manager.in_flight["ses_fsm"] = Turn(
+ task=holder, context=context, logical_turn_id=turn_id,
+ )
+ try:
+ replacement = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p0", content="replacement"),
+ context=_context(),
+ )
+ assert replacement.state == "waiting_terminal"
+ expected_delivery = str(replacement.delivery_id)
+ finally:
+ manager.in_flight.pop("ses_fsm")
+ holder.cancel()
+ await asyncio.gather(holder, return_exceptions=True)
+ # Give the later admission something it could claim incorrectly when a
+ # linked P0/replay is not yet selected. Different authors keep the FIFO
+ # and challenger from coalescing into the same start batch.
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="older FIFO", author_id="older"),
+ context=_context(),
+ )
+ return turn_id, expected_delivery or str(queued.delivery_id)
+
+ turn_id, expected_delivery = asyncio.run(prepare())
+ snapshot_written = threading.Event()
+ contender_at_writer = threading.Event()
+ original_snapshot = manager._write_terminal_snapshot
+
+ def snapshot_then_contend(conn, candidate, **kwargs):
+ result = original_snapshot(conn, candidate, **kwargs)
+ if candidate == turn_id and result.get("changed"):
+ snapshot_written.set()
+ assert contender_at_writer.wait(5), "competing admission never requested the writer"
+ return result
+
+ def observe_writer(_conn, _cursor, statement, _parameters, _context, _many):
+ if statement.lstrip().upper().startswith("BEGIN IMMEDIATE"):
+ contender_at_writer.set()
+
+ def admit():
+ assert snapshot_written.wait(5), "terminal snapshot never reached its transaction"
+ return asyncio.run(contender.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p1", content="new admission", author_id="new"),
+ context=_context(),
+ ))
+
+ monkeypatch.setattr(manager, "_write_terminal_snapshot", snapshot_then_contend)
+ event.listen(contender_engine, "before_cursor_execute", observe_writer)
+ try:
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ competing = pool.submit(admit)
+ terminal = manager._terminalize_durable_turn(
+ turn_id,
+ "failed" if successor_kind == "start_replay" else "completed",
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ evidence_kind="terminal_result",
+ evidence={"result_text": "immutable result", "settles_run": True},
+ replay_unknown_start=successor_kind == "start_replay",
+ )
+ admitted = competing.result(timeout=5)
+ finally:
+ event.remove(contender_engine, "before_cursor_execute", observe_writer)
+
+ assert terminal["changed"] is True
+ assert terminal["successor_turn_id"]
+ assert admitted.state == "queued"
+ with engine.connect() as conn:
+ predecessor = delivery_store.get_turn(conn, turn_id)
+ successor = delivery_store.active_turn(conn, "ses_fsm")
+ selected = delivery_store.get_delivery(conn, expected_delivery)
+ challenger = delivery_store.get_delivery(conn, str(admitted.delivery_id))
+ assert predecessor["state"] == "terminal"
+ assert json.loads(predecessor["terminal_evidence_json"])["result_text"] == "immutable result"
+ assert successor["id"] == terminal["successor_turn_id"]
+ assert selected["turn_id"] == successor["id"]
+ assert selected["state"] == "claimed"
+ assert challenger["state"] == "queued" and challenger["turn_id"] is None
+
+
def test_post_native_terminal_storage_failure_retains_owner_and_running_projection(
managers,
monkeypatch,
@@ -7291,9 +7404,12 @@ def test_accepted_steer_after_target_terminal_attaches_exact_terminal_turn(manag
@pytest.mark.parametrize("activity_blocks_settlement", [False, True])
[email protected]("terminal_contended", [False, True, "expired", "expired_unknown"])
def test_late_accepted_agent_run_settles_from_terminal_turn_snapshot(
managers,
+ monkeypatch,
activity_blocks_settlement: bool,
+ terminal_contended: bool | str,
) -> None:
from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
from storage.background import SQLiteBackgroundTaskStore
@@ -7313,6 +7429,9 @@ def test_late_accepted_agent_run_settles_from_terminal_turn_snapshot(
)
async def run() -> tuple[str, str, str]:
+ expires = isinstance(terminal_contended, str)
+ if expires:
+ monkeypatch.setattr(manager, "TERMINAL_WRITE_RETRY_SECONDS", 0)
turn_id, active_context = await _activate(manager)
run_id = "run-late-terminal-steer"
now = "2026-08-01T00:00:00Z"
@@ -7384,10 +7503,57 @@ def test_late_accepted_agent_run_settles_from_terminal_turn_snapshot(
"settles_run": True,
},
)
- manager.on_terminal_delivery_complete(active_context)
- release.set()
- accepted_delivery = await promoted
- assert accepted_delivery.state == "accepted"
+ receipt_arrived = asyncio.Event()
+ original_finish = manager._finish_steer
+
+ async def finish(*args, **kwargs):
+ receipt_arrived.set()
+ return await original_finish(*args, **kwargs)
+
+ monkeypatch.setattr(manager, "_finish_steer", finish)
+ with _engine_b.connect() as blocker:
+ if terminal_contended:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ manager.on_terminal_delivery_complete(active_context)
+ release.set()
+ if terminal_contended:
+ await asyncio.wait_for(receipt_arrived.wait(), 5)
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, turn_id)["state"] == "active"
+ if expires:
+ deferred = await asyncio.wait_for(promoted, 5)
+ assert deferred.state == "reconciling_steer"
+ assert deferred.reason == "terminal_commit_pending"
+ else:
+ assert not promoted.done()
+ blocker.rollback()
+ if expires:
+ if terminal_contended == "expired_unknown":
+ # Recovery can have saved UNKNOWN before the authoritative
+ # acceptance lands. Definitive proof must upgrade that fence.
+ with engine.begin() as conn:
+ assert delivery_store.mark_attempt_receipt_batch(
+ conn, leader_delivery_id=str(queued.delivery_id), outcome="unknown",
+ receipt={"reason": "backend_has_no_durable_reconciliation"},
+ )
+ await manager._join_session_terminal("ses_fsm")
+ with engine.connect() as conn:
+ fenced = delivery_store.get_delivery(conn, str(queued.delivery_id))
+ assert fenced["current_receipt_outcome"] == "accepted"
+ assert fenced["state"] == "reconciling_steer"
+ # A fresh manager needs neither the in-memory latch nor the
+ # backend's receipt cache to materialize and settle this Run.
+ _terminal_manager.controller.scheduled_task_service = scheduled
+ _terminal_manager._reconcile_steer_attempt = AsyncMock(
+ side_effect=AssertionError("accepted proof must not ask the backend"),
+ )
+ observations, _ = _terminal_manager.scan_runtime_delivery_recovery(limit=10, occupied=frozenset())
+ observation = next(item for item in observations if item.delivery_id == str(queued.delivery_id))
+ assert await _terminal_manager.recover_runtime_delivery_observation(observation)
+ _terminal_manager._reconcile_steer_attempt.assert_not_awaited()
+ else:
+ accepted_delivery = await promoted
+ assert accepted_delivery.state == "accepted"
return turn_id, run_id, str(queued.delivery_id)
try:
@@ -8787,6 +8953,413 @@ def test_startup_recovery_reads_growing_tables_only_through_index_seeks(tmp_path
assert not scans, "startup recovery scans a growing table:\n" + "\n".join(scans)
+async def test_resultless_terminal_run_settlement_lands_off_loop_before_completion(
+ managers, monkeypatch,
+):
+ """The resultless B tail is a second writer, not covered by its zero-wait BEGIN."""
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStore
+ from storage.background import SQLiteBackgroundTaskStore
+
+ manager, _other, engine, engine_b, _starts = managers
+ run_store = SQLiteBackgroundTaskStore(Path(str(engine.url.database)))
+ requests = TaskExecutionStore(root=Path(str(engine.url.database)).parent / "unused")
+ requests._sqlite = run_store
+ definitions = ScheduledTaskStore(path=Path(str(engine.url.database)).parent / "unused.json")
+ definitions._sqlite = run_store
+ service = ScheduledTaskService(controller=manager.controller, store=definitions, request_store=requests)
+ manager.controller.scheduled_task_service = service
+ definition = definitions.add_task(
+ session_id="ses_fsm", session_key="", prompt="primary", schedule_type="at",
+ run_at="2030-08-01T00:00:00+00:00", timezone_name="UTC",
+ )
+ request = requests.enqueue_task_run(
+ definition.id, source_kind="scheduler", task=definition,
+ expected_run_at=definition.run_at, expected_timezone=definition.timezone,
+ expected_job_id="resultless-job",
+ )
+ assert request is not None
+ definitions.load()
+ service.scheduler.add_job(lambda: None, "date", run_date=definition.run_at, id="resultless-job")
+ service._job_ids[definition.id] = "resultless-job"
+ turn_id, _context_value = await _activate(manager)
+ with engine.begin() as conn:
+ initial = delivery_store.initial_deliveries_for_turn(conn, turn_id)[0]
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_status="running"))
+ conn.execute(update(agent_runs).where(agent_runs.c.id == request.id).values(
+ status="running", delivery_id=initial["id"],
+ ))
+ worker_entered = asyncio.Event()
+ loop = asyncio.get_running_loop()
+ loop_thread = threading.get_ident()
+ original_settle = manager._settle_agent_run_ids_from_terminal_turn
+ original_retire = service._retire_one_shot_job
+ retirement_threads = []
+ events = []
+
+ def retire(task_id):
+ retirement_threads.append(threading.get_ident())
+ return original_retire(task_id)
+
+ monkeypatch.setattr(service, "_retire_one_shot_job", retire)
+
+ def settle(*args, **kwargs):
+ assert threading.get_ident() != loop_thread
+ loop.call_soon_threadsafe(worker_entered.set)
+ return original_settle(*args, **kwargs)
+
+ monkeypatch.setattr(manager, "_settle_agent_run_ids_from_terminal_turn", settle)
+ monkeypatch.setattr("core.inbox_events.bus.publish", lambda event, _payload: events.append(event))
+ try:
+ manager._finish_durable_terminal_result(
+ "ses_fsm", turn_id, is_error=True, settled_by=SETTLED_BY_STOPPED,
+ terminal_evidence={"settles_run": False, "result_text": ""},
+ )
+ pending = manager._pending_terminals[turn_id]
+ with engine_b.connect() as blocker:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ await asyncio.wait_for(worker_entered.wait(), 5)
+ assert not pending.task.done()
+ assert "session.status" not in events
+ with engine.connect() as conn:
+ assert conn.execute(select(agent_runs.c.status).where(agent_runs.c.id == request.id)).scalar_one() == "running"
+ pending.task.cancel() # An owned store step still has to land.
+ blocker.rollback()
+ await asyncio.wait_for(pending.task, 5)
+ with engine.connect() as conn:
+ assert conn.execute(select(agent_runs.c.status).where(agent_runs.c.id == request.id)).scalar_one() == "canceled"
+ assert delivery_store.get_turn(conn, turn_id)["terminal_outcome"] == "canceled"
+ assert events.count("session.status") == 1
+ assert retirement_threads == [loop_thread]
+ assert service.scheduler.get_job("resultless-job") is None
+ assert definition.id not in service._job_ids
+ assert not manager._pending_terminals
+ finally:
+ run_store.close()
+
+
[email protected]("gate", ["start", "drain", "linked"])
+async def test_recovery_redrives_a_failed_post_commit_terminal_tail(managers, monkeypatch, gate):
+ """A retained committed tail must recover without a new user admission.
+
+ Existing contention cases never fail after the transaction has selected a
+ successor; a failed executor admission used to leave that successor fenced forever.
+ """
+ manager, _other, engine, _engine_b, starts = managers
+ turn_id, context = await _activate(manager)
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"), context=_context(),
+ )
+ with engine.begin() as conn:
+ initial = delivery_store.initial_deliveries_for_turn(conn, turn_id)[0]
+ conn.execute(agent_runs.insert().values(
+ id="tail-run", run_type="agent_run", status="running", cancel_requested=0,
+ session_id="ses_fsm", delivery_id=initial["id"], metadata_json="{}",
+ created_at="2026-08-01T00:00:00Z", updated_at="2026-08-01T00:00:00Z",
+ ))
+ original = manager._run_off_loop
+ attempts = []
+
+ async def worker(operation):
+ attempts.append(operation)
+ if len(attempts) == 1:
+ raise RuntimeError("executor temporarily unavailable")
+ return await original(operation)
+
+ publication_attempts = []
+ publish_terminal = manager._publish_terminal_inbox_update
+
+ def publish(session_id):
+ publication_attempts.append(session_id)
+ return publish_terminal(session_id)
+
+ monkeypatch.setattr(manager, "_run_off_loop", worker)
+ monkeypatch.setattr(manager, "_publish_terminal_inbox_update", publish)
+ manager._finish_durable_terminal_result(
+ "ses_fsm", turn_id, is_error=True, settled_by=SETTLED_BY_STOPPED,
+ terminal_evidence={"settles_run": False, "result_text": ""},
+ )
+ pending = manager._pending_terminals[turn_id]
+ first = pending.task
+ assert (await first)["defer_queue_resume"]
+ assert pending.result["changed"] and not publication_attempts
+ with engine.connect() as conn:
+ successor = delivery_store.get_delivery(conn, str(queued.delivery_id))["turn_id"]
+ if gate == "start":
+ assert not await manager._start_persisted_turn(successor)
+ elif gate == "drain":
+ assert not await manager.drain_delivery_queue("ses_fsm")
+ else:
+ assert not await manager._resume_linked_control_successor("ses_fsm", turn_id)
+ assert pending.task is not first, "recovery left a failed completion permanently fenced"
+ await asyncio.wait_for(pending.task, 5)
+ # The completion owns the resume; yield to that real continuation once.
+ await asyncio.sleep(0)
+ assert not manager._pending_terminals
+ assert len(attempts) == 2
+ assert publication_attempts == ["ses_fsm"]
+ assert [text for _, text in starts] == ["primary", "next"]
+
+
[email protected]("admission", ["p1", "stop"])
+async def test_admission_joins_delivered_terminal_instead_of_the_ended_native(
+ managers, monkeypatch, admission,
+):
+ """An asynchronously pending B must not expose the ended native to P1/P0."""
+ manager, _other, engine, engine_b, starts = managers
+ turn_id, context = await _activate(manager)
+ manager._steer = AsyncMock(side_effect=AssertionError("steered into ended native"))
+ joining = asyncio.Event()
+ original_join = manager._join_session_terminal
+
+ async def join(session_id):
+ joining.set()
+ await original_join(session_id)
+
+ monkeypatch.setattr(manager, "_join_session_terminal", join)
+ manager.on_terminal_result(context, is_error=False, terminal_evidence={"result_text": "answer", "settles_run": True})
+ with engine_b.connect() as blocker:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ manager.on_terminal_delivery_complete(context)
+ operation = asyncio.create_task(
+ manager.deliver(DeliveryRequest(session_id="ses_fsm", priority="p1", content="new input"), context=_context())
+ if admission == "p1" else manager.cancel("ses_fsm")
+ )
+ await asyncio.wait_for(joining.wait(), 5)
+ assert not operation.done()
+ manager._steer.assert_not_awaited()
+ manager.controller.command_handler.handle_stop.assert_not_awaited()
+ blocker.rollback()
+ result = await asyncio.wait_for(operation, 5)
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, turn_id)["state"] == "terminal"
+ if admission == "p1":
+ assert result.state == "claimed" and result.turn_id != turn_id
+ assert [text for _, text in starts] == ["primary", "new input"]
+ else:
+ assert result["code"] == "not_in_flight"
+ assert [text for _, text in starts] == ["primary"]
+
+
[email protected]("competitor", ["native", "absent_start", "refresh", "shutdown"])
+async def test_pending_terminal_evidence_survives_timeout_and_competing_terminalizer(
+ managers, monkeypatch, competitor,
+):
+ """The retry deadline bounds waiting, not ownership of the delivered evidence."""
+ manager, _other, engine, engine_b, _starts = managers
+ turn_id, context = await _activate(manager)
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"), context=_context(),
+ )
+ monkeypatch.setattr(manager, "TERMINAL_WRITE_RETRY_SECONDS", 0)
+ evidence = {"result_text": "first evidence", "settles_run": True}
+ manager.on_terminal_result(context, is_error=False, terminal_evidence=evidence)
+ with engine_b.connect() as blocker:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ manager.on_terminal_delivery_complete(context)
+ pending = manager._pending_terminals[turn_id]
+ assert (await pending.task)["defer_queue_resume"] is True
+ assert manager._pending_terminals[turn_id] is pending
+ blocker.rollback()
+ if competitor == "native":
+ resume = manager.on_native_terminal(context, outcome="failed")
+ if resume is not None:
+ await resume
+ elif competitor == "absent_start":
+ with engine.connect() as conn:
+ attempt_id = delivery_store.get_turn(conn, turn_id)["start_attempt_id"]
+ assert attempt_id
+ assert not manager.reconcile_start_attempt_not_written(turn_id, attempt_id, backend="codex")
+ elif competitor == "refresh":
+ await manager.release_for_backend_refresh(backend="codex", base_session_ids={"ses_fsm"})
+ else:
+ await manager.release_for_service_shutdown()
+ if turn_id in manager._pending_terminals:
+ await manager._pending_terminals[turn_id].task
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ successor = delivery_store.get_delivery(conn, str(queued.delivery_id))
+ assert turn["state"] == "terminal" and turn["terminal_outcome"] == "completed"
+ assert turn["terminal_evidence_kind"] == "terminal_result"
+ assert json.loads(turn["terminal_evidence_json"]) == evidence
+ assert successor["state"] == ("queued" if competitor == "shutdown" else "claimed")
+ assert not manager._pending_terminals
+
+
+async def test_refresh_does_not_relabel_delivered_evidence_after_retry_expiry(managers, monkeypatch):
+ """An expired pending write still decides the projected Turn's outcome.
+
+ Existing refresh cases release SQLite before the join finishes, so they cannot
+ catch a spurious refresh notice when the sink is gone but B is still pending.
+ """
+ from core.session_turns import Turn
+
+ manager, _other, engine, engine_b, _starts = managers
+ turn_id, context = await _activate(manager)
+ monkeypatch.setattr(manager, "TERMINAL_WRITE_RETRY_SECONDS", 0)
+ notices = Mock()
+ monkeypatch.setattr(manager, "_notify_backend_refresh", notices)
+ entered = asyncio.Event()
+ with engine_b.connect() as blocker:
+ async def projected_runner():
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ # Release only after refresh has chosen whether it owns the
+ # outcome, not during its bounded pending-completion join.
+ blocker.rollback()
+
+ task = asyncio.create_task(projected_runner())
+ projected = Turn(task=task, context=context, started_at="2026-08-01T00:00:00Z", logical_turn_id=turn_id)
+ manager.in_flight["ses_fsm"] = projected
+ await entered.wait()
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ manager.on_terminal_result(context, is_error=False, terminal_evidence={"result_text": "delivered"})
+ manager.on_terminal_delivery_complete(context)
+ pending = manager._pending_terminals[turn_id]
+ assert (await pending.task)["defer_queue_resume"]
+ assert not manager._turn_outcome_decided(projected)
+ try:
+ await manager.release_for_backend_refresh(backend="codex", base_session_ids={"ses_fsm"})
+ await pending.task
+ finally:
+ blocker.rollback()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ manager.in_flight.pop("ses_fsm", None)
+ assert projected.cancel_settled_by is None
+ notices.assert_not_called()
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, turn_id)["terminal_evidence_kind"] == "terminal_result"
+ assert not manager._pending_terminals
+
+
+async def test_terminal_retry_rechecks_retired_generation_without_holding_its_boundary(
+ managers, caplog,
+):
+ """Retirement between zero-wait attempts leaves the successor unpromoted."""
+ manager, _other, engine, engine_b, starts = managers
+ turn_id, context = await _activate(manager)
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"), context=_context(),
+ )
+ registry = RuntimeActivationRegistry()
+ registry.bind_loop_thread()
+ identity = registry.attach("codex", "exact-generation")
+ manager.controller.agent_service.activation_registry = registry
+ manager.controller.agent_service.runtime_activation_identity_for_session_binding = (
+ lambda *_args, **_kwargs: RuntimeActivationResolution(authoritative=True, identity=identity)
+ )
+ manager.on_terminal_result(context, is_error=False, terminal_evidence={"result_text": "answer"})
+ with engine_b.connect() as blocker:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ manager.on_terminal_delivery_complete(context)
+ pending = manager._pending_terminals[turn_id]
+ assert registry.retire_if_current(identity, lambda: True)
+ blocker.rollback()
+ await asyncio.wait_for(pending.task, 5)
+ with engine.connect() as conn:
+ assert delivery_store.get_turn(conn, turn_id)["terminal_evidence_kind"] == "terminal_result"
+ assert delivery_store.get_delivery(conn, str(queued.delivery_id))["state"] == "queued"
+ assert [text for _, text in starts] == ["primary"]
+ assert "off the controller loop" not in caplog.text
+ assert not manager._pending_terminals
+
+
+def _hold_terminal_probe_writer(db_path, channel) -> None:
+ """An independent process releases its writer after a loop tick or watchdog."""
+ try:
+ with closing(sqlite3.connect(db_path)) as connection:
+ connection.execute("BEGIN IMMEDIATE")
+ channel.send("writer_held")
+ # This is only a deadlock escape on the unfixed baseline, not a
+ # sleep used to arrange a race. The parent cannot request the tick
+ # before receiving writer_held.
+ tick_before_release = channel.poll(2) and channel.recv() == "loop_tick"
+ connection.rollback()
+ channel.send(bool(tick_before_release))
+ # Keep the pipe open for the late tick on the unfixed baseline.
+ # The parent acknowledges the observation before joining us.
+ while channel.poll(10):
+ if channel.recv() == "probe_complete":
+ break
+ else:
+ raise RuntimeError("parent never acknowledged the writer probe")
+ finally:
+ channel.close()
+
+
+async def test_terminal_evidence_writer_keeps_controller_loop_responsive(managers, monkeypatch):
+ """A separate process holds the writer until a queued loop callback runs.
+
+ The watchdog only bounds a regression; evidence/setup/teardown must also pass.
+ """
+ import inspect
+ import multiprocessing
+
+ manager, _other, engine, _engine_b, _starts = managers
+ turn_id, context = await _activate(manager, text="contended terminal")
+ manager.on_terminal_result(
+ context, is_error=False,
+ terminal_evidence={"result_text": "durable result", "settles_run": True},
+ )
+ complete = asyncio.Event()
+ publish = manager._publish_terminal_inbox_update
+
+ def publish_and_signal(session_id):
+ publish(session_id)
+ complete.set()
+
+ monkeypatch.setattr(manager, "_publish_terminal_inbox_update", publish_and_signal)
+ spawn = multiprocessing.get_context("spawn")
+ parent, child = spawn.Pipe()
+ writer = spawn.Process(
+ target=_hold_terminal_probe_writer,
+ args=(str(engine.url.database), child),
+ )
+ writer.start()
+ child.close()
+ tick = None
+ try:
+ assert await asyncio.to_thread(parent.poll, 10), "writer process did not start"
+ assert parent.recv() == "writer_held"
+ tick = asyncio.get_running_loop().call_soon(parent.send, "loop_tick")
+ result = manager.on_terminal_delivery_complete(context)
+ if inspect.isawaitable(result):
+ await result
+ await asyncio.wait_for(complete.wait(), 10)
+ assert await asyncio.to_thread(parent.poll, 10), "writer process did not finish"
+ tick_before_release = parent.recv()
+ with engine.connect() as conn:
+ turn = delivery_store.get_turn(conn, turn_id)
+ assert turn["state"] == "terminal"
+ assert turn["terminal_evidence_kind"] == "terminal_result"
+ assert json.loads(turn["terminal_evidence_json"]) == {
+ "result_text": "durable result", "settles_run": True,
+ }
+ assert tick_before_release, (
+ "the controller callback ran only after the separate writer's watchdog released SQLite"
+ )
+ finally:
+ if tick is not None:
+ tick.cancel()
+ if writer.is_alive():
+ parent.send("probe_complete")
+ await asyncio.to_thread(writer.join, 5)
+ if writer.is_alive():
+ writer.terminate() # Only this test-owned process, never a pattern kill.
+ await asyncio.to_thread(writer.join, 5)
+ parent.close()
+ assert writer.exitcode == 0, "writer process failed or required forced teardown"
+
+
@pytest.mark.anyio
async def test_a_turn_end_after_its_terminal_write_takes_no_writer(managers) -> None:
"""#2706: a Turn end reaches SQLite's writer from several owners on the controller loop: the evidence-carrying
diff --git a/tests/test_terminal_emit_commit.py b/tests/test_terminal_emit_commit.py
index f36ee6c42..302f76488 100644
--- a/tests/test_terminal_emit_commit.py
+++ b/tests/test_terminal_emit_commit.py
@@ -22,7 +22,7 @@ from core.session_turns import SessionTurnManager
from sqlalchemy import update
from storage import message_deliveries as delivery_store
-from storage.models import agent_sessions
+from storage.models import agent_sessions, messages
from tests.test_message_dispatcher_result_fallback import (
_StubIMClient,
_StubSessionHandler,
@@ -145,6 +145,145 @@ async def _blocked_at(dispatcher, monkeypatch, name: str) -> asyncio.Event:
return entered
[email protected]("owner", ["runner", "agent_initiated"])
[email protected]("interruption", ["none", "cancel", "refresh", "refresh_no_drain", "shutdown"])
[email protected]("backlog", [False, True])
+def test_contended_terminal_keeps_cleanup_fenced_until_evidence_commits(
+ managers, monkeypatch, owner, interruption, backlog,
+):
+ """#2706 B2: a signalled runner cannot outrun the asynchronous writer wait.
+
+ Prior tests only delayed IM surfaces / Hub, not the evidence write itself.
+ Check the real dispatcher and each cleanup owner, including repeated cancel.
+ """
+ manager, _other, engine, engine_b, _starts = managers
+ harness = _Harness(manager, engine, monkeypatch)
+
+ async def exercise():
+ context = _context()
+ if owner == "runner":
+ turn_id, context = await _activate(manager)
+ else:
+ assert manager.register_agent_initiated_turn(context)
+ turn_id = context.platform_specific["turn_token"]
+ if backlog:
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"), context=_context(),
+ )
+ with engine.begin() as conn:
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_status="running"))
+ conn.execute(messages.insert().values(
+ id="prior-result", session_id="ses_fsm", platform="avibe", author="agent", type="result",
+ source="agent", content_text="prior result", content_json="{}", metadata_json="{}",
+ created_at="2026-07-31T23:59:00Z", updated_at="2026-07-31T23:59:00Z",
+ ))
+ contended = asyncio.Event()
+ cleanup_waiting = asyncio.Event()
+ events = []
+ launched = []
+ hub_states = []
+ original_terminalize = manager._terminalize_durable_turn
+ original_join = manager._join_terminal_cleanup
+
+ def hub(_context, _settled_by):
+ hub_states.append(harness.turn(turn_id)["state"])
+
+ async def join(candidate):
+ if candidate == turn_id:
+ cleanup_waiting.set()
+ return await original_join(candidate)
+
+ async def launch(candidate, **_kwargs):
+ launched.append(candidate)
+ return True
+
+ monkeypatch.setattr(manager, "_settle_model_hub_turn", hub)
+ monkeypatch.setattr(manager, "_join_terminal_cleanup", join)
+ monkeypatch.setattr(manager, "_start_persisted_turn", launch)
+ monkeypatch.setattr("core.inbox_events.bus.publish", lambda name, _payload: events.append(name))
+ with engine_b.connect() as blocker:
+ def terminalize(candidate, outcome, **kwargs):
+ first = candidate == turn_id and kwargs.get("evidence_kind") == "terminal_result" and not contended.is_set()
+ if first:
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ result = original_terminalize(candidate, outcome, **kwargs)
+ if first:
+ contended.set()
+ return result
+
+ monkeypatch.setattr(manager, "_terminalize_durable_turn", terminalize)
+ if owner == "runner":
+ task = await harness.start(turn_id, context)
+ else:
+ task = manager.in_flight["ses_fsm"].task
+ harness.receivers.append(asyncio.create_task(harness.controller.emit_agent_message(context, "result", RESULT)))
+ try:
+ await asyncio.wait_for(contended.wait(), WAIT_S)
+ await asyncio.wait_for(cleanup_waiting.wait(), WAIT_S)
+ assert not task.done()
+ assert harness.turn(turn_id)["state"] == "active"
+ assert not hub_states and not launched and "turn.end" not in events
+ transition = None
+ if interruption == "cancel":
+ task.cancel()
+ # A second cancellation must not cancel the pending write.
+ asyncio.get_running_loop().call_soon(task.cancel)
+ elif interruption in {"refresh", "refresh_no_drain", "shutdown"}:
+ transition_waiting = asyncio.Event()
+ ensure = manager._ensure_terminal_completion
+
+ def joined(pending):
+ result = ensure(pending)
+ if asyncio.current_task() is transition:
+ transition_waiting.set()
+ return result
+
+ monkeypatch.setattr(manager, "_ensure_terminal_completion", joined)
+ if interruption in {"refresh", "refresh_no_drain"}:
+ if interruption == "refresh":
+ manager.begin_backend_drain("codex")
+ transition = asyncio.create_task(manager.release_for_backend_refresh(
+ backend="codex", base_session_ids={"ses_fsm"},
+ ))
+ else:
+ transition = asyncio.create_task(manager.release_for_service_shutdown())
+ await asyncio.wait_for(transition_waiting.wait(), WAIT_S)
+ blocker.rollback()
+ await asyncio.wait_for(asyncio.gather(task, *harness.receivers, return_exceptions=True), WAIT_S)
+ if transition is not None:
+ await asyncio.wait_for(transition, WAIT_S)
+ finally:
+ blocker.rollback()
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, *harness.receivers, return_exceptions=True)
+ turn = harness.turn(turn_id)
+ assert turn["terminal_evidence_kind"] == "terminal_result"
+ assert _evidence(turn)["result_text"] == RESULT
+ assert "ses_fsm" not in manager.in_flight
+ assert not manager._pending_terminals
+ assert events.index("inbox.session.updated") < events.index("turn.end")
+ assert events.count("turn.end") == 1
+ if not backlog or interruption in {"refresh", "shutdown"}:
+ assert events.index("session.status") < events.index("turn.end")
+ assert launched == []
+ if backlog:
+ with engine.connect() as conn:
+ selected = delivery_store.get_delivery(conn, str(queued.delivery_id))
+ if interruption in {"refresh", "shutdown"}:
+ assert selected["state"] == "queued"
+ if interruption == "refresh":
+ await manager.end_backend_drain("codex")
+ with engine.connect() as conn:
+ selected = delivery_store.get_delivery(conn, str(queued.delivery_id))
+ assert selected["state"] == "claimed" and launched == [selected["turn_id"]]
+ else:
+ assert selected["state"] == "claimed" and launched == [selected["turn_id"]]
+ assert hub_states == (["terminal"] if owner == "runner" else [])
+
+ asyncio.run(exercise())
+
+
@pytest.mark.parametrize(
"branch",
["silent", "duplicate", "suppressed", "delivered"],
@@ -519,6 +658,60 @@ def harness_state(engine, turn_id: str) -> str:
return str(delivery_store.get_turn(conn, turn_id)["state"])
+def test_expired_terminal_retries_keep_the_runner_as_the_only_resume_owner(managers, monkeypatch):
+ """Post-Hub fallback must retain the projection until pending completion lands.
+
+ Ordinary contention tests finish B before Hub. Two expired attempts used to
+ drop the projection first and let both the retry task and runner resume.
+ """
+ manager, _other, engine, engine_b, _starts = managers
+ harness = _Harness(manager, engine, monkeypatch)
+ monkeypatch.setattr(manager, "TERMINAL_WRITE_RETRY_SECONDS", 0)
+ resumes = []
+ launched = []
+ original_resume = manager._resume_post_terminal
+ original_terminalize = manager._terminalize_durable_turn
+
+ async def resume(session_id):
+ resumes.append(session_id)
+ await original_resume(session_id)
+
+ async def launch(candidate, **_kwargs):
+ launched.append(candidate)
+ return True
+
+ monkeypatch.setattr(manager, "_resume_post_terminal", resume)
+
+ async def exercise():
+ turn_id, context = await _activate(manager)
+ monkeypatch.setattr(manager, "_start_persisted_turn", launch)
+ queued = await manager.deliver(
+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="next"), context=_context(),
+ )
+ first = True
+ with engine_b.connect() as blocker:
+ def terminalize(candidate, outcome, **kwargs):
+ nonlocal first
+ if first and candidate == turn_id and kwargs.get("evidence_kind") == "terminal_result":
+ first = False
+ blocker.exec_driver_sql("BEGIN IMMEDIATE")
+ return original_terminalize(candidate, outcome, **kwargs)
+
+ monkeypatch.setattr(manager, "_terminalize_durable_turn", terminalize)
+ monkeypatch.setattr(manager, "_settle_model_hub_turn", lambda *_args: blocker.rollback())
+ runner = await harness.start(turn_id, context)
+ await asyncio.wait_for(runner, WAIT_S)
+ await asyncio.wait_for(asyncio.gather(*harness.receivers), WAIT_S)
+ assert harness.turn(turn_id)["terminal_evidence_kind"] == "terminal_result"
+ with engine.connect() as conn:
+ successor = delivery_store.get_delivery(conn, str(queued.delivery_id))["turn_id"]
+ assert resumes == ["ses_fsm"]
+ assert launched == [successor]
+ assert not manager._pending_terminals
+
+ asyncio.run(exercise())
+
+
def test_a_fallback_write_that_fails_again_is_retried_after_hub_finalization(managers, monkeypatch) -> None:
"""When the runner's early fallback write meets the same busy database, it still
gets the attempt after Model Hub finalization that it had on master, and the