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(harness): recover stalled session queues (#941)

Call White2302cb78cdaa
diff --git a/core/internal_server.py b/core/internal_server.py
index 2a4af4176..d0d336dc0 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -559,6 +559,18 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)
import uvicorn
app = create_app(controller)
+ manager = getattr(controller, "session_turns", None)
+ recover_queue = getattr(manager, "recover_persisted_agent_run_queue", None)
+ if callable(recover_queue):
+ try:
+ recovered = await recover_queue()
+ if recovered:
+ logger.info(
+ "Recovered persisted Workbench Agent Run queues for %s",
+ ",".join(recovered),
+ )
+ except Exception:
+ logger.exception("Failed to recover persisted Workbench Agent Run queues")
config = uvicorn.Config(
app,
log_config=None,
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 83e99244b..741dfcd6a 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -2455,6 +2455,21 @@ class ScheduledTaskService:
session_id=session_id,
)
await self._drain_callbacks()
+ if request.request_type == "agent_run" and session_id:
+ manager = getattr(self.controller, "session_turns", None)
+ recover_queue = getattr(
+ manager,
+ "recover_persisted_agent_run_queue",
+ None,
+ )
+ if callable(recover_queue):
+ try:
+ await recover_queue(session_id)
+ except Exception:
+ logger.exception(
+ "Failed to recover persisted Agent Run queue for session=%s",
+ session_id,
+ )
async def _execute_task(
self,
diff --git a/core/session_turns.py b/core/session_turns.py
index 331e6ed8f..562679364 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -31,7 +31,8 @@ from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USE
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
from storage import messages_service
from storage.db import get_cached_sqlite_engine
-from storage.models import messages
+from storage.background import normalize_run_status
+from storage.models import agent_runs, messages
from storage.workbench_sessions_service import derive_session_harness_activities
from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
@@ -42,6 +43,10 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
"""Annotate a registry background activity with the unified banner fields.
@@ -145,6 +150,17 @@ def _parse_queue_timestamp(value: Any) -> Optional[datetime]:
return parsed.astimezone(timezone.utc)
+def _run_metadata_holds_workbench_queue(value: Any) -> bool:
+ try:
+ metadata = json.loads(value or "{}")
+ except (TypeError, ValueError):
+ return False
+ return bool(
+ isinstance(metadata, dict)
+ and metadata.get("workbench_queue_holds_run") is True
+ )
+
+
def _scheduled_provenance(row: dict) -> Optional[dict]:
metadata = row.get("metadata") or {}
provenance = metadata.get(SCHEDULED_PROVENANCE_KEY)
@@ -545,6 +561,7 @@ class Turn:
task: asyncio.Task
context: "MessageContext"
+ started_at: str = ""
flush_on_cancel: bool = False
stop_no_flush: bool = False
@@ -579,6 +596,7 @@ class SessionTurnManager:
self.in_flight: dict[str, Turn] = {}
self._draining_backends: set[str] = set()
self._deferred_restart_sessions: dict[str, set[str]] = {}
+ self._queue_recovery_locks: dict[str, asyncio.Lock] = {}
# The live streaming turn sink per SESSION KEY (avibe/web-Chat only; IM/CLI
# turns register none). Each is ``{on_chunk, done_event, turn_token}`` — the
# turn's stream callback + completion event + correlation token. Keyed by
@@ -813,7 +831,11 @@ class SessionTurnManager:
task = asyncio.create_task(_runner(), name="internal-dispatch-async")
if isinstance(session_id, str) and session_id:
- self.in_flight[session_id] = Turn(task=task, context=context)
+ self.in_flight[session_id] = Turn(
+ task=task,
+ context=context,
+ started_at=_utc_now_iso(),
+ )
# Make the DB row authoritative at ACCEPTANCE, not at dispatch start:
# ``update_session``'s backend lock re-checks ``agent_status`` inside
# its UPDATE predicate, so writing ``running`` synchronously here —
@@ -1105,12 +1127,130 @@ class SessionTurnManager:
return False
return True
+ async def recover_persisted_agent_run_queue(
+ self,
+ session_id: Optional[str] = None,
+ ) -> list[str]:
+ """Resume durable Workbench Agent Run queues after their owner vanished.
+
+ ``workbench_queue_holds_run`` rows are deliberately invisible to the
+ scheduler because the Session FSM owns their FIFO position. A process
+ restart drops the in-memory owner and therefore must re-enter that FSM.
+ Recovery is evidence-based: only a persisted queue row that references
+ a still-queued Agent Run is eligible. An older, scheduler-owned queued
+ Run defers recovery until that Run reaches its normal synchronous or
+ terminal path, preserving FIFO across restart.
+ """
+
+ if self._build_context is None:
+ return []
+ if session_id:
+ session_ids = [session_id]
+ else:
+ with self._sqlite_engine().connect() as conn:
+ session_ids = messages_service.list_queued_session_ids(conn)
+
+ recovered: list[str] = []
+ for queued_session_id in session_ids:
+ lock = self._queue_recovery_locks.setdefault(
+ queued_session_id,
+ asyncio.Lock(),
+ )
+ async with lock:
+ entry = self.in_flight.get(queued_session_id)
+ if entry is not None and not entry.task.done():
+ continue
+ with self._sqlite_engine().connect() as conn:
+ queue_rows = messages_service.list_queued(conn, queued_session_id)
+ if not queue_rows:
+ continue
+ head_provenance = _scheduled_provenance(queue_rows[0]) or {}
+ head_spec = head_provenance.get("platform_specific") or {}
+ if (
+ not isinstance(head_spec, dict)
+ or head_spec.get("task_trigger_kind") != "agent_run"
+ ):
+ continue
+ head_segment = _collect_scheduled_segment(queue_rows)
+ referenced_run_ids = _scheduled_segment_execution_ids(
+ head_segment
+ )
+ if not referenced_run_ids:
+ continue
+ run_rows = list(
+ conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.created_at,
+ agent_runs.c.status,
+ agent_runs.c.metadata_json,
+ )
+ .where(agent_runs.c.session_id == queued_session_id)
+ .where(agent_runs.c.run_type == "agent_run")
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ ).mappings()
+ )
+
+ queued_rows = [
+ row
+ for row in run_rows
+ if normalize_run_status(row["status"]) == "queued"
+ ]
+ live_references = {
+ str(row["id"])
+ for row in queued_rows
+ if str(row["id"]) in referenced_run_ids
+ and _run_metadata_holds_workbench_queue(row["metadata_json"])
+ }
+ if not live_references:
+ continue
+
+ first_reference_at = min(
+ (
+ parsed
+ for row in queued_rows
+ if str(row["id"]) in live_references
+ and (parsed := _parse_queue_timestamp(row["created_at"]))
+ is not None
+ ),
+ default=None,
+ )
+ defer_to_scheduler = False
+ for row in queued_rows:
+ run_id = str(row["id"])
+ if run_id in live_references:
+ continue
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except (TypeError, ValueError):
+ metadata = {}
+ if isinstance(metadata, dict) and metadata.get(
+ "workbench_queue_holds_run"
+ ):
+ continue
+ created_at = _parse_queue_timestamp(row["created_at"])
+ if (
+ first_reference_at is None
+ or created_at is None
+ or created_at <= first_reference_at
+ ):
+ defer_to_scheduler = True
+ break
+ if defer_to_scheduler:
+ continue
+
+ if await self.flush_queue(queued_session_id):
+ recovered.append(queued_session_id)
+ return recovered
+
def turn_state(self, session_id: str) -> dict:
"""Compose orthogonal foreground, inbox, Activity, and connection facts."""
entry = self.in_flight.get(session_id)
active = entry is not None and not entry.task.done()
native_turn_started = False
backend = ""
+ backend_alive: Optional[bool] = None
+ owner: dict[str, Any] | None = None
if active and entry is not None:
payload = getattr(entry.context, "platform_specific", None) or {}
target = payload.get("agent_session_target")
@@ -1120,6 +1260,30 @@ class SessionTurnManager:
started = getattr(service, "runtime_turn_started", None)
if callable(started):
native_turn_started = started(entry.context) is True
+ probe = getattr(self.controller, "backend_alive", None) if self.controller is not None else None
+ if native_turn_started and callable(probe):
+ try:
+ backend_alive = probe(entry.context)
+ except Exception:
+ logger.debug("turn_state: backend liveness probe failed", exc_info=True)
+ coalesced = payload.get("coalesced_queue")
+ owner_run_ids = (
+ [str(value) for value in coalesced.get("execution_ids", []) if str(value or "").strip()]
+ if isinstance(coalesced, dict) and isinstance(coalesced.get("execution_ids"), list)
+ else []
+ )
+ owner_run_id = str(payload.get("task_execution_id") or "").strip()
+ if owner_run_id and owner_run_id not in owner_run_ids:
+ owner_run_ids.insert(0, owner_run_id)
+ owner = {
+ "source": str(payload.get("task_trigger_kind") or payload.get("turn_source") or "human"),
+ "acquired_at": entry.started_at or None,
+ "run_id": owner_run_id or None,
+ "run_ids": owner_run_ids,
+ "runtime_key": str(payload.get("agent_runtime_turn_key") or "").strip() or None,
+ "native_turn_started": native_turn_started,
+ "backend_alive": backend_alive,
+ }
pending_input_count = 0
harness_activities: list[dict[str, Any]] = []
try:
@@ -1170,6 +1334,8 @@ class SessionTurnManager:
}
if backend:
result["backend"] = backend
+ if owner is not None:
+ result["owner"] = owner
return result
async def release_for_backend_refresh(
@@ -1498,7 +1664,11 @@ class SessionTurnManager:
# roll the sink back so it doesn't leak, and skip FSM registration.
self.pop_turn_sink(session_key, done)
return False
- self.in_flight[session_id] = Turn(task=task, context=context)
+ self.in_flight[session_id] = Turn(
+ task=task,
+ context=context,
+ started_at=_utc_now_iso(),
+ )
bus.publish("turn.start", {"session_id": session_id})
if self._pop_context_flag(context, _SHOW_CHECKPOINT_DEFERRED_START_KEY):
self._begin_show_checkpoint(context)
diff --git a/docs/plans/harness-session-failure-recovery.md b/docs/plans/harness-session-failure-recovery.md
new file mode 100644
index 000000000..a2c482029
--- /dev/null
+++ b/docs/plans/harness-session-failure-recovery.md
@@ -0,0 +1,99 @@
+# Harness Session Failure Recovery
+
+## Background
+
+Issue #915 reports a direct Agent Run queued on one long-lived Session while
+other Sessions continue normally. The first lease hypothesis is wrong:
+the scheduler's per-session reservation is process-local and is released when
+its short dispatch task returns. A Workbench turn then has two longer-lived
+owners:
+
+1. `SessionTurnManager.in_flight`, which holds the Session FSM until a terminal
+ result completes the dispatch sink.
+2. `AgentService._turn_gates`, which holds the backend runtime FIFO from backend
+ acceptance until that same terminal result.
+
+Two missing convergence edges reproduce the failure family:
+
+1. The pre-fix `HFR-002` fault injection proves that an accepted backend can
+ die without producing a terminal result. The backend liveness probe reports
+ `False`, but no owner consumes that fact, so both live owners remain held.
+2. The pre-fix Incus `HFR-004` restart proves the exact no-visible-owner symptom.
+ The old owner reaches a terminal Run state, but its queued successor remains
+ represented by both a Workbench queue row and a queued Run carrying
+ `workbench_queue_holds_run`. The scheduler deliberately excludes that Run
+ because the Session FSM owns its FIFO position, while the restarted FSM has
+ no boot edge that re-enters the persisted queue.
+
+No stale scheduler lease is involved in either case.
+
+## Goal
+
+Convert definitive loss of the backend runtime into the same idempotent silent
+terminal event used by every normal failure path. Preserve unlimited duration
+for live Agents, FIFO order, one turn per Session, and current restart/cancel
+semantics.
+
+## Design
+
+- Keep `AgentService` as the backend-runtime owner. Once a backend explicitly
+ marks a turn accepted, supervise that exact runtime-key/token pair.
+- Recover only after the backend-specific probe returns `False` twice around a
+ short race grace period. `True` and `None` are never recoverable states.
+- Emit one silent failed terminal result while the token is still current.
+ Existing outbound handling atomically settles the Run, signals the Session
+ sink, releases the runtime gate, flushes the persisted Workbench queue, and
+ drains callbacks.
+- Token identity, not PID or age, guards recovery. A released or superseded
+ token makes the supervisor a no-op, preventing PID reuse and late-result
+ races from affecting a newer turn.
+- Capture backend liveness at acceptance against the concrete transport or
+ receiver-task generation that owns the turn. A replacement runtime for the
+ same cwd/session key cannot make the old accepted owner appear alive.
+- Extend the existing Session FSM projection with authoritative live ownership:
+ owner source/run id, acquired time, backend, acceptance, and backend liveness.
+ `vibe runs show` may attach this live projection; it is diagnostic only and is
+ not a second recovery source.
+- On controller boot, re-enter only when the queue head is a persisted
+ Workbench-held row that names a still-queued Agent Run. A per-Session
+ recovery lock makes this idempotent.
+ If an older scheduler-owned Run is queued, defer to it; its normal terminal
+ or synchronous completion then asks the FSM to recover the successor. A
+ user-owned queue head remains untouched even if a held Agent Run is behind
+ it, preserving the explicit Stop contract.
+- Codex liveness remains positive while an already-read notification is queued
+ or being delivered, so recovery cannot overtake a delayed normal terminal.
+
+## Fault Matrix
+
+| ID | Boundary | Expected result |
+| --- | --- | --- |
+| HFR-001 | Failure before backend acceptance | Existing exception/terminal path fails the Run and releases the FIFO |
+| HFR-002 | Backend exits after acceptance, before terminal delivery | Definitive liveness loss fails owner once and starts queued successor once |
+| HFR-003 | Scheduler execution canceled while claimed | Claimed Run returns to queued and the process-local Session reservation releases |
+| HFR-004 | Controller restarts with running Run and persisted queued work | Startup re-enters the persisted FSM queue after any older Run settles; pure user queues stay parked |
+| HFR-005 | Live long-running backend exceeds all probe intervals | Owner remains protected regardless of age |
+| HFR-006 | Liveness false blip or unknown state | No recovery unless the same token is definitively dead after grace |
+| HFR-007 | Late terminal after recovery | Token guard drops it; Run/callback and successor remain exactly once |
+| HFR-008 | User cancel and restart overlap | Terminal/cancel idempotency prevents duplicate turn or callback |
+
+## Real Regression
+
+Repository-managed local Incus Worktree target
+`fix-session-queue-recove-ca3d3d2f` supplied both black-box proofs:
+
+- Backend death: Session `ses7dr38p3qsp`, owner Run `91962dcd8f50`, successor
+ `ef4b716f05e1`. At `05:05:53.727Z`, after live owner diagnostics reported
+ `native_turn_started=true` and `backend_alive=true`, SIGKILL targeted only
+ Codex PGID 8205. The owner failed at `05:05:54.756Z` with
+ `backend_runtime_exited_before_terminal`; the successor started at
+ `05:05:54.761Z`, completed once, and left an empty queue.
+- Restart pre-fix: Session `sesswwbh4da32`, owner Run `fae757453b2b`, successor
+ `3838c93fbfaa`. The service restarted at `05:08:19.393Z`; the owner became
+ terminal, but the successor and its queue row were still queued at
+ `05:20:48Z`. With the fix synced into the same preserved environment, boot
+ logged persisted-queue recovery at `05:21:14.433Z`; the same successor
+ started once at `05:21:14.428Z`, completed once at `05:21:35.520Z`, and the
+ queue became empty.
+
+No host Avibe service or remote Incus environment was touched.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 8f2dc55b3..fbb13a85b 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -7,7 +7,7 @@ import logging
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from modules.im import MessageContext
from modules.im.base import FileAttachment
@@ -137,6 +137,19 @@ class BaseAgent(ABC):
"""
return None
+ def capture_backend_liveness(
+ self,
+ context: Any,
+ ) -> Callable[[], Optional[bool]]:
+ """Capture the liveness authority for the runtime accepting this turn.
+
+ Backends whose runtime identity can be replaced while a turn is still
+ settling must override this and bind the concrete process/task
+ generation. The default preserves the conservative legacy probe.
+ """
+
+ return lambda: self.backend_alive(context)
+
def mark_runtime_turn_started(self, context: Any) -> None:
"""Mark the current gated turn as accepted by the backend runtime.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index fd93fcbd4..eed644bd5 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -144,7 +144,6 @@ class ClaudeAgent(BaseAgent):
message = self._prepare_message_with_files(request)
await client.query(message, session_id=runtime_session_key)
- self.mark_runtime_turn_started(context)
if (
runtime_session_key not in self.receiver_tasks
or self.receiver_tasks[runtime_session_key].done()
@@ -158,6 +157,7 @@ class ClaudeAgent(BaseAgent):
composite_key=runtime_session_key,
)
)
+ self.mark_runtime_turn_started(context)
turn_registered = True
logger.info(f"Sent message to Claude for session {runtime_session_key}")
@@ -247,6 +247,16 @@ class ClaudeAgent(BaseAgent):
return None
return not task.done()
+ def capture_backend_liveness(self, context) -> Callable[[], Optional[bool]]:
+ """Bind liveness to the receiver task generation accepting this turn."""
+
+ payload = getattr(context, "platform_specific", None) or {}
+ key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()
+ task = self.receiver_tasks.get(key) if key else None
+ if task is None:
+ return lambda: None
+ return lambda: not task.done()
+
async def _handle_question_callback(self, request: AgentRequest) -> None:
"""Handle question-related callbacks (button clicks, modal submissions).
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index d4caf4f2a..acb997917 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -8,7 +8,7 @@ import os
import shlex
import time
from pathlib import Path
-from typing import Any, Dict, Optional
+from typing import Any, Callable, Dict, Optional
from config import paths
from config.v2_config import (
@@ -117,11 +117,32 @@ class CodexAgent(BaseAgent):
transport = self._transports.get(cwd)
if transport is None:
return None
+ return self._transport_alive(transport)
+
+ @staticmethod
+ def _transport_alive(transport: CodexTransport) -> Optional[bool]:
try:
- return bool(transport.is_alive)
+ return bool(
+ transport.is_alive
+ or getattr(transport, "has_pending_notifications", False)
+ )
except Exception:
return None
+ def capture_backend_liveness(
+ self,
+ context: Any,
+ ) -> Callable[[], Optional[bool]]:
+ """Bind liveness to the app-server generation that accepted the turn."""
+
+ payload = getattr(context, "platform_specific", None) or {}
+ base_session_id = str(payload.get("turn_base_session_id") or "").strip()
+ cwd = self._session_mgr.get_cwd(base_session_id) if base_session_id else None
+ transport = self._transports.get(cwd) if cwd else None
+ if transport is None:
+ return lambda: None
+ return lambda: self._transport_alive(transport)
+
async def handle_message(self, request: AgentRequest) -> None:
"""Process a user message by routing it through app-server.
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index ed2441df0..08fd646ef 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -49,6 +49,7 @@ class CodexTransport:
# Ordered notification queue
self._notify_queue: asyncio.Queue[tuple[str, dict[str, Any]]] = asyncio.Queue()
self._notify_task: Optional[asyncio.Task[None]] = None
+ self._notify_inflight = 0
# ------------------------------------------------------------------
# Lifecycle
@@ -167,6 +168,12 @@ class CodexTransport:
def is_initialized(self) -> bool:
return self._initialized and self.is_alive
+ @property
+ def has_pending_notifications(self) -> bool:
+ """Whether an already-read notification can still deliver a terminal."""
+
+ return self._notify_inflight > 0 or not self._notify_queue.empty()
+
@property
def pid(self) -> Optional[int]:
"""OS pid of the codex app-server subprocess, or ``None`` if not running.
@@ -328,11 +335,14 @@ class CodexTransport:
try:
while True:
method, params = await self._notify_queue.get()
+ self._notify_inflight += 1
try:
assert self._notification_cb is not None
await self._notification_cb(method, params)
except Exception:
logger.exception("Error in notification handler for %s", method)
+ finally:
+ self._notify_inflight -= 1
except asyncio.CancelledError:
return
diff --git a/modules/agents/service.py b/modules/agents/service.py
index acfdf5133..c5b212e37 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -2,7 +2,7 @@ import logging
import asyncio
import uuid
from dataclasses import dataclass, field
-from typing import Any, Dict, Optional
+from typing import Any, Callable, Dict, Optional
from core.session_activities import SessionActivityRegistry
from core.message_output import terminal_output_for, terminal_turn_output
@@ -23,6 +23,13 @@ STALE_STOP_REASONS = {"not_active", "runtime_unavailable"}
class AgentService:
"""Registry and dispatcher for agent implementations."""
+ # These clocks never decide that a turn is old. They only pace a positive
+ # backend-liveness probe and confirm one definitive False result across the
+ # small process-exit/terminal-delivery race window.
+ _liveness_probe_interval_seconds = 1.0
+ _liveness_failure_grace_seconds = 0.5
+ _backend_exit_terminal_error = "backend_runtime_exited_before_terminal"
+
def __init__(
self,
controller,
@@ -208,6 +215,7 @@ class AgentService:
gate.runtime_started = False
gate.task = asyncio.current_task()
gate.context = request.context
+ gate.request = request
gate.cancel_tidy_task = None
self._stamp_runtime_turn(request, runtime_key, gate.token)
try:
@@ -383,6 +391,153 @@ class AgentService:
if gate is None or gate.token != runtime_token:
return
gate.runtime_started = True
+ gate.liveness_probe = self._capture_backend_liveness(gate, context)
+ self._start_runtime_liveness_monitor(runtime_key, gate, runtime_token)
+
+ def _capture_backend_liveness(
+ self,
+ gate: "_RuntimeTurnGate",
+ context: Any,
+ ) -> Callable[[], Optional[bool]]:
+ capture = getattr(gate.agent, "capture_backend_liveness", None)
+ if callable(capture):
+ try:
+ probe = capture(context)
+ if callable(probe):
+ return probe
+ except Exception:
+ logger.debug(
+ "Failed to capture backend liveness for %s",
+ gate.backend,
+ exc_info=True,
+ )
+ return lambda: self.backend_alive(context, use_captured=False)
+
+ @staticmethod
+ def _probe_backend_liveness(
+ probe: Callable[[], Optional[bool]] | None,
+ ) -> Optional[bool]:
+ if probe is None:
+ return None
+ try:
+ return probe()
+ except Exception:
+ logger.debug("Captured backend liveness probe raised", exc_info=True)
+ return None
+
+ def _start_runtime_liveness_monitor(
+ self,
+ runtime_key: str,
+ gate: "_RuntimeTurnGate",
+ runtime_token: str,
+ ) -> None:
+ existing = gate.liveness_task
+ if existing is not None and not existing.done():
+ return
+ try:
+ loop = asyncio.get_running_loop()
+ task = loop.create_task(
+ self._monitor_runtime_liveness(runtime_key, runtime_token),
+ name=f"agent-runtime-liveness:{gate.backend}:{runtime_key}",
+ )
+ except RuntimeError:
+ # mark_runtime_turn_started is normally called on the controller loop.
+ # A synchronous unit/stub caller has no runtime to supervise.
+ return
+ gate.liveness_task = task
+ self._background_tasks.add(task)
+
+ def _finished(finished: asyncio.Task) -> None:
+ self._background_tasks.discard(finished)
+ current = self._turn_gates.get(runtime_key)
+ if current is not None and current.token == runtime_token and current.liveness_task is finished:
+ current.liveness_task = None
+ if finished.cancelled():
+ return
+ try:
+ error = finished.exception()
+ except asyncio.CancelledError:
+ return
+ if error is not None:
+ logger.error(
+ "Runtime liveness monitor crashed for backend=%s runtime=%s: %r",
+ gate.backend,
+ runtime_key,
+ error,
+ exc_info=error,
+ )
+
+ task.add_done_callback(_finished)
+
+ async def _monitor_runtime_liveness(self, runtime_key: str, runtime_token: str) -> None:
+ """Turn a definitive owned-backend death into the normal terminal path.
+
+ Age is deliberately absent. A live or unknown backend may run forever.
+ Recovery requires the same runtime-key/token owner and two definitive
+ ``False`` probes around a short grace period; a terminal event or newer
+ turn changes the token and makes this monitor a no-op.
+ """
+
+ while True:
+ await asyncio.sleep(self._liveness_probe_interval_seconds)
+ gate = self._turn_gates.get(runtime_key)
+ if gate is None or gate.token != runtime_token or not gate.runtime_started:
+ return
+ if gate.context is None or self._probe_backend_liveness(gate.liveness_probe) is not False:
+ continue
+
+ await asyncio.sleep(self._liveness_failure_grace_seconds)
+ gate = self._turn_gates.get(runtime_key)
+ if gate is None or gate.token != runtime_token or not gate.runtime_started:
+ return
+ context = gate.context
+ if context is None or self._probe_backend_liveness(gate.liveness_probe) is not False:
+ continue
+
+ logger.error(
+ "Accepted Agent turn lost its owned backend before terminal delivery "
+ "(backend=%s runtime=%s)",
+ gate.backend,
+ runtime_key,
+ )
+ emit = getattr(self.controller, "emit_agent_message", None)
+ if not callable(emit):
+ logger.error(
+ "Cannot recover dead backend turn because the terminal emitter is unavailable "
+ "(backend=%s runtime=%s)",
+ gate.backend,
+ runtime_key,
+ )
+ continue
+ try:
+ output = (
+ terminal_output_for(gate.request)
+ if gate.request is not None
+ else terminal_turn_output()
+ )
+ await emit(
+ context,
+ "result",
+ "",
+ is_error=True,
+ level="silent",
+ output=output,
+ terminal_error=self._backend_exit_terminal_error,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ # Do not release only half of the ownership graph. Retrying the
+ # idempotent terminal chokepoint is safer than freeing the runtime
+ # gate while the Session sink or Run row may still be active.
+ logger.exception(
+ "Failed to converge dead backend turn through terminal delivery "
+ "(backend=%s runtime=%s)",
+ gate.backend,
+ runtime_key,
+ )
+ continue
+ return
def runtime_turn_started(self, context: Any) -> bool:
payload = getattr(context, "platform_specific", None) or {}
@@ -458,6 +613,9 @@ class AgentService:
await gate.lock.acquire()
gate.token = uuid.uuid4().hex
gate.backend = agent_name
+ gate.agent = self.agents.get(agent_name)
+ gate.context = context
+ gate.request = None
# The backend already produced output, so the turn is unambiguously
# running — there is no queued-startup window to distinguish (unlike a
# user turn waiting on the gate), so mark it started immediately.
@@ -466,6 +624,8 @@ class AgentService:
context.platform_specific = {}
context.platform_specific[AGENT_RUNTIME_TURN_KEY] = runtime_key
context.platform_specific[AGENT_RUNTIME_TURN_TOKEN] = gate.token
+ gate.liveness_probe = self._capture_backend_liveness(gate, context)
+ self._start_runtime_liveness_monitor(runtime_key, gate, gate.token)
# Fresh streaming token too: the previous turn's SSE sink is already gone,
# and a leftover ``turn_token`` would only confuse ``mark_turn_complete``
# (which no-ops anyway with no live sink for this session).
@@ -509,12 +669,23 @@ class AgentService:
return
if runtime_token is not None and gate.token != runtime_token:
return
+ liveness_task = gate.liveness_task
+ gate.liveness_task = None
gate.token = ""
gate.backend = ""
gate.runtime_started = False
gate.agent = None
gate.task = None
gate.context = None
+ gate.request = None
+ gate.liveness_probe = None
+ if liveness_task is not None and not liveness_task.done():
+ try:
+ current = asyncio.current_task()
+ except RuntimeError:
+ current = None
+ if liveness_task is not current:
+ liveness_task.cancel()
if gate.lock.locked():
gate.lock.release()
@@ -569,13 +740,29 @@ class AgentService:
gate = self._turn_gates.get(runtime_key)
return gate is not None and gate.token == runtime_token
- def backend_alive(self, context: Any) -> Optional[bool]:
+ def backend_alive(
+ self,
+ context: Any,
+ *,
+ use_captured: bool = True,
+ ) -> Optional[bool]:
"""Resolve the backend for this turn (via its runtime gate) and ask it
whether it is still alive. Returns ``None`` when the backend is unknown
or has no probe — callers treat ``None`` as alive (no false alarm)."""
payload = getattr(context, "platform_specific", None) or {}
runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()
gate = self._turn_gates.get(runtime_key) if runtime_key else None
+ runtime_token = str(payload.get(AGENT_RUNTIME_TURN_TOKEN) or "").strip()
+ if (
+ use_captured
+ and gate is not None
+ and runtime_token
+ and gate.token == runtime_token
+ and getattr(gate, "runtime_started", False)
+ ):
+ return self._probe_backend_liveness(
+ getattr(gate, "liveness_probe", None)
+ )
backend = gate.backend if gate else None
agent = getattr(gate, "agent", None) if gate is not None else None
if agent is None and backend:
@@ -691,4 +878,7 @@ class _RuntimeTurnGate:
agent: BaseAgent | None = None
task: asyncio.Task | None = None
context: Any = None
+ request: AgentRequest | None = None
+ liveness_probe: Callable[[], Optional[bool]] | None = None
cancel_tidy_task: asyncio.Task | None = None
+ liveness_task: asyncio.Task | None = None
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 8d3e9e487..4e481226c 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -627,6 +627,19 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+def list_queued_session_ids(conn: Connection) -> list[str]:
+ """Session ids with persisted queue rows, ordered by their oldest row."""
+
+ query = (
+ select(messages.c.session_id)
+ .where(messages.c.session_id.is_not(None))
+ .where(messages.c.type == QUEUED_TYPE)
+ .group_by(messages.c.session_id)
+ .order_by(func.min(messages.c.created_at), func.min(messages.c.id))
+ )
+ return [str(session_id) for session_id in conn.execute(query).scalars() if session_id]
+
+
def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
"""Claim the session's queued messages: read them (oldest first), then delete
them in the SAME transaction, so the rows are returned exactly once. Empty
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 0ae521ab1..2f59953e4 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -8,6 +8,19 @@ navigation:
- Read that capability's observations.yaml.
- Read the listed scenario test files before changing production code.
capabilities:
+ - id: harness_failure_recovery
+ name: Harness per-Session failure recovery
+ status: active
+ catalog: tests/scenarios/harness_failure_recovery/catalog.yaml
+ observations: tests/scenarios/harness_failure_recovery/observations.yaml
+ scenario_tests:
+ - tests/test_agent_service.py
+ - tests/test_scheduled_tasks.py
+ unit_or_contract_tests:
+ - tests/test_cli_task_command.py
+ - tests/test_cli_pagination.py
+ - tests/test_codex_transport.py
+ - tests/test_internal_server.py
- id: auth_setup
name: IM-driven backend auth recovery
status: active
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
new file mode 100644
index 000000000..d7740af8e
--- /dev/null
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -0,0 +1,73 @@
+version: 1
+capability:
+ id: harness_failure_recovery
+ name: Harness per-Session failure recovery
+ canonical_tests:
+ - tests/test_agent_backend_alive.py
+ - tests/test_agent_service.py
+ - tests/test_scheduled_tasks.py
+ shared_harness: []
+status_legend:
+ covered: deterministic scenario or contract coverage exists
+ manual: validated in the local Incus black-box environment
+scenarios:
+ - id: HFR-001
+ name: failure before backend acceptance releases ownership
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_agent_service.py::test_agent_service_releases_gate_when_exception_terminal_emit_fails
+ - id: HFR-002
+ name: accepted backend generation death releases owner and dispatches successor once
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_dead_accepted_owner_converges_run_session_and_persisted_fifo
+ - id: HFR-003
+ name: canceled scheduler execution requeues its claimed Run
+ status: covered
+ kind: cancellation
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_drain_requests_requeues_cancelled_task_run
+ - id: HFR-004
+ name: restart recovers held run queues without flushing user-owned queue heads
+ status: covered
+ kind: restart
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settles
+ - id: HFR-005
+ name: live long-running owner is never stolen by age
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_agent_service.py::test_agent_service_never_steals_live_or_unknown_long_running_owner
+ - id: HFR-006
+ name: transient or unknown liveness does not release ownership
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_agent_service.py::test_agent_service_requires_dead_backend_after_grace_before_recovery
+ - id: HFR-007
+ name: late terminal cannot release or settle a successor
+ status: covered
+ kind: idempotency
+ layer: contract
+ backend: shared
+ test: tests/test_agent_service.py::test_late_terminal_from_recovered_owner_cannot_release_successor
+ - id: HFR-008
+ name: cancel and restart remain idempotent
+ status: covered
+ kind: idempotency
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_failed_run_records_error_and_enqueues_one_terminal_callback
+manual_evidence:
+ - local Incus backend process death after prompt acceptance
+ - local Incus controller restart with persisted queued successor
+plan: docs/plans/harness-session-failure-recovery.md
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
new file mode 100644
index 000000000..5b4a55389
--- /dev/null
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -0,0 +1,65 @@
+version: 1
+capability: harness_failure_recovery
+observations:
+ - id: HFR-OBS-001
+ date: 2026-07-18
+ source: deterministic pre-fix fault injection
+ result: confirmed
+ detail: >-
+ After backend acceptance, a definitive backend_alive false result was
+ observable but had no lifecycle consumer. The AgentService runtime gate
+ remained locked and a same-runtime successor timed out waiting. The
+ scheduler execution and its per-session reservation had already returned.
+ - id: HFR-OBS-002
+ date: 2026-07-18
+ source: code-path trace
+ result: confirmed
+ detail: >-
+ A silent terminal result is the existing shared idempotent convergence
+ point: it settles the Run, signals the Session sink, releases the runtime
+ token, flushes the persisted Workbench queue, and enables callback drain.
+ - id: HFR-OBS-003
+ date: 2026-07-18
+ source: local Incus pre-fix controller restart
+ result: confirmed
+ detail: >-
+ Session sesswwbh4da32 lost its in-memory owner on restart. Owner Run
+ fae757453b2b became terminal, while successor 3838c93fbfaa remained queued
+ with its Workbench queue row for more than twelve minutes. No running Run
+ or live Session owner remained. The scheduler correctly excluded the held
+ Run, but the restarted Session FSM never re-entered its durable queue.
+ - id: HFR-OBS-004
+ date: 2026-07-18
+ source: local Incus post-fix controller restart
+ result: passed
+ detail: >-
+ With state preserved, boot recovered Session sesswwbh4da32 at
+ 05:21:14Z. The exact successor Run 3838c93fbfaa started once, completed
+ once with HFR915_RR_SECOND_DONE, recorded one output, and emptied the
+ queue.
+ - id: HFR-OBS-005
+ date: 2026-07-18
+ source: local Incus Codex process-group kill
+ result: passed
+ detail: >-
+ Session ses7dr38p3qsp owned Codex PGID 8205 after prompt acceptance.
+ SIGKILL at 05:05:53.727Z failed owner Run 91962dcd8f50 through the shared
+ terminal path, then successor ef4b716f05e1 started once, completed once,
+ recorded one output, and emptied the persisted queue.
+ - id: HFR-OBS-006
+ date: 2026-07-18
+ source: deterministic ownership-generation fault injection
+ result: confirmed
+ detail: >-
+ A replacement runtime under the same cwd or session key can be alive
+ while the transport or receiver task that accepted an older turn is
+ dead. Recovery and diagnostics must therefore use the liveness probe
+ captured from the concrete accepted generation.
+ - id: HFR-OBS-007
+ date: 2026-07-18
+ source: deterministic mixed-queue fault injection
+ result: confirmed
+ detail: >-
+ A user queue row preserved by explicit Stop can precede a held Agent Run
+ row. Startup recovery must not call the generic FIFO flush until the
+ eligible held Agent Run segment itself is at the queue head.
diff --git a/tests/test_agent_backend_alive.py b/tests/test_agent_backend_alive.py
index 33e78f19b..678074f42 100644
--- a/tests/test_agent_backend_alive.py
+++ b/tests/test_agent_backend_alive.py
@@ -56,6 +56,17 @@ class ClaudeBackendAliveTests(unittest.TestCase):
agent = self._agent({"k1": _Task(done=False)})
self.assertIsNone(agent.backend_alive(_ctx(None)))
+ def test_captured_probe_stays_bound_to_receiver_generation(self):
+ accepted = _Task(done=False)
+ agent = self._agent({"k1": accepted})
+ probe = agent.capture_backend_liveness(_ctx("k1"))
+
+ accepted._done = True
+ agent.receiver_tasks["k1"] = _Task(done=False)
+
+ self.assertIs(agent.backend_alive(_ctx("k1")), True)
+ self.assertIs(probe(), False)
+
class CodexBackendAliveTests(unittest.TestCase):
def _agent(self, *, cwd_for_session, transports):
@@ -96,6 +107,27 @@ class CodexBackendAliveTests(unittest.TestCase):
agent = self._agent(cwd_for_session={"b1": "/repo"}, transports={})
self.assertIsNone(agent.backend_alive(self._ctx_base(None)))
+ def test_captured_probe_stays_bound_to_transport_generation(self):
+ accepted = types.SimpleNamespace(
+ is_alive=True,
+ has_pending_notifications=False,
+ )
+ agent = self._agent(
+ cwd_for_session={"b1": "/repo"},
+ transports={"/repo": accepted},
+ )
+ context = self._ctx_base("b1")
+ probe = agent.capture_backend_liveness(context)
+
+ accepted.is_alive = False
+ agent._transports["/repo"] = types.SimpleNamespace(
+ is_alive=True,
+ has_pending_notifications=False,
+ )
+
+ self.assertIs(agent.backend_alive(context), True)
+ self.assertIs(probe(), False)
+
class AgentServiceBackendAliveTests(unittest.TestCase):
def _service(self, *, backend_name, gate_backend, probe_return):
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index b8430be3f..e8878f259 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import sys
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -10,6 +11,7 @@ import pytest
from core.message_output import terminal_turn_output
from core.session_activities import SessionActivityRegistry
from modules.agents.service import AgentService
+from modules.agents.codex.transport import CodexTransport
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.session_activities import SQLiteSessionActivityStore
@@ -1137,6 +1139,8 @@ def test_agent_service_schedules_terminal_tidy_on_cancellation() -> None:
def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> None:
+ """HFR-001: pre-accept failure releases ownership even if terminal emit fails."""
+
async def _run():
controller = _Controller()
@@ -1159,3 +1163,335 @@ def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> Non
assert not service._turn_gates["session:/repo"].lock.locked()
asyncio.run(_run())
+
+
+def test_agent_service_recovers_accepted_turn_when_owned_backend_dies() -> None:
+ """A dead accepted backend must release the runtime FIFO without a timeout."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ recovered = asyncio.Event()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+
+ class _AcceptedThenDeadAgent(_RuntimeAgent):
+ def __init__(self) -> None:
+ super().__init__()
+ self.alive = True
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return self.alive
+
+ agent = _AcceptedThenDeadAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.01
+ service._liveness_failure_grace_seconds = 0.02
+
+ async def _emit(context, message_type, text, **kwargs):
+ assert message_type == "result"
+ assert text == ""
+ assert kwargs["is_error"] is True
+ assert kwargs["level"] == "silent"
+ assert kwargs["terminal_error"] == "backend_runtime_exited_before_terminal"
+ service.release_runtime_turn(context)
+ recovered.set()
+
+ controller.emit_agent_message = _emit
+
+ first = _request("first")
+ second = _request("second")
+ await service.handle_message("claude", first)
+ assert service._turn_gates["session:/repo"].lock.locked()
+
+ successor = asyncio.create_task(service.handle_message("claude", second))
+ await asyncio.sleep(0)
+ assert agent.started == ["first"]
+
+ agent.alive = False
+ try:
+ await asyncio.wait_for(recovered.wait(), timeout=0.5)
+ await asyncio.wait_for(successor, timeout=0.5)
+ assert agent.started == ["first", "second"]
+ finally:
+ if not successor.done():
+ successor.cancel()
+ await asyncio.gather(successor, return_exceptions=True)
+ service.release_runtime_turn(second.context)
+
+ asyncio.run(_run())
+
+
+def test_agent_service_recovery_uses_the_accepted_backend_generation() -> None:
+ """HFR-002: a replacement runtime cannot hide the accepted owner's death."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ recovered = asyncio.Event()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+
+ class _GenerationAgent(_RuntimeAgent):
+ def __init__(self) -> None:
+ super().__init__()
+ self.current = SimpleNamespace(alive=True)
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return self.current.alive
+
+ def capture_backend_liveness(self, _context):
+ accepted = self.current
+ return lambda: accepted.alive
+
+ agent = _GenerationAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.005
+ service._liveness_failure_grace_seconds = 0.005
+
+ async def _emit(context, *_args, **_kwargs):
+ service.release_runtime_turn(context)
+ recovered.set()
+
+ controller.emit_agent_message = _emit
+ first = _request("first")
+ second = _request("second")
+ await service.handle_message("claude", first)
+ accepted = agent.current
+ successor = asyncio.create_task(service.handle_message("claude", second))
+ await asyncio.sleep(0)
+
+ agent.current = SimpleNamespace(alive=True)
+ accepted.alive = False
+ try:
+ await asyncio.wait_for(recovered.wait(), timeout=0.5)
+ await asyncio.wait_for(successor, timeout=0.5)
+ assert agent.started == ["first", "second"]
+ assert service.backend_alive(second.context) is True
+ finally:
+ if not successor.done():
+ successor.cancel()
+ await asyncio.gather(successor, return_exceptions=True)
+ service.release_runtime_turn(second.context)
+
+ asyncio.run(_run())
+
+
[email protected]("liveness", [True, None])
+def test_agent_service_never_steals_live_or_unknown_long_running_owner(liveness) -> None:
+ """HFR-005/HFR-006: age alone never releases a live or unknown owner."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ controller.emit_agent_message = AsyncMock(side_effect=AssertionError("live owner was stolen"))
+
+ class _LongRunningAgent(_RuntimeAgent):
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return liveness
+
+ agent = _LongRunningAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.005
+ service._liveness_failure_grace_seconds = 0.005
+
+ first = _request("first")
+ second = _request("second")
+ await service.handle_message("claude", first)
+ successor = asyncio.create_task(service.handle_message("claude", second))
+ try:
+ await asyncio.sleep(0.06)
+ assert agent.started == ["first"]
+ assert not successor.done()
+ controller.emit_agent_message.assert_not_awaited()
+
+ service.release_runtime_turn(first.context)
+ await asyncio.wait_for(successor, timeout=0.5)
+ assert agent.started == ["first", "second"]
+ finally:
+ if not successor.done():
+ successor.cancel()
+ await asyncio.gather(successor, return_exceptions=True)
+ service.release_runtime_turn(second.context)
+
+ asyncio.run(_run())
+
+
+def test_agent_service_requires_dead_backend_after_grace_before_recovery() -> None:
+ """HFR-006: a transient false probe cannot release the accepted owner."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+ controller.emit_agent_message = AsyncMock(side_effect=AssertionError("false blip stole the owner"))
+
+ class _FlappingAgent(_RuntimeAgent):
+ alive = True
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return self.alive
+
+ agent = _FlappingAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.005
+ service._liveness_failure_grace_seconds = 0.04
+
+ request = _request("first")
+ await service.handle_message("claude", request)
+ agent.alive = False
+ await asyncio.sleep(0.015)
+ agent.alive = True
+ await asyncio.sleep(0.06)
+
+ assert service._turn_gates["session:/repo"].lock.locked()
+ assert service.runtime_turn_started(request.context) is True
+ controller.emit_agent_message.assert_not_awaited()
+ service.release_runtime_turn(request.context)
+
+ asyncio.run(_run())
+
+
+def test_late_terminal_from_recovered_owner_cannot_release_successor() -> None:
+ """HFR-007: token identity makes dead-owner recovery and late results idempotent."""
+
+ async def _run() -> None:
+ controller = _Controller()
+ recovered = asyncio.Event()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+
+ class _RecoveringAgent(_RuntimeAgent):
+ alive = True
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return self.alive
+
+ agent = _RecoveringAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.005
+ service._liveness_failure_grace_seconds = 0.005
+ terminal_calls = 0
+
+ async def _emit(context, *_args, **_kwargs):
+ nonlocal terminal_calls
+ terminal_calls += 1
+ service.release_runtime_turn(context)
+ recovered.set()
+
+ controller.emit_agent_message = _emit
+ first = _request("first")
+ second = _request("second")
+ await service.handle_message("claude", first)
+ first_token = first.context.platform_specific["agent_runtime_turn_token"]
+ successor = asyncio.create_task(service.handle_message("claude", second))
+ agent.alive = False
+ try:
+ await asyncio.wait_for(recovered.wait(), timeout=0.5)
+ agent.alive = True
+ await asyncio.wait_for(successor, timeout=0.5)
+ gate = service._turn_gates["session:/repo"]
+ successor_token = gate.token
+ assert successor_token and successor_token != first_token
+
+ # The old context still carries the old token. A delayed result's
+ # normal release hook must not touch the successor owner.
+ service.release_runtime_turn(first.context)
+ assert gate.token == successor_token
+ assert gate.lock.locked()
+ assert terminal_calls == 1
+ finally:
+ if not successor.done():
+ successor.cancel()
+ await asyncio.gather(successor, return_exceptions=True)
+ service.release_runtime_turn(second.context)
+
+ asyncio.run(_run())
+
+
+def test_real_child_exit_after_acceptance_recovers_runtime_fifo() -> None:
+ """HFR-002: an owned OS child exit drives the same shared recovery path."""
+
+ async def _run() -> None:
+ process = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "import time; time.sleep(60)",
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ transport = CodexTransport(binary=sys.executable, cwd="/")
+ transport._process = process
+ transport._reader_task = asyncio.create_task(transport._reader_loop())
+
+ controller = _Controller()
+ recovered = asyncio.Event()
+ service = AgentService(controller=controller)
+ controller.agent_service = service
+
+ class _ProcessBackedAgent(_RuntimeAgent):
+ name = "codex"
+
+ async def handle_message(self, request) -> None:
+ self.started.append(request.message)
+ service.mark_runtime_turn_started(request.context)
+
+ def backend_alive(self, _context):
+ return transport.is_alive
+
+ agent = _ProcessBackedAgent()
+ service.register(agent)
+ service._liveness_probe_interval_seconds = 0.005
+ service._liveness_failure_grace_seconds = 0.005
+ terminal_calls = 0
+
+ async def _emit(context, *_args, **_kwargs):
+ nonlocal terminal_calls
+ terminal_calls += 1
+ service.release_runtime_turn(context)
+ recovered.set()
+
+ controller.emit_agent_message = _emit
+ first = _request("first", runtime_key="codex:/repo")
+ second = _request("second", runtime_key="codex:/repo")
+ successor = None
+ try:
+ await service.handle_message("codex", first)
+ successor = asyncio.create_task(service.handle_message("codex", second))
+ process.kill()
+ await process.wait()
+ await transport._reader_task
+
+ await asyncio.wait_for(recovered.wait(), timeout=0.5)
+ await asyncio.wait_for(successor, timeout=0.5)
+ assert agent.started == ["first", "second"]
+ assert terminal_calls == 1
+ finally:
+ if process.returncode is None:
+ process.kill()
+ await process.wait()
+ if successor is not None and not successor.done():
+ successor.cancel()
+ await asyncio.gather(successor, return_exceptions=True)
+ service.release_runtime_turn(second.context)
+
+ asyncio.run(_run())
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 972d7703d..23dd1d661 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -178,6 +178,58 @@ def test_runs_show_defaults_to_caller_run(monkeypatch, tmp_path, capsys) -> None
}
+def test_runs_show_attaches_live_session_owner_for_queued_run(monkeypatch, tmp_path, capsys) -> None:
+ """HFR-002: CLI diagnosis names the authoritative live Session owner."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ store = SQLiteBackgroundTaskStore()
+ try:
+ store.enqueue_run(
+ {
+ "id": "run-queued",
+ "request_type": "agent_run",
+ "status": "queued",
+ "agent_name": "helper",
+ "agent_backend": "codex",
+ "session_id": "ses-alpha",
+ "message": "queued successor",
+ "created_at": "2026-07-18T04:31:27+00:00",
+ "updated_at": "2026-07-18T04:31:27+00:00",
+ }
+ )
+ finally:
+ store.close()
+
+ async def _turn_state(session_id):
+ assert session_id == "ses-alpha"
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "session_id": session_id,
+ "in_flight": True,
+ "owner": {
+ "source": "agent_run",
+ "run_id": "run-owner",
+ "acquired_at": "2026-07-18T04:31:26+00:00",
+ "native_turn_started": True,
+ "backend_alive": True,
+ },
+ },
+ }
+
+ monkeypatch.setattr("vibe.internal_client.turn_state", _turn_state)
+ args = cli.build_parser().parse_args(["runs", "show", "run-queued"])
+
+ assert cli.cmd_runs_show(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ runtime = payload["run"]["session_runtime"]
+ assert runtime["available"] is True
+ assert runtime["owner"]["run_id"] == "run-owner"
+ assert runtime["owner"]["backend_alive"] is True
+
+
def test_runs_show_requires_run_without_caller(monkeypatch, tmp_path, capsys) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)
diff --git a/tests/test_codex_transport.py b/tests/test_codex_transport.py
index 6d8080a63..9bf6a16bc 100644
--- a/tests/test_codex_transport.py
+++ b/tests/test_codex_transport.py
@@ -54,6 +54,30 @@ class CodexTransportHealthTests(unittest.IsolatedAsyncioTestCase):
with self.assertRaises(ConnectionError):
await transport.send_notification("initialized")
+ async def test_pending_notification_keeps_terminal_pipeline_alive(self):
+ transport = CodexTransport(binary="codex", cwd="/tmp")
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def handle(_method, _params):
+ started.set()
+ await release.wait()
+
+ transport._notification_cb = handle
+ transport._notify_task = asyncio.create_task(transport._notify_worker())
+ transport._notify_queue.put_nowait(("turn/completed", {}))
+ await started.wait()
+ try:
+ self.assertTrue(transport.has_pending_notifications)
+ self.assertTrue(transport._notify_queue.empty())
+ finally:
+ release.set()
+ await asyncio.sleep(0)
+ transport._notify_task.cancel()
+ await transport._notify_task
+
+ self.assertFalse(transport.has_pending_notifications)
+
def test_stream_buffer_limit_allows_large_codex_thread_responses(self):
self.assertGreaterEqual(STREAM_BUFFER_LIMIT, 128 * 1024 * 1024)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index c66b435f4..738001bda 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -1419,6 +1419,7 @@ def test_recover_processing_drops_completed_requests(tmp_path: Path) -> None:
def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
+ """HFR-003: cancellation requeues the claim and releases its Session slot."""
path = tmp_path / "scheduled_tasks.json"
request_store = TaskExecutionStore(tmp_path / "task_requests")
store = ScheduledTaskStore(path)
@@ -1455,6 +1456,9 @@ def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
pass
else:
raise AssertionError("expected CancelledError on the execution task")
+ await asyncio.sleep(0)
+ assert request.id not in service._inflight_executions
+ assert "key:slack::channel::C123" not in service._inflight_sessions
asyncio.run(_exercise())
@@ -1468,6 +1472,321 @@ def test_drain_requests_requeues_cancelled_task_run(tmp_path: Path) -> None:
assert not (request_store.completed_dir / f"{request.id}.json").exists()
+def test_restart_recovers_running_row_and_preserves_same_session_fifo(monkeypatch, tmp_path) -> None:
+ """HFR-004: a crash-held row restarts queued and each successor runs once."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ first = request_store.enqueue_agent_run(
+ session_id="ses-restart",
+ session_key="avibe::project::proj-restart",
+ message="first",
+ agent_name="codex",
+ )
+ second = request_store.enqueue_agent_run(
+ session_id="ses-restart",
+ session_key="avibe::project::proj-restart",
+ message="second",
+ agent_name="codex",
+ )
+ assert request_store.claim(first.id) is not None
+ assert request_store.get_run(first.id)["status"] == "running"
+
+ restarted_store = TaskExecutionStore()
+ controller = SimpleNamespace(platform_settings_managers={})
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=restarted_store,
+ )
+ assert [request.id for request in restarted_store.list_pending()] == [first.id, second.id]
+
+ async def _exercise() -> None:
+ started: list[str] = []
+ release_first = asyncio.Event()
+
+ async def _execute(request):
+ started.append(request.id)
+ if request.id == first.id:
+ await release_first.wait()
+ restarted_store.complete(request, ok=True)
+
+ service._execute_claimed_request = _execute # type: ignore[method-assign]
+ await service._drain_requests()
+ await asyncio.sleep(0)
+ assert started == [first.id]
+ assert restarted_store.get_run(second.id)["status"] == "queued"
+
+ release_first.set()
+ first_task = service._inflight_executions[first.id]
+ await first_task
+ await asyncio.sleep(0)
+ await service._drain_requests()
+ second_task = service._inflight_executions[second.id]
+ await second_task
+ assert started == [first.id, second.id]
+
+ asyncio.run(_exercise())
+ assert restarted_store.get_run(first.id)["status"] == "succeeded"
+ assert restarted_store.get_run(second.id)["status"] == "succeeded"
+
+
+def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settles(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """HFR-004: durable queue ownership resumes once an older Run is terminal."""
+
+ from core.session_turns import (
+ SCHEDULED_PROVENANCE_KEY,
+ SessionTurnManager,
+ capture_scheduled_provenance,
+ )
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ older = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="older recovered owner",
+ agent_name="codex",
+ )
+ successor = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="persisted successor",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+
+ queued_context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{successor.id}",
+ platform_specific={
+ "task_execution_id": successor.id,
+ "task_trigger_kind": "agent_run",
+ "vibe_agent_name": "codex",
+ "source_kind": "cli",
+ },
+ )
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ messages_service.append(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text="persisted successor",
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(
+ queued_context
+ )
+ },
+ native_message_id=f"agent_run:{successor.id}",
+ )
+
+ class _Controller:
+ def __init__(self) -> None:
+ self.session_turns = SessionTurnManager(
+ self,
+ build_context=self._build_context,
+ )
+ self.statuses: list[tuple[str, str]] = []
+
+ @staticmethod
+ def _build_context(target_session_id):
+ assert target_session_id == session_id
+ return MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": session_id,
+ "agent_session_target": {"agent_backend": "codex"},
+ },
+ )
+
+ def set_agent_status(self, target_session_id, status) -> None:
+ self.statuses.append((target_session_id, status))
+
+ controller = _Controller()
+ started: list[str] = []
+
+ async def _dispatch(_controller, context, _text, **_kwargs):
+ run_id = str((context.platform_specific or {}).get("task_execution_id") or "")
+ started.append(run_id)
+ sqlite_store.record_run_output(
+ run_id,
+ output_id="terminal",
+ text="recovered once",
+ terminal_status="succeeded",
+ )
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn", _dispatch)
+
+ async def _exercise() -> None:
+ # The older scheduler-owned Run keeps its original FIFO position.
+ assert await controller.session_turns.recover_persisted_agent_run_queue() == []
+ assert started == []
+ with engine.connect() as conn:
+ assert len(messages_service.list_queued(conn, session_id)) == 1
+
+ request_store.complete(older, ok=True)
+ assert await controller.session_turns.recover_persisted_agent_run_queue(
+ session_id
+ ) == [session_id]
+ for _ in range(100):
+ if session_id not in controller.session_turns.in_flight:
+ break
+ await asyncio.sleep(0.005)
+
+ assert started == [successor.id]
+ assert request_store.get_run(successor.id)["status"] == "succeeded"
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+
+ assert await controller.session_turns.recover_persisted_agent_run_queue(
+ session_id
+ ) == []
+ assert started == [successor.id]
+
+ asyncio.run(_exercise())
+ engine.dispose()
+
+
+def test_restart_does_not_auto_send_pure_user_queue(monkeypatch, tmp_path) -> None:
+ """HFR-004 safety: startup recovery is limited to durable Agent Run rows."""
+
+ from core.session_turns import SessionTurnManager
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="kept after explicit stop",
+ )
+
+ controller = SimpleNamespace()
+ manager = SessionTurnManager(
+ controller,
+ build_context=lambda _session_id: MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ ),
+ )
+ controller.session_turns = manager
+
+ assert asyncio.run(manager.recover_persisted_agent_run_queue()) == []
+ with engine.connect() as conn:
+ assert [row["text"] for row in messages_service.list_queued(conn, session_id)] == [
+ "kept after explicit stop"
+ ]
+ engine.dispose()
+
+
+def test_restart_does_not_flush_user_queue_ahead_of_held_agent_run(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """HFR-004 safety: recovery cannot bypass a stopped user-owned queue head."""
+
+ from core.session_turns import (
+ SCHEDULED_PROVENANCE_KEY,
+ SessionTurnManager,
+ capture_scheduled_provenance,
+ )
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ successor = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="held successor",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ queued_context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{successor.id}",
+ platform_specific={
+ "task_execution_id": successor.id,
+ "task_trigger_kind": "agent_run",
+ "vibe_agent_name": "codex",
+ "source_kind": "cli",
+ },
+ )
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id)
+ ).mappings().one()
+ messages_service.enqueue_queued(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ text="kept after explicit stop",
+ )
+ messages_service.append(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text="held successor",
+ metadata={
+ SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(
+ queued_context
+ )
+ },
+ native_message_id=f"agent_run:{successor.id}",
+ )
+
+ controller = SimpleNamespace()
+ manager = SessionTurnManager(
+ controller,
+ build_context=lambda _session_id: MessageContext(
+ user_id="workbench",
+ channel_id=session_id,
+ platform="avibe",
+ ),
+ )
+ controller.session_turns = manager
+
+ assert asyncio.run(manager.recover_persisted_agent_run_queue()) == []
+ assert session_id not in manager.in_flight
+ assert request_store.get_run(successor.id)["status"] == "queued"
+ with engine.connect() as conn:
+ assert [
+ row["text"]
+ for row in messages_service.list_queued(conn, session_id)
+ ] == ["kept after explicit stop", "held successor"]
+ engine.dispose()
+
+
def test_service_lease_loss_cancels_inflight_execution(tmp_path: Path, monkeypatch) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
request = request_store.enqueue_hook_send(session_key="slack::channel::C123", prompt="send digest")
@@ -1784,6 +2103,10 @@ def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path:
gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+ recover_queue = AsyncMock(return_value=[])
+ controller.session_turns = SimpleNamespace(
+ recover_persisted_agent_run_queue=recover_queue,
+ )
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
@@ -1797,6 +2120,7 @@ def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path:
assert stored[run_ids[1]]["status"] == "succeeded"
assert stored[run_ids[0]]["completed_at"] is not None
assert stored[run_ids[1]]["completed_at"] is not None
+ recover_queue.assert_awaited_once_with(session_id)
def test_recover_processing_rebuilds_coalesced_metadata_without_queue_rows(
@@ -4513,3 +4837,208 @@ def test_execute_request_avibe_falls_back_when_no_gate(monkeypatch, tmp_path) ->
assert error is None
assert handler_calls == [("run the digest", "avibe")], "no gate → direct scheduled path"
+
+
+def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """HFR-002: one dead accepted owner releases every shared ownership layer."""
+
+ from core.internal_server import create_app
+ from core.message_output import terminal_output_for
+ from core.session_turns import SessionTurnManager, emit_matches_active_turn
+ from modules.agents.base import AgentRequest
+ from modules.agents.service import AgentService
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ first = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="first",
+ agent_name="worker",
+ )
+ second = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="second",
+ agent_name="worker",
+ )
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+
+ class _Controller:
+ primary_platform = "avibe"
+
+ def __init__(self) -> None:
+ self.session_turns = SessionTurnManager(self)
+ self.session_turn_gate = None
+ self.agent_service = AgentService(self)
+ self.platform_settings_managers = {}
+ self.im_clients = {"avibe": SimpleNamespace()}
+ self.statuses: list[tuple[str, str]] = []
+ self.terminal_transitions: list[str] = []
+
+ @staticmethod
+ def _get_session_key(context) -> str:
+ return f"avibe::{context.channel_id}"
+
+ @staticmethod
+ def _session_id_from_context(context) -> str | None:
+ payload = getattr(context, "platform_specific", None) or {}
+ value = payload.get("agent_session_id")
+ return str(value) if value else None
+
+ def get_turn_sink(self, session_key):
+ return self.session_turns.get_turn_sink(session_key)
+
+ def register_turn_sink(self, session_key, **kwargs) -> None:
+ self.session_turns.register_turn_sink(session_key, **kwargs)
+
+ def pop_turn_sink(self, session_key, done_event=None) -> None:
+ self.session_turns.pop_turn_sink(session_key, done_event)
+
+ def mark_turn_complete(self, context) -> None:
+ sink = self.get_turn_sink(self._get_session_key(context))
+ if sink is not None and emit_matches_active_turn(sink, context):
+ sink["done_event"].set()
+
+ def set_agent_status(self, target_session_id, status) -> None:
+ self.statuses.append((target_session_id, status))
+
+ def backend_alive(self, context):
+ return self.agent_service.backend_alive(context)
+
+ def get_im_client_for_context(self, _context):
+ return SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ )
+
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ *,
+ output,
+ is_error=False,
+ terminal_error=None,
+ **_kwargs,
+ ):
+ assert message_type == "result"
+ if not self.agent_service.emit_matches_runtime_turn(context):
+ return None
+ self.session_turns.on_terminal_result(context, is_error=is_error)
+ run_id = str((context.platform_specific or {}).get("task_execution_id") or "")
+ result = sqlite_store.record_run_output(
+ run_id,
+ output_id="terminal",
+ text=text,
+ terminal_status=("failed" if is_error else "succeeded") if output.settles_run else None,
+ error=terminal_error,
+ provenance=output.provenance(context),
+ )
+ if result["terminal_transition"]:
+ self.terminal_transitions.append(run_id)
+ self.mark_turn_complete(context)
+ self.agent_service.release_runtime_turn(context)
+ self.session_turns.on_terminal_delivery_complete(context)
+ return None
+
+ controller = _Controller()
+
+ class _AcceptedBackend:
+ name = "claude"
+
+ def __init__(self) -> None:
+ self.first_alive = True
+ self.started: list[str] = []
+
+ @staticmethod
+ def runtime_turn_key(request) -> str:
+ return request.composite_session_id
+
+ def backend_alive(self, context):
+ run_id = str((context.platform_specific or {}).get("task_execution_id") or "")
+ return self.first_alive if run_id == first.id else True
+
+ async def handle_message(self, request) -> None:
+ run_id = str((request.context.platform_specific or {}).get("task_execution_id") or "")
+ self.started.append(run_id)
+ controller.agent_service.mark_runtime_turn_started(request.context)
+ if run_id == second.id:
+ await controller.emit_agent_message(
+ request.context,
+ "result",
+ "second completed",
+ output=terminal_output_for(request),
+ )
+
+ backend = _AcceptedBackend()
+ controller.agent_service.register(backend)
+ controller.agent_service._liveness_probe_interval_seconds = 0.005
+ controller.agent_service._liveness_failure_grace_seconds = 0.005
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ del parsed_session_key
+ await controller.agent_service.handle_message(
+ "claude",
+ AgentRequest(
+ context=context,
+ message=message,
+ working_path=str(tmp_path),
+ base_session_id=session_id,
+ composite_session_id=f"{session_id}:{tmp_path}",
+ session_key=controller._get_session_key(context),
+ ),
+ )
+
+ controller.message_handler = SimpleNamespace(
+ handle_scheduled_message=_handle_scheduled_message,
+ )
+ create_app(controller)
+ scheduled = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ async def _wait_for(predicate, *, timeout=1.0) -> None:
+ async def _poll() -> None:
+ while not predicate():
+ await asyncio.sleep(0.005)
+
+ await asyncio.wait_for(_poll(), timeout=timeout)
+
+ async def _exercise() -> None:
+ await scheduled._drain_requests()
+ await _wait_for(lambda: backend.started == [first.id])
+ await _wait_for(lambda: first.id not in scheduled._inflight_executions)
+
+ await scheduled._drain_requests()
+ await _wait_for(
+ lambda: request_store.get_run(second.id)["metadata"].get(
+ "workbench_queue_holds_run"
+ )
+ is True
+ )
+ state = controller.session_turns.turn_state(session_id)
+ assert state["owner"]["run_id"] == first.id
+ assert state["pending_input_count"] == 1
+ assert request_store.get_run(first.id)["status"] == "running"
+ assert request_store.get_run(second.id)["status"] == "queued"
+
+ backend.first_alive = False
+ await _wait_for(lambda: request_store.get_run(second.id)["status"] == "succeeded")
+ await _wait_for(lambda: session_id not in controller.session_turns.in_flight)
+
+ assert backend.started == [first.id, second.id]
+ assert controller.terminal_transitions == [first.id, second.id]
+ assert request_store.get_run(first.id)["status"] == "failed"
+ assert request_store.get_run(first.id)["error"] == (
+ "backend_runtime_exited_before_terminal"
+ )
+ assert request_store.get_run(second.id)["result_text"] == "second completed"
+ assert controller.session_turns.turn_state(session_id)["pending_input_count"] == 0
+
+ asyncio.run(_exercise())
diff --git a/tests/test_session_activities.py b/tests/test_session_activities.py
index 5f0ad21cb..cc317a88c 100644
--- a/tests/test_session_activities.py
+++ b/tests/test_session_activities.py
@@ -12,7 +12,7 @@ from core.session_activities import (
SessionActivityRegistry,
activity_completion_output,
)
-from core.session_turns import SessionTurnManager
+from core.session_turns import SessionTurnManager, Turn
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.session_activities import SQLiteSessionActivityStore
@@ -353,6 +353,48 @@ def test_turn_state_composes_foreground_inbox_activity_and_connection_axes():
assert [item["id"] for item in state["background_activities"]] == ["task-1"]
+def test_turn_state_reports_authoritative_live_owner_diagnostics():
+ """HFR-002: queued Run diagnosis comes from the live Session owner."""
+
+ context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-owner",
+ "agent_runtime_turn_key": "session:/repo",
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+ )
+ controller = SimpleNamespace(
+ agent_service=SimpleNamespace(
+ activities=SessionActivityRegistry(),
+ runtime_turn_started=lambda candidate: candidate is context,
+ ),
+ backend_alive=lambda candidate: False if candidate is context else None,
+ )
+ manager = SessionTurnManager(controller=controller)
+ manager._engine = SimpleNamespace(begin=lambda: nullcontext(object()))
+ manager.in_flight["ses-1"] = Turn(
+ task=SimpleNamespace(done=lambda: False),
+ context=context,
+ started_at="2026-07-18T04:31:26+00:00",
+ )
+
+ with mock.patch("core.session_turns.messages_service.list_queued", return_value=[{"id": "queued-1"}]):
+ state = manager.turn_state("ses-1")
+
+ assert state["in_flight"] is True
+ assert state["backend"] == "codex"
+ assert state["owner"] == {
+ "source": "agent_run",
+ "acquired_at": "2026-07-18T04:31:26+00:00",
+ "run_id": "run-owner",
+ "run_ids": ["run-owner"],
+ "runtime_key": "session:/repo",
+ "native_turn_started": True,
+ "backend_alive": False,
+ }
+
+
def test_activity_restart_recovers_connection_and_interrupts_live_work(tmp_path: Path):
db_path = tmp_path / "state" / "vibe.sqlite"
ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
diff --git a/vibe/cli.py b/vibe/cli.py
index 3eec0daf1..e0ecf7e72 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -4295,13 +4295,42 @@ def cmd_runs_show(args):
if run is None:
_print_task_error(TaskCliError(f"run '{run_id}' not found", code="run_not_found", details={"run_id": run_id}))
return 1
- payload_fields = {"run": _run_payload(run)}
+ run_payload = _run_payload(run)
+ session_runtime = _live_session_runtime_for_run(run_payload)
+ if session_runtime is not None:
+ run_payload["session_runtime"] = session_runtime
+ payload_fields = {"run": run_payload}
if run_default_notice:
payload_fields["run_default_notice"] = run_default_notice
_print_cli_payload("agent_run", **payload_fields)
return 0
+def _live_session_runtime_for_run(run: dict) -> dict | None:
+ """Attach authoritative controller ownership to an active Session Run."""
+
+ if normalize_run_status(run.get("status")) not in {"queued", "running"}:
+ return None
+ session_id = _run_session_id(run)
+ if not session_id:
+ return None
+ from vibe import internal_client
+
+ try:
+ result = asyncio.run(internal_client.turn_state(session_id))
+ except internal_client.InternalServerTimeout:
+ return {"available": False, "reason": "controller_probe_timeout"}
+ except internal_client.InternalServerUnavailable:
+ return {"available": False, "reason": "controller_unavailable"}
+ except Exception:
+ logger.debug("Failed to inspect live Session owner for Run %s", run.get("id"), exc_info=True)
+ return {"available": False, "reason": "controller_probe_failed"}
+ body = result.get("body") if isinstance(result, dict) else None
+ if result.get("status_code") != 200 or not isinstance(body, dict):
+ return {"available": False, "reason": "controller_probe_rejected"}
+ return {"available": True, **body}
+
+
def _run_type(run: dict | None) -> str:
if not isinstance(run, dict):
return ""