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): settle zombie agent runs honestly and sweep the ones that lost their owner (#1005)

Qi Qic133b3031848
diff --git a/config/v2_config.py b/config/v2_config.py
index 2a7511bba..3064c24dd 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -29,6 +29,21 @@ CONFIG_LOCK = threading.RLock()
DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600
+# Harness run staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.4).
+# How often the sweep may run at all — it rides the scheduler's existing 2 s tick, so
+# this only rate-limits the candidate query.
+DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS = 60
+# How long a ``running`` agent run may have no live owner before it is declared
+# orphaned. Must comfortably exceed the gap between claiming a row and registering the
+# executing turn, so a legitimately-starting run is never swept.
+DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS = 120
+# How long a ``queued`` run may sit while its transport is unavailable. Long enough
+# that a brief IM reconnect just delivers late instead of failing the run.
+DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS = 1800
+# How long a workbench queue hold may go unrefreshed. Deliberately the longest of the
+# three: a session actively recovering its queue keeps touching the row.
+DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS = 3600
+
# Absolute-time backstop for evicting a Codex transport whose turn is stuck
# "active" forever (e.g. the ``codex app-server`` wedged or silently
# disconnected after ``turn/start`` but before ``turn/completed``, so
@@ -248,6 +263,16 @@ class RuntimeConfig:
# workload. "auto" enables it only when Avibe can create and write the
# delegated cgroup; unsupported systems silently fall back to legacy spawn.
resource_governance: dict = field(default_factory=lambda: {"mode": "auto"})
+ # Harness run staleness sweep. A Run whose executor died, whose transport never
+ # came back, or whose workbench queue hold was never released has nothing left to
+ # write its terminal state, so it would sit ``running``/``queued`` forever. The
+ # sweep terminalizes those on evidence (see
+ # ``docs/plans/agent-run-zombie-settlement.md`` §4). Each key is seconds and ``0``
+ # disables that class; the defaults are the product decision, so there is no UI.
+ harness_run_sweep_interval_seconds: int = DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS
+ harness_run_orphan_grace_seconds: int = DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS
+ harness_run_queued_ttl_seconds: int = DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS
+ harness_run_hold_ttl_seconds: int = DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS
@dataclass
@@ -1182,6 +1207,10 @@ class V2Config:
"default_cwd": self.runtime.default_cwd,
"log_level": self.runtime.log_level,
"resource_governance": self.runtime.resource_governance,
+ "harness_run_sweep_interval_seconds": self.runtime.harness_run_sweep_interval_seconds,
+ "harness_run_orphan_grace_seconds": self.runtime.harness_run_orphan_grace_seconds,
+ "harness_run_queued_ttl_seconds": self.runtime.harness_run_queued_ttl_seconds,
+ "harness_run_hold_ttl_seconds": self.runtime.harness_run_hold_ttl_seconds,
},
"agents": {
"opencode": self.agents.opencode.__dict__,
diff --git a/core/controller.py b/core/controller.py
index dab9d1dba..62a74037d 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -28,6 +28,7 @@ from core.message_context import build_context_session_key
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.message_output import MessageOutput
from core.processing_indicator import ProcessingIndicatorService
+from core.run_settlement import SETTLED_BY_NO_TERMINAL_RESULT
from core.runtime_commands import RuntimeCommandWatcher
from core.scheduled_tasks import ScheduledTaskService
from core.show_git import ShowGitCheckpointService
@@ -1103,7 +1104,12 @@ class Controller:
def settle_bound_turn_sink(self, binding: Optional[Dict[str, Any]]) -> bool:
return self.session_turns.settle_bound_turn_sink(binding)
- def mark_turn_complete(self, context: Optional[MessageContext] = None) -> None:
+ def mark_turn_complete(
+ self,
+ context: Optional[MessageContext] = None,
+ *,
+ settled_by: str = SETTLED_BY_NO_TERMINAL_RESULT,
+ ) -> None:
"""Release a streaming turn sink whose turn finished WITHOUT emitting a
result (missing/disabled backend, dedup, inline-stop, error, or any
synchronous no-agent path) so the SSE dispatch closes promptly instead
@@ -1124,6 +1130,19 @@ class Controller:
if not emit_matches_active_turn(sink, context):
return
+ # Record WHY the waiter is being released, so ``dispatch_turn`` can tell its
+ # caller. An ``agent_run`` released with a no-result settlement must be
+ # terminalized by that caller: nothing else will ever do it (see
+ # docs/plans/agent-run-zombie-settlement.md). ``setdefault`` keeps a real
+ # terminal result — which always runs before this ``finally`` — as the
+ # winning settlement.
+ #
+ # The default is the no-dispatch case this method was written for (blank
+ # prompt, dedup, inline stop). A caller that IS a terminal output overrides
+ # it: the dispatcher passes ``SETTLED_BY_TURN_ONLY_RESULT`` when the output
+ # completes the turn but deliberately leaves the run to another owner (a
+ # requeued Claude Activity), which must NOT be settled here (Codex P1).
+ sink.setdefault("settled_by", settled_by or SETTLED_BY_NO_TERMINAL_RESULT)
done = sink.get("done_event")
if done is not None:
done.set()
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index a140ba1fb..ff82dd7d0 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -26,6 +26,11 @@ from core.message_mirror import (
)
from core.message_output import MessageOutput, output_for_message
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
+from core.run_settlement import (
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+ SETTLED_BY_TURN_ONLY_RESULT,
+)
from core.session_turns import emit_matches_active_turn
from storage.background import SQLiteBackgroundTaskStore
from vibe.i18n import t as i18n_t
@@ -117,6 +122,22 @@ async def _stream_chunk(
# because its result emit adopts the live turn's token (see ClaudeAgent).
if not emit_matches_active_turn(sink, context):
return
+ # Record WHY the waiter is being released, before releasing it. This is the
+ # honest settlement: a real terminal result arrived, so ``dispatch_turn``
+ # must leave the run's terminal state to the out-of-band writer. The
+ # fallback releasers use ``setdefault``, so this value always wins over them.
+ #
+ # An acknowledged Stop is NOT one of those fallbacks and must not be
+ # overwritten (Codex P2). ``settle_bound_turn_sink`` bails out when ``done`` is
+ # already set, so reaching here with ``stopped`` recorded means the user's stop
+ # won the race and was already reported to them; replacing the reason would
+ # make ``_execute_agent_run`` skip the guarded ``canceled`` settlement and let
+ # the outcome depend on which coroutine happened to resume first. The run's
+ # terminal STATUS is still first-writer-wins in the store, so a result whose row
+ # write already landed keeps its ``succeeded`` — this only stops the reason from
+ # silently disagreeing with what the user was told.
+ if sink.get("settled_by") != SETTLED_BY_STOPPED:
+ sink["settled_by"] = SETTLED_BY_TERMINAL_RESULT
done = sink.get("done_event")
if done is not None:
done.set()
@@ -212,15 +233,58 @@ class ConsolidatedMessageDispatcher:
return getter(context)
return self.controller.im_client
- def _signal_turn_complete(self, context: MessageContext) -> None:
+ def _signal_turn_complete(
+ self,
+ context: MessageContext,
+ *,
+ settled_by: str = SETTLED_BY_TERMINAL_RESULT,
+ ) -> None:
"""Release a live streaming SSE waiter for this turn when a result is
finalized without streaming a visible chunk (empty/silent result), so
the stream closes promptly instead of hanging until the timeout. No-op
- for non-streaming turns or controllers without the registry."""
+ for non-streaming turns or controllers without the registry.
+
+ Every caller here is a TERMINAL RESULT emit, so the settlement recorded on
+ the sink must say so — ``mark_turn_complete``'s own default is the
+ no-dispatch case and would make a durable caller re-settle the run as
+ failed. ``SETTLED_BY_TURN_ONLY_RESULT`` is passed when the output completes
+ the turn but not the run (Codex P1)."""
mark = getattr(self.controller, "mark_turn_complete", None)
- if callable(mark):
+ if not callable(mark):
+ return
+ try:
+ mark(context, settled_by=settled_by)
+ except TypeError:
+ # Older controller / test double without the keyword: the release still
+ # matters more than the attribution.
mark(context)
+ @staticmethod
+ def _turn_release_settlement(output_semantics) -> str:
+ """Which settlement a terminal-result release records on the turn sink.
+
+ An output may NAME its settlement, and that always wins: the emit knows why
+ it exists, and only it can. The live case is the synthetic terminal result a
+ user stop emits (``stop_output_for``) — an empty body that ends the turn while
+ the run was *called off*, so it must read ``stopped`` and let the stop's own
+ writer settle the row ``canceled``. Deriving the reason from ``settles_run``
+ alone would label it ``turn_only_result``, which is in no settlement map, and
+ the run would be left ``running`` for the sweep to relabel ``orphaned``.
+
+ Otherwise ``settles_run`` decides: it means this output's own writer owns the
+ run's terminal state (``_record_agent_run_terminal_result`` runs right before
+ the release), which is the honest ``terminal_result``. Without it the run
+ belongs to somebody else — the requeued Activity behind a delivery failure —
+ and this turn must not settle it at all."""
+ explicit = str(getattr(output_semantics, "settled_by", None) or "").strip()
+ if explicit:
+ return explicit
+ return (
+ SETTLED_BY_TERMINAL_RESULT
+ if getattr(output_semantics, "settles_run", True)
+ else SETTLED_BY_TURN_ONLY_RESULT
+ )
+
def _release_runtime_turn(self, context: MessageContext) -> None:
service = getattr(self.controller, "agent_service", None)
release = getattr(service, "release_runtime_turn", None)
@@ -1429,7 +1493,10 @@ class ConsolidatedMessageDispatcher:
# doesn't stay stuck (missing agent / exception / user stop).
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
- self._signal_turn_complete(context)
+ self._signal_turn_complete(
+ context,
+ settled_by=self._turn_release_settlement(output_semantics),
+ )
if level != "silent" and not is_error:
# A CLEAN silent completion — ``level='normal'`` with an
# empty/``<silent>``-stripped body (we're already inside the
@@ -1496,7 +1563,10 @@ class ConsolidatedMessageDispatcher:
if mutates_turn_lifecycle:
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
- self._signal_turn_complete(context)
+ self._signal_turn_complete(
+ context,
+ settled_by=self._turn_release_settlement(output_semantics),
+ )
# A previously persisted output is a successful idempotent
# delivery attempt. Return its stable identity so a recovered
# Activity can acknowledge its durable Outbox snapshot instead
@@ -1585,7 +1655,10 @@ class ConsolidatedMessageDispatcher:
# status bubble posted to a real channel so it doesn't stay stuck.
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
- self._signal_turn_complete(context)
+ self._signal_turn_complete(
+ context,
+ settled_by=self._turn_release_settlement(output_semantics),
+ )
return message_id
finally:
if mutates_turn_lifecycle:
@@ -1926,7 +1999,10 @@ class ConsolidatedMessageDispatcher:
# delivery path failed and therefore produced no durable message id.
# Without this release, direct agent_run and avibe turn waiters keep
# waiting forever despite the backend having already finished.
- self._signal_turn_complete(context)
+ self._signal_turn_complete(
+ context,
+ settled_by=self._turn_release_settlement(output_semantics),
+ )
return primary_message_id
finally:
diff --git a/core/message_output.py b/core/message_output.py
index ffead5a0a..887ecd066 100644
--- a/core/message_output.py
+++ b/core/message_output.py
@@ -7,9 +7,11 @@ dispatcher fallback preserves older callers that still use terminal ``result``.
from __future__ import annotations
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from typing import Any, Mapping
+from core.run_settlement import SETTLED_BY_STOPPED
+
@dataclass(frozen=True)
class MessageOutput:
@@ -24,6 +26,7 @@ class MessageOutput:
sequence: int | None = None
run_id: str | None = None
requires_delivery_for_run_settlement: bool = False
+ settled_by: str | None = None
metadata: Mapping[str, Any] = field(default_factory=dict)
@property
@@ -103,3 +106,34 @@ def terminal_output_for(request: Any) -> MessageOutput:
output = getattr(request, "output", None)
return output if isinstance(output, MessageOutput) else terminal_turn_output()
+
+
+def stop_output_for(request: Any) -> MessageOutput:
+ """A user stop's synthetic terminal result: ends the Turn, does NOT own the Run.
+
+ Every backend answers an acknowledged stop with an empty silent ``result`` so the
+ dot settles to idle and the SSE waiter closes through the one outbound chokepoint.
+ That output is the *turn's* release, not the *run's* result: nobody produced an
+ answer, the user called the work off. Sending it with the terminal-turn default
+ (``completes_run=True``) made the dispatcher record the run ``succeeded`` from an
+ empty body — and, because the terminal write lands before the stop's own guarded
+ write, first-writer-wins meant a user-ended run was reported as a success.
+
+ So: ``completes_run=False`` keeps the empty result out of the run's terminal
+ state, while ``settled_by`` names the reason on the turn sink so the settlement
+ lanes reach the writer that already knows a stop is ``canceled`` with
+ ``interrupt_reason=stopped`` (``SETTLEMENT_TERMINAL_STATUS``). Without the reason,
+ "does not settle the run" would read as ``turn_only_result`` — the Activity case,
+ where somebody else genuinely owns the row — and the run would sit ``running``
+ until the staleness sweep called it ``orphaned``.
+
+ Built with ``replace`` so a request carrying its own output policy (Activity
+ lineage, an explicit ``run_id``) keeps it; only the lifecycle is overridden.
+ """
+
+ return replace(
+ terminal_output_for(request),
+ completes_turn=True,
+ completes_run=False,
+ settled_by=SETTLED_BY_STOPPED,
+ )
diff --git a/core/run_settlement.py b/core/run_settlement.py
new file mode 100644
index 000000000..a14d56587
--- /dev/null
+++ b/core/run_settlement.py
@@ -0,0 +1,147 @@
+"""Shared vocabulary for how a turn's dispatch waiter was settled.
+
+Two layers need to agree on these strings and neither owns the other:
+
+* ``core/services/dispatch.py`` records WHY a streaming turn's waiter was
+ released (``TurnDispatchOutcome.settled_by``), which is stamped on the live
+ turn sink by the three release sites.
+* ``core/scheduled_tasks.py`` turns that into an ``agent_runs`` terminal state
+ plus ``metadata.interrupt_reason`` for a run whose backend never emitted a
+ terminal result.
+
+Keeping the strings here (rather than inline at each site) is what stops the
+values in ``docs/plans/agent-run-zombie-settlement.md`` from drifting apart from
+the ones in ``docs/plans/harness-run-reliability.md`` (``evicted`` /
+``restarted`` / ``lifetime_timeout``), which land on the same column.
+"""
+
+from __future__ import annotations
+
+from typing import Final
+
+# ----- how a turn sink's ``done_event`` was released -----------------------
+
+#: The backend emitted the turn's real terminal ``result``. The only honest
+#: settlement — the out-of-band writer owns the run's terminal state.
+SETTLED_BY_TERMINAL_RESULT: Final = "terminal_result"
+
+#: The turn ended without dispatching an agent at all, so
+#: ``Controller.mark_turn_complete`` released the waiter with no result
+#: (blank prompt, dedup, inline stop, any future no-dispatch early return).
+SETTLED_BY_NO_TERMINAL_RESULT: Final = "no_terminal_result"
+
+#: An external stop (Running-tab "End") settled the sink as a fallback because
+#: the backend was interrupted without emitting a terminal result.
+SETTLED_BY_STOPPED: Final = "stopped"
+
+#: ``dispatch_turn`` refused a second concurrent streaming turn for the session
+#: and returned before any sink existed.
+SETTLED_BY_REFUSED_CONCURRENT_TURN: Final = "refused_concurrent_turn"
+
+#: A REAL terminal output released the turn while deliberately keeping the run's
+#: ownership somewhere else, so no run settlement is owed here. The Claude
+#: Activity delivery-failure path is the live case: when a completion cannot be
+#: persisted or delivered it emits a silent ``result`` with
+#: ``MessageOutput(completes_turn=True, completes_run=False)`` to close the origin
+#: turn while the REQUEUED Activity keeps the run and retries. Reading that as
+#: "no terminal result" would settle an Activity-owned run ``failed`` — and fire
+#: its callback — before the retry ever ran.
+#:
+#: This value never reaches a row: it is not in ``SETTLEMENTS_WITHOUT_RESULT``, so
+#: it has no terminal status and no user-visible text, exactly like
+#: ``SETTLED_BY_TERMINAL_RESULT``.
+SETTLED_BY_TURN_ONLY_RESULT: Final = "turn_only_result"
+
+#: An agent-runtime refresh retired the turn: ``release_for_backend_refresh``
+#: cancels in-flight turns of a backend whose cached process state is about to
+#: disappear (an ``agents.*`` save's rolling reconciliation, a Codex runtime
+#: reload). This is NOT the same event as a user stop even though both arrive as
+#: a cancelled task — nobody asked for this run to end, so it must not be
+#: reported as ``canceled`` with the user-stop explanation.
+#:
+#: Spelled ``backend_refresh`` rather than reusing ``harness-run-reliability``'s
+#: ``restarted``: that value is reserved for the *service* restarting around a
+#: run, which recovery retries, while this one interrupts a live turn inside a
+#: healthy process and does not.
+SETTLED_BY_BACKEND_REFRESH: Final = "backend_refresh"
+
+#: Settlements that mean "no terminal result will ever arrive for this run" — the
+#: ONLY ones a caller may terminalize a row from. Both settlement lanes test
+#: membership here rather than excluding ``SETTLED_BY_TERMINAL_RESULT``, so a new
+#: "the turn ended but the run lives on" value can never be mistaken for a zombie.
+SETTLEMENTS_WITHOUT_RESULT: Final = frozenset(
+ {
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ SETTLED_BY_BACKEND_REFRESH,
+ }
+)
+
+# ----- ``agent_runs.metadata.interrupt_reason`` ---------------------------
+#
+# A run terminalized by something other than its own backend result carries the
+# reason so a later notification / UI badge can say which, and so a failure
+# counter can tell an infrastructure fault from a broken definition.
+
+INTERRUPT_REASON_NO_TERMINAL_RESULT: Final = SETTLED_BY_NO_TERMINAL_RESULT
+INTERRUPT_REASON_STOPPED: Final = SETTLED_BY_STOPPED
+INTERRUPT_REASON_REFUSED_CONCURRENT_TURN: Final = SETTLED_BY_REFUSED_CONCURRENT_TURN
+INTERRUPT_REASON_BACKEND_REFRESH: Final = SETTLED_BY_BACKEND_REFRESH
+
+
+# ----- user-visible reason text -------------------------------------------
+#
+# The run's ``error`` column is shown to the user (``vibe runs show``, the Runs
+# UI, the callback message), so every settlement here needs a translated string.
+# Mapping the wire values to explicit keys — instead of interpolating the value
+# into a key — keeps the settlement vocabulary free to change without silently
+# degrading to a raw key leaking into the UI, and lets one test assert every
+# settlement resolves in every language.
+SETTLEMENT_I18N_KEYS: Final = {
+ SETTLED_BY_NO_TERMINAL_RESULT: "harness.run.interrupted.noTerminalResult",
+ SETTLED_BY_STOPPED: "harness.run.interrupted.stopped",
+ SETTLED_BY_REFUSED_CONCURRENT_TURN: "harness.run.interrupted.refusedConcurrentTurn",
+ SETTLED_BY_BACKEND_REFRESH: "harness.run.interrupted.backendRefresh",
+}
+
+
+# ----- which terminal status each settlement writes -----------------------
+#
+# ``stopped`` is the one settlement that carries explicit user intent: someone
+# pressed End/Stop on a running agent. ``canceled`` — already in the closed
+# vocabulary for exactly that — is the honest terminal, not ``failed``: the run
+# did not break, it was called off. This also makes the narrow race in
+# ``settle_bound_turn_sink`` benign in both directions. If the backend's terminal
+# result lands first, the honest ``succeeded`` write wins and this settlement is a
+# no-op; if it lands after the stop was acknowledged, the row reads ``canceled``,
+# which is still true of a run the user stopped.
+#
+# The other settlements are infrastructure faults with no user intent behind
+# them, so they stay ``failed`` and remain visible to a failure counter.
+SETTLEMENT_TERMINAL_STATUS: Final = {
+ SETTLED_BY_NO_TERMINAL_RESULT: "failed",
+ SETTLED_BY_STOPPED: "canceled",
+ SETTLED_BY_REFUSED_CONCURRENT_TURN: "failed",
+ SETTLED_BY_BACKEND_REFRESH: "failed",
+}
+
+
+# ----- staleness-sweep reason text ----------------------------------------
+#
+# The settlements above are all reported by the turn that owned the run. A run
+# whose owner vanished (process restart, lost turn, a queue gate that never
+# reopened) has nobody left to report it, so ``sweep_stale_runs`` terminalizes it
+# out of band and stamps one of these reasons instead. Same contract as
+# ``SETTLEMENT_I18N_KEYS``: the text lands in the user-visible ``error`` column.
+#
+# The keys are the ``SWEEP_REASON_*`` values from ``storage.background``, spelled
+# as literals here on purpose — this module stays dependency-free so the dispatch
+# layer can import it without pulling in SQLAlchemy, and importing core from
+# storage would invert the layering. ``tests/test_i18n_backend_keys.py`` asserts
+# this map's key set equals the store's constants, so the two cannot drift.
+SWEEP_I18N_KEYS: Final = {
+ "orphaned": "harness.run.interrupted.orphaned",
+ "transport_unavailable": "harness.run.interrupted.transportUnavailable",
+ "queue_hold_expired": "harness.run.interrupted.queueHoldExpired",
+}
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 1376aecee..d4dbe35fc 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -6,10 +6,11 @@ import asyncio
import json
import logging
import tempfile
+import time
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any, Dict, NamedTuple, Optional
+from typing import Any, Dict, NamedTuple, Optional, Sequence
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -20,6 +21,12 @@ from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from config import paths
+from config.v2_config import (
+ DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS,
+ DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS,
+ DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS,
+ DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS,
+)
from config.v2_settings import split_thread_native_id
from core.message_context import (
build_thread_session_anchor,
@@ -28,13 +35,29 @@ from core.message_context import (
thread_id_from_session_anchor,
)
from core.reply_enhancer import strip_silent_blocks
+from core.run_settlement import (
+ SETTLEMENTS_WITHOUT_RESULT,
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLEMENT_I18N_KEYS,
+ SETTLEMENT_TERMINAL_STATUS,
+ SWEEP_I18N_KEYS,
+)
from core.session_activities import activity_completion_output
from modules.im import MessageContext
from storage.db import create_sqlite_engine, get_cached_sqlite_engine
-from storage.background import SQLiteBackgroundTaskStore
+from storage.background import (
+ SKIP_REASON_SESSION_BUSY,
+ SKIP_REASON_TRANSPORT_UNAVAILABLE,
+ SQLiteBackgroundTaskStore,
+ SWEEP_REASON_ORPHANED,
+ SWEEP_REASON_QUEUE_HOLD_EXPIRED,
+ SWEEP_REASON_TRANSPORT_UNAVAILABLE,
+ SweptRun,
+)
from storage.models import agent_sessions, scope_settings, scopes
from storage.pagination import PageRequest, PageResult, page_sequence
from vibe import runtime
+from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
@@ -216,6 +239,10 @@ class AgentRunExecutionResult:
complete_on_return: bool
requeue_on_return: bool = False
coalesced_completion_ids: tuple[str, ...] = ()
+ # The run's terminal row was already written by the executor itself (through a
+ # guarded writer), so the caller must skip ``complete()`` but still run the
+ # post-completion side effects: callback delivery and session-queue recovery.
+ settled_out_of_band: bool = False
def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None) -> ResolvedSessionIdTarget:
@@ -1017,6 +1044,12 @@ class TaskExecutionStore:
callback_active: bool = True,
metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
+ if not (message or "").strip():
+ # Refuse at the door: a blank prompt never reaches an agent backend
+ # (``MessageHandler`` returns early), so the run could never be settled
+ # by a terminal result. Every caller (CLI, callback, delivery) has a
+ # real message; a blank one is a bug in the caller.
+ raise ValueError("agent run requires a non-empty message")
return self.enqueue(
TaskExecutionRequest(
id=uuid4().hex[:12],
@@ -1151,6 +1184,73 @@ class TaskExecutionStore:
error=error,
)
+ def record_skip_reason(self, run_id: str, *, reason: str) -> bool:
+ """Record why the drain deferred a queued run (SQLite only, no-op otherwise)."""
+
+ if self._sqlite is None:
+ return False
+ return self._sqlite.record_run_skip_reason(run_id, reason=reason)
+
+ def sweep_stale_runs(
+ self,
+ *,
+ owned_run_ids: set[str],
+ error_texts: dict[str, str],
+ deliverable_run_ids: Optional[set[str]] = None,
+ busy_session_ids: Optional[set[str]] = None,
+ orphan_grace_seconds: int,
+ queued_ttl_seconds: int,
+ hold_ttl_seconds: int,
+ ) -> list[SweptRun]:
+ """Terminalize provably stale runs. Empty for the legacy file store."""
+
+ if self._sqlite is None:
+ return []
+ return self._sqlite.sweep_stale_runs(
+ owned_run_ids=owned_run_ids,
+ error_texts=error_texts,
+ deliverable_run_ids=deliverable_run_ids,
+ busy_session_ids=busy_session_ids,
+ orphan_grace_seconds=orphan_grace_seconds,
+ queued_ttl_seconds=queued_ttl_seconds,
+ hold_ttl_seconds=hold_ttl_seconds,
+ )
+
+ def supports_guarded_settlement(self) -> bool:
+ """Whether this store can terminalize a run without clobbering a cancel.
+
+ Only the SQLite store has the status-scoped UPDATE behind
+ :meth:`settle_without_result`. The legacy file store has no equivalent, so
+ its callers must fall back to the ``complete()`` path instead.
+ """
+
+ return self._sqlite is not None
+
+ def settle_without_result(
+ self,
+ run_id: str,
+ *,
+ terminal_status: str = "failed",
+ error: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ ) -> Optional[str]:
+ """Terminalize a still-open run whose turn produced no terminal result.
+
+ Returns the status actually written (``terminal_status``, or ``canceled``
+ when a ``failed`` settlement met a pending cancel), or ``None`` when nothing
+ was written because the row is missing, already terminal, or holds a
+ deferred terminal status.
+ """
+
+ if self._sqlite is None:
+ return None
+ return self._sqlite.settle_run_terminal(
+ run_id,
+ terminal_status=terminal_status,
+ error=error,
+ metadata=metadata,
+ )
+
def defer_run_terminal(
self,
run_id: str,
@@ -1593,14 +1693,36 @@ class ScheduledTaskService:
# serialize turns per session (never two at once for the same
# conversation) while still running different sessions concurrently.
self._inflight_sessions: set[str] = set()
+ # lock key -> the request id that took it. The set above answers "is this
+ # conversation busy"; this answers "busy on behalf of WHOM", which is what
+ # lets the sweep release a leaked lock without ever freeing one a live
+ # execution still holds (see ``_release_leaked_session_locks``).
+ self._session_lock_owners: Dict[str, str] = {}
# Cache of session_id -> canonical lock key (resolution hits SQLite).
self._session_lock_cache: Dict[str, str] = {}
self._pending_recovered_activity_terminals: list[Any] = []
+ # Monotonic timestamp of the last staleness sweep, so the sweep can ride the
+ # 2 s store tick while running at most once per configured interval.
+ self._last_sweep_at: float = 0.0
+ # Warn once, not once per interval, while the sweep is failing closed.
+ self._sweep_ownership_unavailable_logged = False
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self._drain_dirty = True
self._recover_activity_lifecycle()
self.request_store.recover_processing()
+ def _t(self, key: str, **kwargs: Any) -> str:
+ """Translate a user-visible string in the configured language.
+
+ Mirrors ``UpdateChecker._t``: read the language straight off the
+ controller's config so a headless service (tests, CLI-only runs) with no
+ controller still falls back to English instead of raising.
+ """
+
+ config = getattr(self.controller, "config", None)
+ lang = str(getattr(config, "language", "en") or "en")
+ return i18n_t(key, lang, **kwargs)
+
@staticmethod
def _activity_run_ids(activity: Any) -> list[str]:
run_ids: list[str] = []
@@ -1880,6 +2002,7 @@ class ScheduledTaskService:
pass
self._inflight_executions.clear()
self._inflight_sessions.clear()
+ self._session_lock_owners.clear()
async def _watch_store(self) -> None:
while self._running:
@@ -1904,6 +2027,10 @@ class ScheduledTaskService:
# so sweep for owed auto-resume callbacks every tick — a cheap indexed lookup that
# no-ops when nothing is pending.
await self._drain_vault_callbacks()
+ # Same reason, one layer down: a run whose owner vanished emits no
+ # store change either, so only a periodic pass can find it. Self
+ # rate-limited, so riding this tick is cheap.
+ self._sweep_stale_runs()
await asyncio.sleep(2)
except asyncio.CancelledError:
raise
@@ -1914,6 +2041,235 @@ class ScheduledTaskService:
except asyncio.CancelledError:
raise
+ def _runtime_seconds(self, name: str, default: int) -> int:
+ """Read one sweep timing knob off runtime config, tolerating junk values."""
+
+ runtime_config = getattr(getattr(self.controller, "config", None), "runtime", None)
+ try:
+ return int(getattr(runtime_config, name, default))
+ except (TypeError, ValueError):
+ return default
+
+ def _owned_agent_run_ids(self) -> set[str]:
+ """Every run id something in THIS process is still legitimately executing.
+
+ Two lanes own a ``running`` row and neither can see the other:
+
+ - the drain lane: ``_inflight_executions``, one entry per claimed request
+ whose ``_execute_claimed_request`` task has not finished;
+ - the turn lane: a workbench/web turn that took over out of band. Those
+ never enter ``_inflight_executions``, so they are asked for directly via
+ :meth:`SessionTurnManager.owned_agent_run_ids`.
+
+ Raises when the turn lane cannot be reached. That is deliberate: the caller
+ must fail closed, because a missing provider silently reads as "no live
+ turns own anything", which would terminalize every streaming run.
+ """
+
+ owned = set(self._inflight_executions)
+ session_turns = getattr(self.controller, "session_turns", None)
+ provider = getattr(session_turns, "owned_agent_run_ids", None)
+ if not callable(provider):
+ raise RuntimeError("controller.session_turns.owned_agent_run_ids is unavailable")
+ owned |= {str(run_id) for run_id in provider() if run_id}
+ return owned
+
+ def _busy_session_ids(self) -> set[str]:
+ """Sessions with a live turn, which is why their queue holds exist.
+
+ The gate answers ``enqueued`` for a run submitted into a session that already
+ has a turn in flight, and that run is then requeued with
+ ``workbench_queue_holds_run``. Nobody reports it as owned — the live turn owns
+ only the ids it is itself executing — so the hold class needs this second live
+ fact or it fails the follower of any turn longer than the hold TTL (Codex P2).
+
+ Raises when the turn lane cannot be reached, for the same reason
+ :meth:`_owned_agent_run_ids` does: "no session is busy" and "I cannot tell" are
+ opposite answers, and the caller must fail closed on the second.
+ """
+
+ session_turns = getattr(self.controller, "session_turns", None)
+ provider = getattr(session_turns, "busy_session_ids", None)
+ if not callable(provider):
+ raise RuntimeError("controller.session_turns.busy_session_ids is unavailable")
+ return {str(session_id) for session_id in provider() if session_id}
+
+ def _deliverable_queued_run_ids(self) -> set[str]:
+ """Queued runs whose transport is ready RIGHT NOW, whatever the row remembers.
+
+ The drain records ``transport_unavailable`` when it defers a run, but it
+ ``break``s at ``_MAX_CONCURRENT_EXECUTIONS`` without examining the rows below
+ the cut — so their stamp is never refreshed and stays true-at-the-time long
+ after the platform reconnected. This is the live half of that evidence: a run
+ listed here is deliverable and is only queued for capacity, so the sweep must
+ leave it alone (Codex P1).
+ """
+
+ return {
+ pending.id
+ for pending in self.request_store.list_pending()
+ if self._transport_ready_for_request(pending)
+ }
+
+ def _release_leaked_session_locks(self) -> set[str]:
+ """Drop per-session locks whose owning execution no longer exists.
+
+ A terminalized row is only half the repair. ``_inflight_sessions`` gates
+ dispatch for the whole conversation, so an entry that outlives its execution
+ wedges every later run for that session — the database reads honest and the
+ session still never drains.
+
+ ``_on_execution_done`` normally releases the lock, so the only way one
+ survives is if that callback was never attached (``asyncio.create_task``
+ raising after the lock was taken). Keying off the recorded owner rather than
+ off the swept rows is what makes this safe in the other direction: a lock
+ held by a live task is never freed, so this can never let two turns run
+ concurrently in one session.
+ """
+
+ leaked = {
+ lock_key: run_id
+ for lock_key, run_id in self._session_lock_owners.items()
+ if run_id not in self._inflight_executions
+ }
+ for lock_key, run_id in leaked.items():
+ self._session_lock_owners.pop(lock_key, None)
+ self._inflight_sessions.discard(lock_key)
+ logger.warning(
+ "Released leaked session lock %s owned by dead execution %s", lock_key, run_id
+ )
+ if leaked:
+ # The wedge is gone; re-check the queue now instead of waiting for the
+ # next store change, which a stuck session has no reason to produce.
+ self._drain_dirty = True
+ return set(leaked)
+
+ def _sweep_stale_runs(self) -> None:
+ """Terminalize runs that nothing is executing any more (plan §4).
+
+ Rides the existing store tick because the leak it repairs is the ABSENCE of
+ an event — a turn that never reported back, a transport that never came up, a
+ queue gate that never reopened — so nothing will ever wake it up. Rate
+ limited to ``harness_run_sweep_interval_seconds`` so the ordinary case
+ (nothing stale) costs one indexed SELECT per interval, not one per tick.
+ """
+
+ interval = self._runtime_seconds(
+ "harness_run_sweep_interval_seconds", DEFAULT_HARNESS_RUN_SWEEP_INTERVAL_SECONDS
+ )
+ if interval <= 0:
+ return
+ now = time.monotonic()
+ # The first tick after startup sweeps immediately: a restart is exactly when
+ # the previous process's orphans are sitting there waiting to be found.
+ if self._last_sweep_at and now - self._last_sweep_at < interval:
+ return
+ self._last_sweep_at = now
+ try:
+ owned_run_ids = self._owned_agent_run_ids()
+ except Exception:
+ # Fail closed. "Nobody owns these runs" and "I cannot tell who owns them"
+ # are opposite answers, and acting on the second would fail runs that are
+ # still streaming. Skipping costs one interval of staleness.
+ if not self._sweep_ownership_unavailable_logged:
+ self._sweep_ownership_unavailable_logged = True
+ logger.warning("Skipping stale-run sweep: run ownership is unknown", exc_info=True)
+ else:
+ logger.debug("Skipping stale-run sweep: run ownership is unknown", exc_info=True)
+ return
+ self._sweep_ownership_unavailable_logged = False
+ queued_ttl_seconds = self._runtime_seconds(
+ "harness_run_queued_ttl_seconds", DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDS
+ )
+ try:
+ deliverable_run_ids = self._deliverable_queued_run_ids()
+ except Exception:
+ # Same fail-closed posture as ownership, expressed as "disable the class":
+ # a recorded transport reason is only half the evidence, and without the
+ # live half a deliverable run could be failed for a transport that is back.
+ logger.warning(
+ "Skipping transport-stale sweep: queue deliverability is unknown", exc_info=True
+ )
+ deliverable_run_ids = set()
+ queued_ttl_seconds = 0
+ hold_ttl_seconds = self._runtime_seconds(
+ "harness_run_hold_ttl_seconds", DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS
+ )
+ try:
+ busy_session_ids = self._busy_session_ids()
+ except Exception:
+ # Fail closed by disabling the class, same posture as deliverability: a hold
+ # is only abandoned if no live turn explains it, and "I cannot tell which
+ # sessions are busy" would fail a run the gate is about to flush.
+ logger.warning(
+ "Skipping queue-hold sweep: live session turns are unknown", exc_info=True
+ )
+ busy_session_ids = set()
+ hold_ttl_seconds = 0
+ swept = self.request_store.sweep_stale_runs(
+ owned_run_ids=owned_run_ids,
+ deliverable_run_ids=deliverable_run_ids,
+ busy_session_ids=busy_session_ids,
+ error_texts={reason: self._t(key) for reason, key in SWEEP_I18N_KEYS.items()},
+ orphan_grace_seconds=self._runtime_seconds(
+ "harness_run_orphan_grace_seconds", DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS
+ ),
+ queued_ttl_seconds=queued_ttl_seconds,
+ hold_ttl_seconds=hold_ttl_seconds,
+ )
+ # Unconditional: the in-memory wedge and the stale rows are independent
+ # failures, and either can outlive the other.
+ self._release_leaked_session_locks()
+ if swept:
+ self._drain_dirty = True
+ self._retire_swept_queue_segments(swept)
+
+ def _retire_swept_queue_segments(self, swept: list[Any]) -> None:
+ """Drop the persisted Workbench queue rows a swept run left behind.
+
+ Terminalizing the row is not enough for an avibe session: the queued
+ ``messages`` segment that carried the run's prompt is not reclaimed by
+ ``recover_persisted_agent_run_queue`` — recovery ignores references whose run
+ is no longer ``queued`` — so the Session keeps showing stale pending input
+ until an unrelated user send happens to force ``flush_queue`` to retire it
+ (Codex P2). Reconcile immediately from the ids the sweep already reported.
+
+ Retirement is scoped to each run's own ``agent_run:<id>`` native id, so it can
+ never touch a live sibling's row, and a per-run failure is logged and skipped
+ rather than aborting the rest — an honest DB row plus one stale queue segment
+ beats leaving every other session unreconciled.
+ """
+
+ touched: set[str] = set()
+ for run in swept:
+ session_id = str(getattr(run, "session_id", "") or "").strip()
+ run_id = str(getattr(run, "run_id", "") or "").strip()
+ if not session_id or not run_id:
+ continue
+ try:
+ retired = _retire_stale_agent_run_queue_rows(
+ session_id=session_id, execution_ids=[run_id]
+ )
+ except Exception:
+ logger.warning(
+ "sweep: failed to retire queue rows for run %s", run_id, exc_info=True
+ )
+ continue
+ if retired:
+ touched.add(session_id)
+ if not touched:
+ return
+ try:
+ from core.inbox_events import bus
+ except Exception:
+ logger.debug("sweep: inbox bus unavailable for queue.updated", exc_info=True)
+ return
+ for session_id in sorted(touched):
+ try:
+ bus.publish("queue.updated", {"session_id": session_id})
+ except Exception:
+ logger.debug("sweep: queue.updated publish failed", exc_info=True)
+
def reconcile_jobs(self) -> None:
if not self._owns_service_instance():
return
@@ -2021,12 +2377,22 @@ class ScheduledTaskService:
if pending.id in self._inflight_executions:
continue
if not self._transport_ready_for_request(pending):
+ # Record it: this is the only skip reason that eventually makes the row
+ # sweepable, and the sweep reads the reason rather than re-deriving
+ # readiness. Transition-only inside the store, so a transport that
+ # stays down does not turn this into a per-tick write.
+ self.request_store.record_skip_reason(
+ pending.id, reason=SKIP_REASON_TRANSPORT_UNAVAILABLE
+ )
continue
lock_key = self._execution_lock_key(pending)
if lock_key is not None and lock_key in self._inflight_sessions:
# A turn for this conversation is already running; keep this
# one queued so we never run two turns for one session at once.
# The next drain tick picks it up once the session frees.
+ # Recorded so it can clear a stale transport reason — this row is
+ # making progress and must not look sweepable.
+ self.request_store.record_skip_reason(pending.id, reason=SKIP_REASON_SESSION_BUSY)
continue
request = self.request_store.claim(pending.id)
if request is None:
@@ -2336,6 +2702,10 @@ class ScheduledTaskService:
def _spawn_execution(self, request: TaskExecutionRequest, lock_key: Optional[str]) -> None:
if lock_key is not None:
self._inflight_sessions.add(lock_key)
+ # Recorded BEFORE ``create_task`` so the one way this lock can leak — the
+ # task never being created, hence ``_on_execution_done`` never attached —
+ # still leaves an owner the sweep can trace back to a dead execution.
+ self._session_lock_owners[lock_key] = request.id
task = asyncio.create_task(self._execute_claimed_request(request))
self._inflight_executions[request.id] = task
task.add_done_callback(
@@ -2348,6 +2718,11 @@ class ScheduledTaskService:
self._inflight_executions.pop(request_id, None)
if lock_key is not None:
self._inflight_sessions.discard(lock_key)
+ # Only if it is still OURS: a later execution may already have taken the
+ # same key, and stealing its owner entry would make the sweep read that
+ # live lock as leaked.
+ if self._session_lock_owners.get(lock_key) == request_id:
+ self._session_lock_owners.pop(lock_key, None)
self._drain_dirty = True
# ``_execute_claimed_request`` already records failures and requeues on
# cancellation; this only surfaces unexpected crashes in the wrapper.
@@ -2360,6 +2735,7 @@ class ScheduledTaskService:
async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
error: Optional[str] = None
should_complete = True
+ settled_out_of_band = False
coalesced_completion_ids: list[str] = _live_coalesced_agent_run_ids(request) or []
task_id = request.task_id
session_key = request.session_key
@@ -2407,7 +2783,11 @@ class ScheduledTaskService:
)
elif request.request_type == "agent_run":
message = _agent_run_message_for_request(request)
- if not message:
+ if not message.strip():
+ # Whitespace-only counts as absent. ``MessageHandler`` returns
+ # early for a blank prompt without dispatching an agent, so
+ # accepting one here produced a run that could never receive a
+ # terminal result. Fail it at the door instead.
raise ValueError("agent run requires message")
if not (request.session_id or request.session_key):
raise ValueError("agent run currently requires session_id or a resolvable session target")
@@ -2429,6 +2809,7 @@ class ScheduledTaskService:
)
error = result.error
should_complete = result.complete_on_return
+ settled_out_of_band = result.settled_out_of_band
if result.requeue_on_return:
self.request_store.requeue(request.id, metadata={"workbench_queue_holds_run": True})
coalesced_completion_ids = list(result.coalesced_completion_ids)
@@ -2442,6 +2823,7 @@ class ScheduledTaskService:
error = str(exc)
logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
should_complete = True
+ settled_out_of_band = False
finally:
if should_complete:
if coalesced_completion_ids:
@@ -2460,6 +2842,10 @@ class ScheduledTaskService:
session_key=session_key,
session_id=session_id,
)
+ if should_complete or settled_out_of_band:
+ # An out-of-band settlement still made this run terminal, so it owes
+ # the same follow-through as ``complete()``: deliver the callback and
+ # let the next queued turn for this session start.
await self._drain_callbacks()
if request.request_type == "agent_run" and session_id:
manager = getattr(self.controller, "session_turns", None)
@@ -2536,8 +2922,15 @@ class ScheduledTaskService:
prompt is submitted, while their actual result arrives later through
``emit_agent_message``. Use the shared dispatch sink so the run stays
``running`` until that terminal result is emitted.
+
+ The run may only stay ``running`` when the sink was released BY that terminal
+ result. Any other release (no agent was dispatched, an external stop, a
+ refused concurrent turn) means no result will ever arrive, so this method
+ settles the run itself — otherwise the row is a permanent zombie, and its
+ callback and session status hang with it. See
+ ``docs/plans/agent-run-zombie-settlement.md``.
"""
- from core.services.dispatch import SOURCE_SCHEDULED, dispatch_turn
+ from core.services.dispatch import SOURCE_SCHEDULED, dispatch_turn_with_outcome
target_info = resolve_session_id_target(session_id) if session_id else None
target = target_info.session_key if target_info else parse_session_key(session_key or "")
@@ -2598,16 +2991,125 @@ class ScheduledTaskService:
async def _noop_chunk(_envelope: dict) -> None:
return None
- result = await dispatch_turn(
+ outcome = await dispatch_turn_with_outcome(
self.controller,
context,
message,
source=SOURCE_SCHEDULED,
on_chunk=_noop_chunk,
)
- if result:
- return AgentRunExecutionResult(error=str(result), complete_on_return=True)
- return AgentRunExecutionResult(error=None, complete_on_return=False)
+ if outcome.error:
+ return AgentRunExecutionResult(error=str(outcome.error), complete_on_return=True)
+ if outcome.settled_by is not None and outcome.settled_by not in SETTLEMENTS_WITHOUT_RESULT:
+ # Somebody else owns this run's terminal state: either the backend emitted
+ # its real terminal result (``terminal_result``), or a terminal output
+ # closed the turn while deliberately keeping the run elsewhere
+ # (``turn_only_result`` — the requeued Activity behind a Claude delivery
+ # failure). Tested as membership rather than "anything but
+ # ``terminal_result``" so a future release reason cannot be misread as a
+ # zombie (Codex P1).
+ return AgentRunExecutionResult(error=None, complete_on_return=False)
+ settled_by = outcome.settled_by or SETTLED_BY_NO_TERMINAL_RESULT
+ if outcome.settled_by is None:
+ # Unreachable: this path always passes ``on_chunk``. Settle rather than
+ # trust an unexplained release — a wrong ``failed`` is recoverable, a
+ # zombie is not.
+ logger.warning(
+ "agent run %s dispatched without a turn sink; settling as %s",
+ execution_id,
+ settled_by,
+ )
+ error_text = self._t(
+ SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT])
+ )
+ if not self._settle_agent_run_without_result(execution_id, settled_by=settled_by, error=error_text):
+ # Legacy file store: no guarded writer exists, so fall back to the
+ # ``finally`` completion path rather than leave the run open.
+ return AgentRunExecutionResult(error=error_text, complete_on_return=True)
+ return AgentRunExecutionResult(
+ error=error_text,
+ complete_on_return=False,
+ settled_out_of_band=True,
+ )
+
+ def settle_agent_runs_without_result(
+ self,
+ execution_ids: Sequence[str],
+ *,
+ settled_by: str,
+ ) -> None:
+ """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
+ avibe-targeted run goes through ``session_turn_gate.submit_scheduled``, which
+ returns while the turn is still running, so ``SessionTurnManager`` calls this
+ when that turn ends without a result (Codex P1). Same guarded writer, same
+ 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.
+ """
+
+ settled_any = False
+ error_text = self._t(
+ SETTLEMENT_I18N_KEYS.get(settled_by, SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT])
+ )
+ for raw_execution_id in execution_ids:
+ execution_id = str(raw_execution_id or "").strip()
+ if not execution_id:
+ continue
+ if self._settle_agent_run_without_result(
+ execution_id, settled_by=settled_by, error=error_text
+ ):
+ settled_any = True
+ if settled_any:
+ self._drain_dirty = True
+
+ def _settle_agent_run_without_result(
+ self,
+ execution_id: str,
+ *,
+ settled_by: str,
+ error: str,
+ ) -> bool:
+ """Terminalize a run whose turn ended without a terminal result.
+
+ Deliberately NOT routed through ``_execute_claimed_request``'s ``finally``:
+ that path writes via ``update_run_status``, whose UPDATE has no status
+ predicate and would clobber a row a concurrent ``vibe runs cancel`` already
+ settled. ``settle_without_result`` is scoped to ``queued|running`` and maps a
+ cancel-requested run to ``canceled`` inside its own transaction.
+
+ The terminal status comes from ``SETTLEMENT_TERMINAL_STATUS``: an explicit
+ user stop is ``canceled``, an infrastructure fault is ``failed``.
+
+ Returns ``True`` when this store owns the terminal write (whether or not this
+ call is the one that performed it — an already-terminal row is settled too),
+ and ``False`` only when the store has no guarded writer at all.
+ """
+
+ if not self.request_store.supports_guarded_settlement():
+ return False
+ settled = self.request_store.settle_without_result(
+ execution_id,
+ terminal_status=SETTLEMENT_TERMINAL_STATUS.get(settled_by, "failed"),
+ error=error,
+ metadata={"interrupt_reason": settled_by},
+ )
+ if settled is None:
+ logger.info(
+ "Agent run %s was already settled elsewhere (%s)",
+ execution_id,
+ settled_by,
+ )
+ else:
+ logger.warning(
+ "Agent run %s settled %s without a terminal result (%s)",
+ execution_id,
+ settled,
+ settled_by,
+ )
+ return True
def _reserve_runtime_session(
self,
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index cf0cd2fb0..71959ce6c 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -29,8 +29,13 @@ from __future__ import annotations
import asyncio
import logging
import uuid
+from dataclasses import dataclass
from typing import Awaitable, Callable, Optional, TYPE_CHECKING
+from core.run_settlement import (
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
+)
from modules.im import MessageContext
if TYPE_CHECKING: # pragma: no cover - typing-only
@@ -46,6 +51,27 @@ SOURCE_HUMAN = "human"
SOURCE_SCHEDULED = "scheduled"
+@dataclass(frozen=True)
+class TurnDispatchOutcome:
+ """What a dispatched turn produced, and how its waiter was released.
+
+ ``settled_by`` is the settlement vocabulary from ``core.run_settlement``. It is
+ ``None`` for exactly one case — a caller that passed no ``on_chunk``, so no sink
+ was ever registered and there was nothing to wait on. Every streaming caller
+ gets a real value, including the concurrent-turn refusal below which returns
+ before a sink exists.
+
+ A caller that owns a durable record of the turn (``ScheduledTaskService`` and
+ its ``agent_runs`` row) MUST branch on this: only
+ ``SETTLED_BY_TERMINAL_RESULT`` means "the backend emitted a terminal result, so
+ the out-of-band writer will settle the record". Every other value means no
+ terminal result is coming and the caller has to settle it itself.
+ """
+
+ error: Optional[str]
+ settled_by: Optional[str]
+
+
async def dispatch_turn(
controller: "Controller",
context: MessageContext,
@@ -56,6 +82,30 @@ async def dispatch_turn(
) -> Optional[str]:
"""Run one agent turn for ``context`` and return the primary message id.
+ Thin wrapper over :func:`dispatch_turn_with_outcome` for the callers that only
+ need the error/message-id channel (IM, web Chat, CLI).
+ """
+
+ outcome = await dispatch_turn_with_outcome(
+ controller,
+ context,
+ text,
+ source=source,
+ on_chunk=on_chunk,
+ )
+ return outcome.error
+
+
+async def dispatch_turn_with_outcome(
+ controller: "Controller",
+ context: MessageContext,
+ text: str,
+ *,
+ source: str = SOURCE_HUMAN,
+ on_chunk: Optional[ChunkCallback] = None,
+) -> TurnDispatchOutcome:
+ """Run one agent turn for ``context`` and report how its waiter was released.
+
``source`` selects between the human-initiated and scheduler-initiated
paths in ``MessageHandler``; today they only differ in source tagging.
@@ -80,7 +130,7 @@ async def dispatch_turn(
if on_chunk is None:
# IM / CLI: fire-and-forget; no live stream to hold open.
- return await _run()
+ return TurnDispatchOutcome(error=await _run(), settled_by=None)
session_key = controller._get_session_key(context)
if controller.get_turn_sink(session_key) is not None:
@@ -92,7 +142,11 @@ async def dispatch_turn(
# with a terminal chunk instead of racing — the in-flight turn keeps
# streaming undisturbed.
await on_chunk({"kind": "error", "text": controller._t("error.streamTurnInProgress"), "message_id": None})
- return None
+ # No sink was registered for THIS turn, so there is no sink to carry the
+ # settlement — report it directly. A caller holding a durable record (an
+ # ``agent_runs`` row) must settle it: this turn never reached a backend, so
+ # no terminal result will ever arrive for it.
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_REFUSED_CONCURRENT_TURN)
# Tag this turn with a unique token, stamped into the context the agent
# receiver will carry. ``_stream_chunk`` only forwards an emit to the sink
# when the emit's context token matches the registered sink's token, so a
@@ -118,7 +172,16 @@ async def dispatch_turn(
# user Stop/cancel cancels this task; the ``CancelledError`` propagates
# out of ``done.wait()`` and the ``finally`` below pops the sink.
await done.wait()
- return result
+ # Read the settlement off OUR sink before the ``finally`` pops it. A sink
+ # released without a terminal result (``mark_turn_complete`` / an external
+ # stop) leaves no other trace, so this is the only place the distinction
+ # survives. Default defensively to "no terminal result": an unexplained
+ # release must never be reported as a healthy turn.
+ sink = controller.get_turn_sink(session_key)
+ settled_by = SETTLED_BY_NO_TERMINAL_RESULT
+ if isinstance(sink, dict) and sink.get("done_event") is done:
+ settled_by = str(sink.get("settled_by") or SETTLED_BY_NO_TERMINAL_RESULT)
+ return TurnDispatchOutcome(error=result, settled_by=settled_by)
finally:
# Pass our own done event so a turn that was superseded by a newer
# concurrent turn doesn't evict the newer turn's sink on cleanup.
diff --git a/core/session_turns.py b/core/session_turns.py
index be9f45bd6..bd63207ce 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -28,7 +28,14 @@ from sqlalchemy.engine import Engine
from sqlalchemy.exc import IntegrityError
from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA
-from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
+from core.run_settlement import (
+ SETTLEMENTS_WITHOUT_RESULT,
+ SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+)
+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn_with_outcome
from storage import messages_service
from storage.db import get_cached_sqlite_engine
from storage.background import normalize_run_status
@@ -564,6 +571,15 @@ class Turn:
started_at: str = ""
flush_on_cancel: bool = False
stop_no_flush: bool = False
+ #: WHY this turn's task was cancelled, in the ``core.run_settlement``
+ #: vocabulary — set by the canceller BEFORE ``task.cancel()`` so ``_run`` can
+ #: attribute the run it owns correctly. ``None`` means a plain user Stop
+ #: (``cancel`` / ``send_now``), which is the default reading of a cancelled
+ #: turn; a backend runtime refresh sets ``SETTLED_BY_BACKEND_REFRESH`` so a
+ #: routine ``agents.*`` reconciliation is not reported as if the user pressed
+ #: Stop (Codex P1). It rides on the Turn for the same reason the flush intents
+ #: do: it retires when the turn is popped, with no parallel set to leak.
+ cancel_settled_by: Optional[str] = None
class SessionTurnManager:
@@ -613,6 +629,120 @@ class SessionTurnManager:
"""True when ``session_id`` has an active (RUNNING) turn."""
return bool(session_id) and session_id in self.in_flight
+ @staticmethod
+ def _agent_run_ids_from_spec(spec: Any) -> set[str]:
+ """Every ``agent_runs`` id a turn started under this spec is settling."""
+ if not isinstance(spec, dict):
+ return set()
+ found: set[str] = set()
+ primary = str(spec.get("task_execution_id") or "").strip()
+ if primary:
+ found.add(primary)
+ coalesced = spec.get("coalesced_queue")
+ execution_ids = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
+ if isinstance(execution_ids, list):
+ for value in execution_ids:
+ execution_id = str(value or "").strip()
+ if execution_id:
+ found.add(execution_id)
+ return found
+
+ 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.
+
+ The turn lane needs its own settlement because the harness cannot do it:
+ ``_execute_agent_run`` hands an avibe-targeted run to
+ ``session_turn_gate.submit_scheduled`` and returns with
+ ``complete_on_return=False`` while the turn is still running, so the outcome
+ this turn eventually produces is never seen there (Codex P1). Without this, a
+ stopped Workbench run whose backend emits no terminal result stays ``running``
+ until the staleness sweep relabels it ``orphaned`` — or forever when the sweep
+ is disabled.
+
+ Only a settlement that means "no result is coming" may terminalize the row —
+ membership in ``SETTLEMENTS_WITHOUT_RESULT``, not "anything but
+ ``terminal_result``". A real terminal output that completes the turn while
+ leaving the run to another owner (``turn_only_result``: the requeued Activity
+ behind a Claude delivery failure) must be left alone, or its run is failed and
+ its callback fired before the retry runs (Codex P1). ``None`` means no sink
+ existed, so there is nothing to conclude — do not guess. A coalesced turn settles EVERY id it owns, matching
+ ``owned_agent_run_ids``. A plain Chat turn carries no run attribution and no-ops
+ here. The write itself is the guarded first-writer-wins one, so racing an honest
+ terminal result is safe in both directions.
+ """
+
+ if settled_by not in SETTLEMENTS_WITHOUT_RESULT:
+ return
+ run_ids = self._agent_run_ids_from_spec(getattr(context, "platform_specific", None))
+ if not run_ids:
+ return
+ service = getattr(self.controller, "scheduled_task_service", None) if self.controller else None
+ settle = getattr(service, "settle_agent_runs_without_result", None)
+ if not callable(settle):
+ # A fake/partial controller (tests, a boot window before the service
+ # exists). The sweep remains the backstop; guessing is not an option.
+ logger.debug("turn settlement: no harness settlement writer available")
+ return
+ try:
+ settle(sorted(run_ids), settled_by=settled_by)
+ except Exception:
+ logger.warning(
+ "turn settlement: failed to settle runs %s as %s",
+ sorted(run_ids),
+ settled_by,
+ exc_info=True,
+ )
+
+ def owned_agent_run_ids(self) -> set[str]:
+ """Run ids a live turn in THIS process is currently executing.
+
+ The staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.1) needs
+ to know which ``running`` rows still have an owner before it declares any of
+ them orphaned. ``ScheduledTaskService`` can answer for its own drain path, but
+ the workbench lane never enters ``_inflight_executions``:
+ ``claim_queued_runs_for_workbench_in_connection`` claims rows that
+ ``flush_queue`` executes. ``Turn`` carries no run-id field, so the ids are read
+ off the context each turn started under — the same ``task_execution_id`` /
+ ``coalesced_queue`` keys ``_turn_sink_identity`` reads.
+
+ A coalesced turn owns EVERY id it is settling, not just the primary, or the
+ sweep would fail the siblings out from under a live flush.
+
+ Live streaming sinks are unioned in as well. They carry the same attribution
+ and are registered/popped on a different boundary than ``in_flight``, so a run
+ visible through either one is owned. Over-reporting an owner only delays a
+ sweep; under-reporting one fails a live run.
+
+ A malformed context contributes no ids rather than raising — but note the
+ caller must still fail closed if this method is missing or raises outright,
+ because "no owners" and "cannot tell" are opposite answers.
+ """
+ owned: set[str] = set()
+ for turn in list(self.in_flight.values()):
+ owned |= self._agent_run_ids_from_spec(getattr(turn.context, "platform_specific", None))
+ for sink in list(self.active_turn_sinks.values()):
+ owned |= self._agent_run_ids_from_spec(sink)
+ return owned
+
+ def busy_session_ids(self) -> set[str]:
+ """Sessions whose gate is occupied by a live turn RIGHT NOW.
+
+ This is the exemption the staleness sweep needs for the ``queue_hold_expired``
+ class, and it is deliberately NOT expressible through
+ :meth:`owned_agent_run_ids`: a run the gate parked behind a live turn is not one
+ the live turn is executing, so it has no owner to report it, yet it is not
+ abandoned either — ``flush_queue`` will pick it up when the turn ends. Without
+ this, a legitimate Workbench turn lasting longer than the hold TTL had its own
+ queued follower failed underneath it (Codex P2).
+
+ ``in_flight`` is the right predicate because it is the same map
+ ``submit``/``submit_scheduled`` consult before answering ``enqueued`` — the very
+ decision that created the hold. Sinks are not unioned in here: they are keyed by
+ session KEY, not session id, and a streaming turn always has an ``in_flight``
+ entry anyway.
+ """
+ return {session_id for session_id in list(self.in_flight) if session_id}
+
def bind_context(self, build_context: Callable[[str], "MessageContext"]) -> None:
"""Inject the routing-context builder (it lives in ``internal_server``) once
the gate is built, so ``flush_queue`` can rebuild a queued follow-up's
@@ -766,8 +896,14 @@ class SessionTurnManager:
async def _runner() -> None:
cancelled = False
failed = False
+ # How this turn's waiter was released, in the ``core.run_settlement``
+ # vocabulary. Anything other than a real terminal result means no result
+ # is coming, so an ``agent_runs`` row this turn owns has to be settled
+ # here — the gate lane returns to ``_execute_agent_run`` long before the
+ # turn ends, so nobody downstream can do it (Codex P1).
+ settled_by: Optional[str] = None
try:
- await dispatch_turn(
+ outcome = await dispatch_turn_with_outcome(
self.controller,
context,
text,
@@ -782,8 +918,14 @@ class SessionTurnManager:
# scheduled turn (Codex P2).
on_chunk=self._noop_chunk,
)
+ settled_by = outcome.settled_by
except asyncio.CancelledError:
cancelled = True
+ # Do NOT decide the reason here: the canceller knows it, and it is
+ # recorded on the Turn (``cancel_settled_by``) which is only popped
+ # in the ``finally`` below. A plain Stop leaves it unset and reads
+ # as ``SETTLED_BY_STOPPED``; a backend runtime refresh sets its own
+ # value so it is not misreported as a user stop (Codex P1).
raise
except Exception:
# dispatch_turn raised before any backend turn was actually
@@ -792,6 +934,7 @@ class SessionTurnManager:
# NOT auto-flush the send-while-busy queue onto a fresh turn (Codex
# P2). (An explicit send-now flush_on_cancel still flushes.)
failed = True
+ settled_by = SETTLED_BY_NO_TERMINAL_RESULT
logger.exception("internal async dispatch failed for session=%s", session_id)
finally:
if isinstance(session_id, str):
@@ -802,6 +945,15 @@ class SessionTurnManager:
turn = self.in_flight.pop(session_id, None)
if turn is not None:
bus.publish("turn.end", {"session_id": session_id})
+ if cancelled:
+ # Attribute the cancellation to whoever caused it. The Turn
+ # carries the cause when the canceller had a more specific one
+ # than "the user stopped this"; a plain Stop / send-now leaves
+ # it unset, and ``stopped`` (→ ``canceled``) stays the default
+ # reading of a cancelled turn.
+ settled_by = (
+ getattr(turn, "cancel_settled_by", None) if turn is not None else None
+ ) or SETTLED_BY_STOPPED
# Converge the no-terminal-result outcome onto the OUTBOUND status
# chokepoint. The normal path already emitted a terminal result;
# only ``failed`` reaches here without one: dispatch raised before
@@ -815,6 +967,11 @@ class SessionTurnManager:
is_error=True,
output=terminal_turn_output(),
)
+ # Settle before flushing: the next turn must not start while a run
+ # this one owned is still ``running``. Placed after the failure
+ # emit above so the honest outbound terminal writes first and this
+ # guarded write degrades to a no-op.
+ self._settle_turn_owned_agent_runs(context, settled_by)
# Flush intents ride on the popped Turn (set by cancel / send_now),
# so they retire with it — no parallel set to discard. Don't flush
# after a plain Stop (keep the queue) or a terminal failure; send-now
@@ -1371,6 +1528,11 @@ class SessionTurnManager:
if turn_backend and turn_backend != backend:
continue
turn.stop_no_flush = True
+ # Record the cause BEFORE cancelling: this is a runtime refresh, not a
+ # user Stop, so a scheduled run this turn owns must not settle as
+ # ``canceled`` with the user-stop explanation (Codex P1). ``_run`` reads
+ # it off the Turn when it pops it.
+ turn.cancel_settled_by = SETTLED_BY_BACKEND_REFRESH
if turn.task.done():
self.in_flight.pop(session_id, None)
from core.inbox_events import bus
@@ -1838,12 +2000,25 @@ class SessionTurnManager:
This is a fallback for stop paths that successfully interrupt a backend
but do not emit a terminal result. It only releases the dispatch waiter;
- run completion is still owned by the backend's terminal emit. Current
- live backends emit that terminal before ``handle_stop`` returns, and the
- bound stop context carries the original agent-run attribution so the emit
- records the run terminal. The identity guard is intentionally object-based
- so a late stop cannot complete a newer sink registered under the same
- session key.
+ run completion is still owned by the backend's terminal emit when one
+ arrives, and the bound stop context carries the original agent-run
+ attribution so that emit records the run terminal. The identity guard is
+ intentionally object-based so a late stop cannot complete a newer sink
+ registered under the same session key.
+
+ Ordering against a real terminal result is resolved by precedence, not by
+ timing luck. A terminal that lands *before* this call finds ``done`` already
+ set and we bail out, leaving ``settled_by="terminal_result"`` so the run
+ settles from its true result. A terminal that lands *after* the stop was
+ acknowledged cannot take the reason back — the dispatcher refuses to overwrite
+ a recorded ``stopped`` — so this run is always settled through the ``canceled``
+ mapping (``SETTLEMENT_TERMINAL_STATUS``). Whether ``canceled`` reaches the row
+ is then ordinary first-writer-wins: both writers are scoped to
+ ``queued|running``, so if the result's own row write got there first the run
+ keeps ``succeeded``. That is deliberate rather than lossy — the backend really
+ did finish, its text is recorded in the run's outputs either way, and forcing
+ ``canceled`` over an existing terminal status would mean breaking the single
+ guarantee every other settlement path relies on.
"""
if not isinstance(binding, dict):
return False
@@ -1860,6 +2035,10 @@ class SessionTurnManager:
is_set = getattr(done, "is_set", None)
if callable(is_set) and is_set():
return False
+ # A stop that interrupted the backend without a terminal result: record it so
+ # ``dispatch_turn``'s caller settles the run instead of leaving it ``running``
+ # forever. ``setdefault`` keeps an already-recorded real terminal result.
+ sink.setdefault("settled_by", SETTLED_BY_STOPPED)
done.set()
return True
diff --git a/docs/plans/agent-run-zombie-settlement.md b/docs/plans/agent-run-zombie-settlement.md
new file mode 100644
index 000000000..791acd629
--- /dev/null
+++ b/docs/plans/agent-run-zombie-settlement.md
@@ -0,0 +1,955 @@
+# Agent Run Zombie Settlement: honest terminal state + staleness sweep
+
+Status: reviewed by `codex-expert` (APPROVE WITH CHANGES, 2026-07-25); all six blocking
+items folded in below. **PR-A (Gap A) implemented** — see §3.4 "As implemented" and §5.1.
+**PR-B (Gap B, §4) not started.**
+
+Branch: `fix/agent-run-zombie-runs` (from `master` @ `5921ad39`)
+
+## 1. Background and relation to the approved plan
+
+`docs/plans/harness-run-reliability.md` (branch `fix/harness-run-reconcile`, design
+approved) owns seven PRs for harness run reliability. This plan is a **delta**: two
+zombie classes that inventory does not cover, both specific to
+`run_type='agent_run'`.
+
+Verified corrections carried over from that plan (do not re-litigate):
+
+- `agent_runs.pid` is **never populated** — the only writer clears it
+ (`storage/background.py:1585`). Liveness cannot be probed via `pid`.
+- `recover_processing_runs` (`storage/background.py:1563-1588`) exists but
+ **requeues** `running`→`queued` at controller construction; per **D1** it must
+ terminalize instead. That change belongs to PR7's safety mitigations, not here.
+- The status vocabulary is closed: `queued|running|succeeded|failed|canceled`.
+ No new status value. Interruption is expressed as a terminal status + `error` +
+ `metadata.interrupt_reason` (D1).
+- Reconcile must use **guarded writers only** (`defer_run_terminal` /
+ `settle_deferred_run` / `record_run_output`, whose UPDATEs are scoped to
+ `queued|running` and resolve races through `_stronger_terminal_status`).
+ `update_run_status` is unguarded and must not be used for reconcile.
+
+### 1.1 Gap A — a released sink with no terminal emit leaves the run `running` forever
+
+`_execute_agent_run` deliberately opts out of the `finally` terminal write:
+`AgentRunExecutionResult(complete_on_return=False)` at `core/scheduled_tasks.py:2596`
+and `:2610`, so `should_complete=False` at `:2431` and the `finally` (`:2445-2462`)
+writes nothing. The docstring (`:2532-2538`) states the contract: *"the run stays
+`running` until that terminal result is emitted."*
+
+There are exactly two places that release the dispatch waiter:
+
+| Releaser | file:line | Emits a terminal result? |
+|---|---|---|
+| `_stream_chunk`, `completes_turn` + token match | `core/message_dispatcher.py:104-122` | **Yes** — the honest path |
+| `Controller.mark_turn_complete` | `core/controller.py:1099-1122` | **No** — only `done_event.set()` |
+| `settle_bound_turn_sink` (Running-tab End) | `core/session_turns.py:1836-1860` | No (documented fallback; live backends normally emit first) |
+
+`mark_turn_complete` is called from `_handle_turn`'s `finally` whenever no agent was
+dispatched (`core/handlers/message_handler.py:576-585`). `dispatch_turn` then returns
+`None` (`core/services/dispatch.py:120-121`), which `_execute_agent_run:2610` reads as
+"submitted, terminal will arrive later" — indistinguishable from the honest
+fire-and-forget case. Result: `status=running` forever, plus two derived zombies
+(`callback_status` stays `pending` because `list_pending_callbacks` requires a terminal
+status + `completed_at`, `storage/background.py:964-979`; `agent_sessions.agent_status`
+stays `running` until the next controller restart).
+
+**Reachable today, no infrastructure fault needed:** a whitespace-only message.
+`_agent_run_message_for_request` rejects only falsy values (`core/scheduled_tasks.py:2410`),
+while `_handle_turn` returns early on `not message.strip()` (`core/handlers/message_handler.py:103-106`).
+The other no-dispatch early returns (`:130`, `:137`, `:145`) are `is_human`-gated so
+they are unreachable for a harness run; the missing-backend path is safe because it
+emits a terminal error and returns a truthy string → `failed`. So the general class is
+"any current or future no-dispatch early return", and the blank message is today's
+concrete instance.
+
+`dispatch_turn`'s concurrent-turn refusal (`core/services/dispatch.py:86-95`) has the
+same DB symptom but a **different shape**, and an earlier draft of this plan was wrong
+about it: that branch returns `None` *before* `register_turn_sink` (`:107`) ever runs,
+so there is no sink to inspect and a naive `settled_by` read yields `None`. It must be
+terminalized explicitly — see §3.2/§3.3 and the dedicated test in §5. (Reviewer's
+blocking item 1.)
+
+Coverage overlap, stated plainly: B3's orphan sweep (§4) would eventually catch a
+blank-message zombie too, because once `_execute_claimed_request` returns the run is in
+neither ownership source. Gap A is still worth fixing on its own — it settles instantly
+with a precise reason instead of 60–180 s later with `orphaned` — but the two are
+deliberately belt-and-braces, not a single point of failure.
+
+### 1.2 Gap B — no periodic staleness reconcile; `queued` never ages at all
+
+The only reconciler is startup-only and touches `running` only. Nothing ages a
+`queued` row, so these are permanent until the next restart (and B1/B2 survive
+restart because recovery requeues to the same skipped state):
+
+- **B1 — transport never ready.** `_drain_requests` skips a pending run when
+ `_transport_ready_for_request` is false (`core/scheduled_tasks.py:2023`) with no age
+ limit. A platform later disabled in config, or credentials that never validate,
+ strands every run targeting it.
+- **B2 — workbench queue hold.** `requeue_on_return` stamps
+ `metadata.workbench_queue_holds_run=True` (`:2432`) and `list_pending` filters those
+ rows out (`:1045`). Release depends on
+ `SessionTurnManager.recover_persisted_agent_run_queue` (`core/session_turns.py:1130`)
+ whose five bail-outs (`:1165`, `:1169`, `:1178`, `:1205`, `:1218`) each leave the row
+ invisible to the scheduler; `defer_to_scheduler` also chains, so one stuck row can
+ freeze later held rows in the same session.
+- **B3 — `running` with no owner.** Eviction / silent backend death / a lost receiver
+ leaves `running` with nothing awaiting it. PR2 covers the *eviction* path
+ (cancel + reconcile at teardown); B3 is the residual "no teardown event ever fired"
+ case, which no signal-driven fix can reach.
+
+Explicitly **not** in scope: a turn-duration timeout. `core/services/dispatch.py:66-71`
+and `core/session_turns.py:761` state by design that an agent turn may run for hours
+and must never be killed on a timer. The sweep below is **evidence-based**, not
+timer-based; the only time inputs are grace periods that protect against races.
+
+## 2. Goals / non-goals
+
+Goals:
+
+1. Every `agent_run` reaches a terminal status, or is provably owned by a live
+ execution — no third state.
+2. Stranded `queued` rows fail honestly with a diagnosable reason instead of
+ waiting forever.
+3. Zero behaviour change for the honest path (terminal `result` emitted).
+4. No new status value, no schema migration, no collision with PR1–PR7.
+
+Non-goals: turn-duration timeout; PR7's scheduled/watch settlement change;
+PR2's teardown cancel; PR6's notification ladder (this plan records
+`error` + `interrupt_reason` so PR6 can consume it later, and the callback
+already ships for free once `status` + `completed_at` land).
+
+## 3. Design — Gap A: settlement honesty
+
+### 3.1 Mark why the sink was released (single source of truth)
+
+The sink dict is already the shared per-turn state. Add one key, written at the
+three release sites, using a shared constant module-level enum-ish string set:
+
+- `core/message_dispatcher.py:119` (before `done.set()`) → `sink["settled_by"] = "terminal_result"`
+- `core/controller.py:1120` (`mark_turn_complete`, before `done.set()`) →
+ `sink.setdefault("settled_by", "no_terminal_result")`
+- `core/session_turns.py:settle_bound_turn_sink` → `sink.setdefault("settled_by", "stopped")`
+
+`setdefault` matters: a terminal result that already settled the sink must win over a
+later fallback release.
+
+### 3.2 Report it out of `dispatch_turn`
+
+`dispatch_turn` owns the sink lifecycle, so it is the only place that can read
+`settled_by` before `pop_turn_sink`. Add a typed outcome without touching the existing
+signature (web Chat, IM, and the scheduled path all call `dispatch_turn` today):
+
+```python
+@dataclass(frozen=True)
+class TurnDispatchOutcome:
+ error: Optional[str]
+ settled_by: Optional[str] # None ONLY for a non-streaming caller (on_chunk is None)
+
+async def dispatch_turn_with_outcome(...) -> TurnDispatchOutcome: ...
+async def dispatch_turn(...) -> Optional[str]: # unchanged wrapper
+ return (await dispatch_turn_with_outcome(...)).error
+```
+
+Every streaming path must yield a non-`None` `settled_by`. Specifically the
+concurrent-turn refusal at `:86-95` returns before a sink exists, so it synthesizes
+`settled_by="refused_concurrent_turn"`. `settled_by is None` therefore means exactly
+one thing — "this caller passed no `on_chunk`" — which `_execute_agent_run` never does.
+
+### 3.3 Terminalize in `_execute_agent_run`
+
+At `core/scheduled_tasks.py:2610`, replace the unconditional
+`complete_on_return=False` with:
+
+- `settled_by == "terminal_result"` → `complete_on_return=False` (unchanged; the
+ out-of-band writer owns the terminal state). This is the only branch that keeps the
+ run open.
+- any other `settled_by` (`no_terminal_result` / `stopped` /
+ `refused_concurrent_turn`) → settle the run now (§3.3.1) with an i18n'd `error` and
+ `metadata.interrupt_reason` set to that same value.
+- **Revised during implementation (post-review):** the terminal *status* is no longer
+ uniformly `failed`. `SETTLEMENT_TERMINAL_STATUS` (`core/run_settlement.py`) maps
+ `stopped` → `canceled` and the rest → `failed`. `stopped` is the one settlement
+ carrying explicit user intent (Running-tab End), and `canceled` is already in the
+ closed vocabulary for exactly that — a stopped run did not break, it was called off.
+ This also disarms the `settle_bound_turn_sink` ordering race (§3.5): whichever way
+ it falls, the row reads something true.
+- `settled_by is None` → non-streaming caller, unreachable from this path; settle as
+ `no_terminal_result` and `logger.warning` rather than leaving the run open. Never
+ return `complete_on_return=False` for an unknown settlement.
+
+### 3.3.1 Settle through the guarded writer, not the unguarded `finally`
+
+**O1 resolved (reviewer's blocking item 2):** `update_run_status`
+(`storage/background.py:1042-1125`) has no status predicate — its UPDATE is
+`where(agent_runs.c.id == run_id)` (`:1120`) — so `_execute_claimed_request`'s
+`finally` → `TaskExecutionStore.complete` would clobber a row another actor already
+settled `canceled` (a live `vibe runs cancel` racing this settlement). Since PR-A's new
+branches are exactly the ones that terminalize on return, they must **not** ride that
+chokepoint. Instead `_execute_agent_run` itself calls
+`defer_run_terminal` + `settle_deferred_run` (guarded to `queued|running`, races
+resolved via `_stronger_terminal_status`, `storage/background.py:110-118`) and returns
+`complete_on_return=False` so the `finally` stays a no-op. The `finally` keeps its
+current semantics for every other run type — one behaviour change, one code path.
+
+Consequence: a `canceled` row wins, and a concurrent cancel arriving mid-settlement is
+a genuine TOCTOU that the test in §5 must reproduce, not a static fixture.
+
+### 3.3.2 Required writer extension
+
+**Reviewer's blocking item 3:** `defer_run_terminal` / `settle_deferred_run`
+(`storage/background.py:1392-1519`) write only `result_payload_json` and the terminal
+columns — **neither touches `metadata_json`**. Both Gap A and Gap B need
+`metadata.interrupt_reason`, so extending those two signatures to accept and *merge*
+(never replace) a metadata patch is in-scope implementation work for PR-A, and PR-B
+reuses it. Merge semantics must not drop keys other writers own
+(`workbench_queue_holds_run`, `coalesced_queue`, `source_kind`, …).
+
+Define the `interrupt_reason` values as shared constants in one module so this branch
+(`no_terminal_result`, `stopped`, `refused_concurrent_turn`, `orphaned`,
+`transport_unavailable`, `queue_hold_expired`) and the harness plan's (`evicted`,
+`restarted`, `lifetime_timeout`) cannot drift apart.
+
+### 3.4 Reject a blank harness message at the two doors
+
+Independently of §3.3 (belt and braces, and it keeps the failure legible):
+
+- `core/scheduled_tasks.py:2410` — `if not message or not message.strip(): raise ValueError(...)`
+ → the existing `except Exception` makes it a clean `failed` with a real reason.
+- `vibe/cli.py` `cmd_agent_run` — reject a blank `--message` / `--message-file`
+ before enqueue, so the CLI fails fast instead of creating a row that must then be
+ swept.
+
+**As implemented (PR-A):**
+
+- The CLI door was already closed: `_resolve_message_input` (`vibe/cli.py:1215-1262`)
+ strips and rejects both an empty `--message` and an empty `--message-file`, so no
+ change was needed there. Verified, not assumed.
+- The guard moved one level deeper than planned as well: `TaskExecutionStore.enqueue_agent_run`
+ now raises on a blank message, which closes the door for *every* producer rather
+ than just the CLI. The only in-tree callers are the CLI and `enqueue_session_callback`,
+ which already returns `None` for a blank message, so nothing legitimate is refused.
+- `_execute_claimed_request`'s pre-dispatch check became `not message.strip()`, which
+ covers rows enqueued before the store-level guard existed.
+
+**Out of PR-A scope (deliberate):** the workbench gate path. When
+`_execute_agent_run` hands the turn to `gate.submit_scheduled` (`core/scheduled_tasks.py`
+workbench branch) the gate returns `enqueued` / `duplicate` / `ran`, and the `ran`
+result never passes through `dispatch_turn`, so there is no `settled_by` to branch on.
+Threading a settlement through `SessionTurnGate.submit` → `manager.submit` is a larger
+refactor of a second dispatch lane. Gap B's B3 orphan sweep is the backstop for a
+stranded row on that lane; §3.4's door checks remove the one reachable instance.
+
+### 3.5 Ordering against a real terminal result (added post-review)
+
+The review flagged the one place where PR-A changes a *consequence* rather than only
+fixing a zombie: `settled_by == "stopped"`. `_stop_active_agent`
+(`core/services/running_agents.py:983-990`) awaits `handle_stop`, then calls
+`settle_bound_turn_sink`. Before PR-A, a terminal result that landed after that point
+still won and the row read `succeeded`; PR-A settles the row the moment the stop
+releases the waiter, and both writers are scoped to `queued|running`, so whichever
+lands first wins permanently.
+
+Resolved by precedence rather than by a timing assumption or a timer (a turn-duration
+timeout is explicitly out of this design):
+
+- **Terminal lands first** — `settle_bound_turn_sink` finds `done` already set and
+ returns `False` without stamping, so `settled_by` stays `terminal_result` and the
+ run settles from its true result. This is the common case and it is now pinned by
+ `test_stop_defers_to_a_terminal_result_that_already_landed`.
+- **Terminal lands after the stop was acknowledged** — the `canceled` settlement wins
+ and `record_run_output`'s terminal write becomes a no-op, *provided the stop's row
+ write got there first*. (**Corrected by §5.3 P2**: this bullet originally read as a
+ guarantee, but the stop's row write happens later than its in-memory stamp, and a
+ result arriving in between used to overwrite the reason and skip the `canceled`
+ settlement entirely. The reason is now protected; whether `canceled` reaches the row
+ remains first-writer-wins.) The precedence on the reason is deliberate:
+ `canceled` is true of a run the user stopped regardless of what the backend was
+ about to say, and the late text is still appended to the run's outputs
+ (`record_run_output` returns `recorded=True, terminal_transition=False`). Pinned by
+ `test_late_terminal_result_cannot_reopen_a_stopped_run` so a future change to either
+ writer's guard is a test failure, not a silent flip in who wins.
+
+The docstring on `settle_bound_turn_sink` now states this rule instead of asserting
+that live backends always emit before `handle_stop` returns — that was an unenforced
+claim about async backend timing, and the settlement layer should not depend on it.
+
+## 4. Design — Gap B: evidence-based staleness sweep
+
+### 4.1 Ownership provider (who is legitimately executing a run right now)
+
+A `running` row is owned if **any** of these holds. Two sources, because the
+workbench path never enters `_inflight_executions`:
+
+1. `request.id in ScheduledTaskService._inflight_executions` (the drain path).
+2. `SessionTurnManager` live state references the run id — the workbench claim path
+ (`claim_queued_runs_for_workbench_in_connection`, `storage/background.py:289-347`)
+ claims a `primary_run_id` that is executed through `flush_queue`, not the drain.
+ **Reviewer's blocking item 5 — derivation must be explicit:** `Turn`
+ (`core/session_turns.py:562-566`) carries no run-id field, so
+ `SessionTurnManager.owned_agent_run_ids() -> set[str]` reads
+ `Turn.context.platform_specific["task_execution_id"]` for every live `in_flight`
+ turn (the same key `_turn_sink_identity` uses, `:1715-1717`), and unions the
+ `coalesced_queue.execution_ids` list when present — a coalesced turn owns **all**
+ ids it is settling, not just the primary, or the sweep would fail the siblings out
+ from under a live flush.
+
+ Verified by review: source 1 is race-free — `_spawn_execution`
+ (`core/scheduled_tasks.py:2336-2343`) registers the task in the same synchronous
+ block as `claim()`, with no `await` between the DB write and the in-memory insert,
+ so `running` can never be visible without its owner.
+
+**A missing or failing provider must fail closed** (treat as owned → do not sweep).
+Sweeping a live run would double-settle and, worse, could look like a false failure
+notification to the user.
+
+**As built (deviation 5):** `_owned_agent_run_ids()` unions `_inflight_executions` with
+`SessionTurnManager.owned_agent_run_ids()`, and the latter reads **both**
+`in_flight` turns *and* the live `active_turn_sinks` — a sink can be registered for a
+run before/after its `Turn` is in `in_flight`, and reading only `in_flight` leaves that
+window sweepable (mutation M2 confirms: dropping the `active_turn_sinks` union kills
+`test_sweep_skips_running_run_owned_by_workbench_turn`). Fail-closed is implemented as
+`raise RuntimeError` from the provider lookup plus a `try/except → return` in
+`_sweep_stale_runs`, warning once rather than once per interval; the store method
+cannot distinguish "nothing is owned" from "I could not look", so the decision has to
+live in the caller.
+
+### 4.2 What the sweep does
+
+Runs from `ScheduledTaskService._watch_store` (the existing 2 s tick,
+`core/scheduled_tasks.py:1884`) at most every `sweep_interval` (default 60 s),
+only when `_owns_service_instance()` — same gate as every other drain. Exclusions,
+mirroring `recover_processing_runs`: `run_type='watch_runtime'`, and any row carrying
+`result_payload_json.deferred_terminal_status` (that is PR2/Activity territory).
+
+| Class | Precondition | Action |
+|---|---|---|
+| B3 orphaned `running` | `run_type='agent_run'`, not owned per §4.1, `started_at` older than `orphan_grace` (default 120 s) | `failed`, `interrupt_reason="orphaned"` |
+| B1 stranded `queued` | `created_at` older than `queued_ttl` (default 1800 s) **and** the drain's own skip reason is transport-unavailable | `failed`, `interrupt_reason="transport_unavailable"` |
+| B2 held `queued` | `metadata.workbench_queue_holds_run` **and** `updated_at` older than `hold_ttl` (default 3600 s) | `failed`, `interrupt_reason="queue_hold_expired"` |
+
+Ownership per §4.1 exempts a row from **all three** classes, not just B3 — see §5.5: a
+coalesced turn's owned siblings stay `queued` on purpose, so the queue TTLs have to
+respect a live owner too.
+
+Terminalizing the row is not the whole reclamation. A swept run's persisted Workbench
+queue segment (`messages` rows keyed `agent_run:<run_id>`) is nobody else's to reclaim
+once the row leaves `queued`, so the sweep also retires each expired run's own segment
+and republishes `queue.updated` — see §5.6.
+
+Notes:
+
+- B1's precondition should be **recorded, not re-derived**: have
+ `_drain_requests` stamp `metadata.last_skip_reason` (+ a coarse `last_skip_at`) on the
+ skip branches (`:2023`, `:2026`, capacity `:2017`), so the sweep never guesses and
+ the row itself explains why it sat. A row skipped only for capacity or a session lock
+ is **never** swept — it is making progress. (**Superseded in part by §5.3 P1**: the
+ recorded reason is necessary but not sufficient, because the drain stops at its
+ concurrency cap and stops refreshing the stamp. A live deliverability check is now
+ required alongside it.)
+
+ **Reviewer's blocking item 4 — this stamp must not self-trigger the drain.**
+ `_watch_store`'s gate is `maybe_reload()` → `SqliteInvalidationProbe.has_external_write()`
+ (`storage/db.py:82-108`), which bumps on *any* write to the DB file including our own.
+ A naive stamp on every skip iteration therefore becomes a permanent 2 s
+ write → reload → re-drain → write loop for as long as a transport is down, plus a
+ `runs.updated` event each cycle. Required design: write **only when the stored reason
+ changes** (transition-triggered, not tick-triggered), keep `last_skip_at` bucketed to
+ a coarse interval (e.g. the sweep interval) so a steady state produces no write at
+ all, and keep the stamp out of `run_update_event_transaction` so it emits no SSE.
+ The §5 "no hot loop" test guards this.
+- B2's TTL is deliberately longer than B1's and its precondition is `updated_at`, so a
+ session actively recovering its queue keeps the row alive.
+- The `agent_run`-only restriction on B3 keeps this plan disjoint from PR7 (which
+ changes when `scheduled`/`watch` rows settle). Widen it only after PR7 lands.
+
+**Correction (as-built) — what B3's "orphan" actually is.** This section read as if B3
+were mainly about surviving a restart. It is not: `ScheduledTaskService.__init__` calls
+`request_store.recover_processing()` → `recover_processing_runs()`, which **requeues
+every `running` row** (bar `watch_runtime` and deferred ones) at service construction.
+So a restart's in-flight runs are *retried*, not swept, and B3 is about owners lost
+**within a live process** — a turn that returned without settling, a `create_task` that
+never attached its done-callback, a drain task that died between claim and settle. This
+also has a hard consequence for the tests: a staged `running` fixture must be written
+*after* the service is constructed, or recovery flips it to `queued` first (this cost
+nine failing tests before it was diagnosed).
+
+**Correction (as-built) — the exclusions are defended twice.** Mutation testing showed
+the `watch_runtime` / deferred exclusions cannot be killed one at a time:
+`watch_runtime` is filtered out by the SELECT *and* excluded by B3's
+`run_type == "agent_run"` restriction, and a deferred row is skipped by the candidate
+loop *and* refused by `settle_run_terminal`'s own deferred guard. Removing both
+`watch_runtime` guards kills the test; removing only the deferred candidate check does
+not. Kept as-is — this is defence-in-depth, not dead code — and recorded in the test
+docstring so nobody later "simplifies" a guard on the strength of a green suite.
+
+### 4.3 Writers and side effects
+
+One new store method, guarded, alongside `recover_processing_runs`:
+
+```python
+def sweep_stale_runs(self, *, now, orphan_grace, queued_ttl, hold_ttl,
+ owned_run_ids: set[str]) -> list[SweptRun]
+```
+
+It selects candidates, then terminalizes each through the guarded path
+(`defer_run_terminal` + `settle_deferred_run`, or a single UPDATE scoped to
+`queued|running` honoring `_stronger_terminal_status`), writing `status`,
+`completed_at`, `error`, `metadata.interrupt_reason`, and emitting the deferred
+`runs.updated` event exactly like `recover_processing_runs:1588`. Because
+`list_pending_callbacks` only needs a terminal status + `completed_at`, **the
+user-facing callback ships for free** — no new delivery plumbing in this plan.
+
+Also release the in-memory wedge when a swept run holds one: if a swept row's lock key
+is still in `_inflight_sessions` while nothing owns the run, discard it. Without this,
+the DB is honest but the session stays undispatchable (the same wedge PR2 documents).
+
+**Correction (as-built, deviation 7):** rebuilding the lock key from a `SweptRun` is
+unsafe. A lock key is per-*conversation*, not per-run, so a swept run's identity can
+resolve to a key a *different*, live execution currently holds, and freeing it would
+let two turns run concurrently in one session. As built, `_spawn_execution` records
+`_session_lock_owners[lock_key] = request.id` next to the `_inflight_sessions` insert,
+and `_release_leaked_session_locks()` frees only keys whose recorded owner is no longer
+in `_inflight_executions`. That is provably one-directional: a lock held by a live task
+can never be freed. It also runs *unconditionally* after each sweep, not only when a
+row was swept, because the wedge and the stale row are independent failures and either
+can outlive the other.
+
+### 4.4 Config
+
+New keys under runtime config in `config/v2_config.py`, each with the defaults above
+and `0` meaning "disabled":
+`harness_run_orphan_grace_seconds`, `harness_run_queued_ttl_seconds`,
+`harness_run_hold_ttl_seconds`, `harness_run_sweep_interval_seconds`.
+No UI surface in this plan (defaults are the product decision); document in
+`docs/`. All user-visible error copy goes through `vibe/i18n/` — note
+`core/scheduled_tasks.py` imports no i18n today, which the approved plan already
+flags as a violation at this exact seam.
+
+As built, with `DEFAULT_HARNESS_RUN_*` constants exported from `config/v2_config.py`
+and read through `_runtime_seconds()`, which falls back to the default on a missing or
+non-integer value rather than letting a bad config crash the tick:
+
+| Key | Default | `0` means |
+| --- | --- | --- |
+| `harness_run_sweep_interval_seconds` | 60 | sweep disabled entirely |
+| `harness_run_orphan_grace_seconds` | 120 | never sweep orphaned `running` rows |
+| `harness_run_queued_ttl_seconds` | 1800 | never sweep transport-stranded `queued` rows |
+| `harness_run_hold_ttl_seconds` | 3600 | never expire a workbench queue hold |
+
+The i18n seam resolved as `SWEEP_I18N_KEYS` in `core/run_settlement.py`, next to
+`SETTLEMENT_I18N_KEYS`, mapping each `SWEEP_REASON_*` to
+`harness.run.interrupted.<reason>`. The reason strings are spelled as **literals**
+there rather than imported from `storage.background`: `core/run_settlement.py` is
+deliberately dependency-free so the dispatch layer can import it without pulling in
+SQLAlchemy, and importing `core` from `storage` would invert the layering. The drift
+risk that creates is closed by a test
+(`test_sweep_reason_i18n_map_covers_every_store_sweep_reason`) asserting the map's key
+set equals the store's constants.
+
+## 5. Test plan (hermetic; `tests/conftest.py:53-72` autouse isolation, no `uses_real_paths`)
+
+`tests/test_scheduled_tasks.py` (the natural home; `test_agent_run_stays_running_until_terminal_result:2054`
+is the template for the sink-driven cases):
+
+- `test_agent_run_with_blank_message_fails_instead_of_hanging` — the §1.1 reproducer.
+- `test_agent_run_settles_failed_when_sink_released_without_terminal_result` — Gap A
+ proper: stub `_handle_turn` to call `mark_turn_complete` only.
+- `test_agent_run_settles_when_dispatch_refuses_a_concurrent_turn` — **load-bearing
+ (reviewer's blocking item 6)**: drives `core/services/dispatch.py:86-95` with a sink
+ already registered for the session key and asserts the row terminalizes instead of
+ staying `running`. This is the case an earlier draft of this plan got wrong.
+- `test_agent_run_stays_running_until_terminal_result` — must still pass unchanged
+ (regression guard for goal 3), extended to assert `settled_by == "terminal_result"` is
+ actually stamped, so the test fails if the stamp is dropped.
+- `test_agent_run_cancel_racing_settlement_keeps_canceled` — §3.3.1's TOCTOU: flip
+ `cancel_requested` / settle the row `canceled` **between** `_execute_agent_run`
+ computing its outcome and the settlement write, and assert the row stays `canceled`.
+ A static already-canceled fixture would pass even with the unguarded writer, so it
+ must be a real interleaving.
+- `test_sweep_terminalizes_orphaned_running_run`
+- `test_sweep_skips_running_run_owned_by_inflight_execution`
+- `test_sweep_skips_running_run_owned_by_workbench_queue` — the §4.1 source-2 trap.
+- `test_sweep_fails_closed_when_ownership_provider_raises`
+- `test_sweep_terminalizes_queued_run_skipped_for_transport` /
+ `test_sweep_ignores_queued_run_skipped_only_for_capacity`
+- `test_sweep_releases_leaked_session_lock`
+- `test_sweep_respects_deferred_terminal_and_watch_runtime_exclusions`
+- `test_stranded_queued_run_does_not_trigger_repeated_metadata_writes` — **load-bearing
+ (reviewer's blocking item 6)**: across several `_watch_store` ticks with a transport
+ permanently unready, assert the row's `updated_at` / write count stays flat, guarding
+ §4.2's write-amplification loop.
+- `test_sweep_retries_queue_recovery_before_expiring_a_hold` — O4's resolution.
+
+`tests/test_inbox_events.py` — a swept row surfaces in `list_pending_callbacks`
+(proves the free-callback path) and the `runs.updated` event fires.
+
+`tests/test_message_dispatcher_scheduled.py` — `settled_by="terminal_result"` is
+stamped on the honest path.
+
+Plus the en/zh i18n key-parity test the approved plan already wants (there is none
+today), and `ruff check` on changed files before push. No UI change → no `npm run build`.
+
+### 5.1 What PR-A actually landed
+
+Delivered (all verified to FAIL with the fix reverted, so none is a tautology):
+
+- `tests/test_scheduled_tasks.py`
+ - `test_agent_run_settles_failed_when_sink_released_without_terminal_result`
+ - `test_agent_run_settles_when_dispatch_refuses_a_concurrent_turn` (load-bearing)
+ - `test_agent_run_cancel_racing_settlement_keeps_canceled` (load-bearing TOCTOU;
+ the cancel is applied *inside* the patched settlement call, so the interleaving
+ is real — with an unguarded `update_run_status` the row comes back `failed`)
+ - `test_agent_run_cancel_requested_settles_canceled_not_failed` — the in-transaction
+ `cancel_requested` → `canceled` mapping
+ - `test_agent_run_with_blank_message_fails_instead_of_hanging` — covers both the
+ store-level door and a legacy pre-guard row
+ - `test_agent_run_stopped_by_user_settles_canceled` — §3.5's status mapping, driven
+ through the *real* `settle_bound_turn_sink` (`_StopSinkSettler` borrows the actual
+ methods) so the stamp site and its guards are under test, not a hand-written string
+ - `test_stop_defers_to_a_terminal_result_that_already_landed` — the safe half of the
+ stop race; fails if the `done.is_set()` bail-out is removed
+ - `test_late_terminal_result_cannot_reopen_a_stopped_run` — the lossy half, pinned as
+ deliberate precedence; fails if `record_run_output`'s terminal guard is widened
+ - `test_drain_requests_agent_run_passes_agent_name` — **updated**: it used to assert
+ the run stays in `processing`, which encoded the zombie for the legacy file store.
+ It now asserts the run is completed with the settlement reason.
+- `tests/test_core_services_dispatch.py` — four `TurnDispatchOutcome` cases, including
+ that `settled_by is None` means *only* "non-streaming caller".
+- `tests/test_dispatcher_stream_chunk.py` — the `terminal_result` stamp is written by a
+ result emit, not by a notify emit, and not by a stale turn's late result.
+- `tests/test_i18n_backend_keys.py` (new file) — en/zh key parity, no blank strings,
+ and every `SETTLEMENT_I18N_KEYS` entry resolves in every supported language.
+
+Deferred to PR-B (they test the sweep, which PR-B introduces): every `test_sweep_*`
+case and `test_stranded_queued_run_does_not_trigger_repeated_metadata_writes`.
+
+Mutation evidence for the §3.5 additions (each mutation reverted after the run):
+
+| Mutation | Tests killed |
+| --- | --- |
+| `SETTLEMENT_TERMINAL_STATUS[stopped]` → `failed` | `..._stopped_by_user_settles_canceled`, `..._late_terminal_result_cannot_reopen...` |
+| drop the `done.is_set()` bail-out in `settle_bound_turn_sink` | `..._stop_defers_to_a_terminal_result_that_already_landed` |
+| widen `record_run_output`'s terminal guard to include `canceled` | `..._late_terminal_result_cannot_reopen_a_stopped_run` |
+
+Also verified green (no behavior regressions): `test_message_dispatcher_scheduled.py`,
+`test_controller_dispatch_loop.py`, `test_internal_server.py`, `test_inbox_events.py`,
+`test_cli_agent_run_schema.py`, `test_vault_request_callbacks.py`,
+`test_cli_task_command.py`, `test_session_activities.py`,
+`test_background_work_banner.py`, `test_harness_payload_enrichment.py`,
+`test_sqlite_state_migration.py`, `test_cli_pagination.py`, `test_ui_server_fastapi.py`.
+Pre-existing unrelated flake: `test_request_store_file_backend_reload_detects_queue_changes`
+(mtime granularity; fails on the untouched base too).
+
+### 5.2 What PR-B actually landed
+
+18 new cases in `tests/test_scheduled_tasks.py`, all hermetic, plus the store/i18n
+parity test. Every staged `running`/`queued` fixture is written **after** the service is
+constructed (see §4.2's recovery correction) and forced into the past with a raw
+`update(agent_runs)` helper rather than by moving a clock.
+
+| Test | What it pins |
+| --- | --- |
+| `test_sweep_terminalizes_orphaned_running_run` | B3 happy path: `failed` + `interrupt_reason="orphaned"` |
+| `test_sweep_respects_the_orphan_grace_period` | a young unowned row is left alone |
+| `test_sweep_skips_running_run_owned_by_inflight_execution` | ownership source 1 |
+| `test_sweep_skips_running_run_owned_by_workbench_turn` | ownership source 2, through the **real** `SessionTurnManager.register_turn_sink` with a `MessageContext` carrying `task_execution_id` + `coalesced_queue.execution_ids` |
+| `test_sweep_fails_closed_when_ownership_is_unknown[provider-missing\|provider-raises]` | §4.1's fail-closed rule, both ways it can break |
+| `test_sweep_terminalizes_queued_run_stranded_by_a_dead_transport` | B1 happy path |
+| `test_sweep_leaves_a_queued_run_whose_session_is_merely_busy` | drives the **real** `_drain_requests` and asserts the stamped reason is `session_busy`, so a busy session is never swept |
+| `test_sweep_ignores_queued_run_skipped_only_for_capacity` | an unstamped row is unsweepable |
+| `test_sweep_expires_a_workbench_queue_hold_only_after_its_ttl` | B2 both sides of the TTL |
+| `test_sweep_leaves_watch_runtime_and_deferred_rows_alone` | the exclusions (defended twice — see §4.2) |
+| `test_sweep_releases_a_leaked_session_lock` | the wedge release |
+| `test_execution_completion_does_not_steal_a_later_lock_owner` | deviation 7's safety direction |
+| `test_stranded_queued_run_does_not_trigger_repeated_metadata_writes` | reviewer item 4: `wrote == [True, False, False, False]` across four ticks and `updated_at` unchanged |
+| `test_swept_run_notifies_the_session_that_launched_it` | the free callback path |
+| `test_sweep_publishes_a_run_update_event` | `runs.updated` fires (subscription unsubscribed in `finally` — `subscribe_callback` is persistent, not one-shot) |
+| `test_sweep_is_rate_limited_to_the_configured_interval` | rewinds `_last_sweep_at`, no clock patching |
+| `test_sweep_is_disabled_by_a_zero_interval` | the kill switch |
+
+Mutation evidence — 12 of 13 targeted mutations killed, each reverted afterwards:
+
+| Mutation | Verdict |
+| --- | --- |
+| M1 sweep ignores `owned_run_ids` | KILLED (both ownership tests) |
+| M2 ownership omits live `active_turn_sinks` | KILLED |
+| M3 unknown ownership read as empty instead of raising | KILLED |
+| M4 sweep `queued` rows without a recorded skip reason | KILLED (2 tests) |
+| M5 drain does not stamp `session_busy` | KILLED |
+| M6 skip reason written every pass | KILLED |
+| M7 skip stamp bumps `updated_at` | KILLED |
+| M8 wedge release ignores live owners | KILLED |
+| M9 completion steals a later lock owner | KILLED |
+| M10 no sweep rate limit | KILLED |
+| M11 drop one `watch_runtime`/deferred guard | **SURVIVED** — both classes are guarded twice; M11c (remove the SELECT filter *and* the `agent_run` restriction) KILLS. Documented rather than forced. |
+| M12 no orphan grace | KILLED |
+| M14 transport class ignores `deliverable_run_ids` (review round 1) | KILLED |
+| M15 result overwrites a recorded `stopped` (review round 1) | KILLED |
+| M16 unknown deliverability does not disable the class (review round 1) | KILLED |
+
+Deviations from §4 as written, all deliberate: (1) `record_run_skip_reason` writes only
+on reason *change*, with no `last_skip_at` bucketing — a transition-only stamp already
+produces zero steady-state writes, so the bucket was unnecessary machinery; (2)
+`session_busy` is stamped too, so it can overwrite a stale `transport_unavailable` and
+un-sweep a row whose transport came back; (3) capacity skips are deliberately left
+unstamped — the drain `break`s without examining the rest of the queue, and an unstamped
+row is never sweepable, so silence is the safe encoding; (4) each row is terminalized
+through `settle_run_terminal` rather than `defer_run_terminal` + `settle_deferred_run`,
+inheriting exactly the same guards with one write instead of two; (5) ownership unions
+live sinks (§4.1); (6) B3 stays `agent_run`-only per O5; (7) the owner-map wedge release
+(§4.3); (8) no pre-expiry queue-recovery attempt (§7 O4).
+
+Validation: `uvx ruff check core/ storage/ config/ tests/` clean; 211 passed across
+`test_scheduled_tasks.py`, `test_i18n_backend_keys.py`, `test_inbox_events.py`,
+`test_core_services_dispatch.py`, `test_controller_dispatch_loop.py`,
+`test_message_dispatcher_scheduled.py`. One unrelated pre-existing flake,
+`test_request_store_file_backend_reload_detects_queue_changes` — reproduced from a clean
+`git archive` of base master `5921ad39` (2/3 failures) as well as of this HEAD (3/3), so
+it is not caused here. Cause: the legacy file store's `_path_signature` relies on
+directory `st_mtime_ns`, which the kernel's coarse timestamp clock can report identically
+for two writes in the same jiffy. Fix candidate for a separate PR: fold the sorted
+directory entry names into the signature instead of trusting mtime alone.
+
+### 5.3 Review round 1 (avibe-bot/avibe#1005) — two real defects
+
+Both findings were reproduced against the code before being fixed, and each fix is
+pinned by a test that fails when the fix is reverted.
+
+**P1 — stale transport evidence could fail a deliverable run (HFR-021, HFR-022).**
+§4.2 said the recorded skip reason is read off the row and never re-derived, so a
+transport that came back cannot erase the fact that a run missed it. That reasoning only
+holds for rows the drain still visits. The drain `break`s at
+`_MAX_CONCURRENT_EXECUTIONS` without examining the remaining queue (deviation 3's own
+premise), so a row below the cut keeps a `transport_unavailable` stamp indefinitely —
+including long after its platform reconnected — and would be failed for a transport
+outage that is over. The evidence now has two independent halves, both required: the
+recorded reason **and** a live `deliverable_run_ids` set, computed per sweep from
+`request_store.list_pending()` × `_transport_ready_for_request`. Any queued run whose
+transport answers ready is exempt, so a run waiting only for a free slot is never swept.
+If that live half cannot be computed the class disables itself for the tick
+(`queued_ttl_seconds = 0`) — the same fail-closed posture as unknown ownership, since an
+unprovable claim must not terminalize a run. The other two classes keep working.
+
+**P2 — a terminal result could overwrite an acknowledged stop's reason (HFR-023).**
+§3.5 claimed the stop/result precedence was settled by both writers being scoped to
+`queued|running`. It was not, one layer up: the stop stamps `settled_by="stopped"` in
+memory and releases the waiter immediately, while the row is written later when
+`_execute_agent_run` reads the stamp back. A terminal result arriving inside that window
+overwrote the reason unconditionally, so the guarded `canceled` settlement was skipped
+and the recorded outcome depended on which coroutine resumed first — while the user had
+already been told the run was stopped. `_stream_chunk` now refuses to overwrite a
+recorded `stopped`. Deliberately *not* fixed by widening the guarded writer to override
+an existing terminal status: that would break the one guarantee every settlement path
+relies on. Whether `canceled` reaches the row therefore stays ordinary
+first-writer-wins, and `settle_bound_turn_sink`'s docstring now says so instead of
+claiming a precedence the code does not provide.
+
+### 5.4 Review round 2 (avibe-bot/avibe#1005) — the TTL was measured from the wrong clock
+
+**P1 — `queued_ttl` aged from `created_at` instead of from the outage (HFR-024, HFR-025).**
+Round 1 fixed *which* rows the transport class may consider; this is *when* it may act.
+A run can sit in `queued` far longer than the TTL for reasons that are progress —
+capacity, a busy session. Aging from `created_at` meant that as soon as such a run's
+transport blinked, the row satisfied the TTL immediately and was failed on the next
+tick, consuming none of the configured 30-minute reconnect window. The TTL is a
+reconnect window, so it now ages from `metadata.last_skip_at`. That timestamp is already
+exactly right for the job: `record_run_skip_reason` is transition-triggered (deviation 1),
+so `last_skip_at` means "when this reason started", not "when we last looked".
+
+A reason with no parseable timestamp is treated as unrecognized evidence and never
+swept — `_older_than` already fails closed on an undateable value, and the reason and
+timestamp are written in one statement, so one without the other did not come from that
+writer. A `created_at` fallback was considered and rejected: it would silently
+reintroduce this exact bug for those rows, which is what HFR-025 now pins.
+
+| Mutation | Verdict |
+| --- | --- |
+| M17 fall back to `created_at` when `last_skip_at` is absent | KILLED (HFR-025) |
+| M18 age from `created_at` outright (the reported bug) | KILLED (HFR-024 + HFR-025) |
+
+### 5.5 Review round 3 (avibe-bot/avibe#1005) — ownership is not a `running`-only exemption
+
+**P1 — a live coalesced turn's own `queued` siblings were sweepable (HFR-026).**
+The ownership check sat inside the `running` branch, which reads as correct only if you
+assume an owned run is always `running`. It is not: a coalesced Workbench turn claims its
+secondary runs and deliberately leaves them `queued` with `workbench_queue_holds_run`
+while the primary settles them (`storage/background.py:384`, `:478`), and
+`owned_agent_run_ids()` reports **every** id such a turn is settling
+(`core/session_turns.py:635`). So a turn that outlived `hold_ttl` (default 1 h) had its
+own live siblings failed underneath it — a turn-duration timeout by the back door, which
+this design explicitly does not have. The same applies to any queued follow-up waiting
+behind a legitimate multi-hour turn.
+
+The fix hoists the check to the top of the candidate loop as a single `continue`: a live
+owner outranks every class, whatever the row's status. The branch-level
+`run_id not in owned_run_ids` was **removed** rather than left in place, so there is
+exactly one load-bearing guard — a duplicated check would produce another surviving
+mutation like the documented M11 and hide a future regression.
+
+| Mutation | Verdict |
+| --- | --- |
+| M19 restrict the hoisted guard back to `status == "running"` (the reported bug) | KILLED (HFR-026) |
+
+### 5.6 Review round 4 (avibe-bot/avibe#1005) — the gate lane had no settler, and a swept hold left its queue behind
+
+**P1 — an `avibe`-targeted run's turn could end without anyone settling the row (HFR-027).**
+§3.3 settles on the *drain* lane, which is correct for every backend that completes inside
+`_execute_agent_run`. An `avibe` target does not: it hands the prompt to
+`session_turn_gate.submit_scheduled` and returns `complete_on_return=False`
+(`core/scheduled_tasks.py:2891`, `:3137`) while the turn is still live, deliberately leaving
+the row to the *turn* lane. But `SessionTurnManager._run` called the thin `dispatch_turn`
+compat wrapper, which returns only `outcome.error` and discards `settled_by`. So a turn
+released without a terminal result — stopped, evicted, refused, or raising — left its run
+`running` until the B3 orphan grace expired, and a coalesced turn stranded its claimed
+siblings too. This is the same defect as §3.1–3.3, one lane over.
+
+Fix: `_run` now calls `dispatch_turn_with_outcome`, records `settled_by`
+(`SETTLED_BY_STOPPED` on `CancelledError`, `SETTLED_BY_NO_TERMINAL_RESULT` on an
+exception), and in its `finally` calls the new `_settle_turn_owned_agent_runs`, which
+settles **every** id in `_agent_run_ids_from_spec` — primary plus coalesced — through
+`ScheduledTaskService.settle_agent_runs_without_result`. That new entry point reuses the
+existing *guarded* first-writer-wins writer and the drain lane's i18n text, so the two
+lanes cannot fight: a real terminal result wins if it landed first, and this write
+degrades to a no-op. Ordering matters twice — after the failure emit (so the honest
+outbound terminal writes first, per §3.5) and before the queue flush (so the next turn
+never starts while a run this turn owned is still `running`). `settled_by is None` means
+no sink was bound at all, and a `SETTLED_BY_TERMINAL_RESULT` means a result did arrive;
+both return without guessing.
+
+**P2 — expiring a queue hold reclaimed the row but not its persisted queue (HFR-028).**
+A `workbench_queue_holds_run` run also owns a persisted `messages` row of type
+`QUEUED_TYPE` keyed `agent_run:<run_id>`. `recover_persisted_agent_run_queue` ignores
+references whose run is no longer `queued`, so once B2 terminalized the row nothing could
+ever reclaim that segment: the Session kept showing stale pending input until an
+unrelated send forced a flush. `SweptRun` already carried the `session_id` for exactly
+this and never used it. `_sweep_stale_runs` now calls `_retire_swept_queue_segments`,
+which per swept run calls the existing `_retire_stale_agent_run_queue_rows(session_id=…,
+execution_ids=[run_id])` and publishes one `queue.updated` per touched session.
+Retirement is scoped to each run's **own** native id, so it can never touch a live
+sibling's row, and a per-run failure is logged and skipped rather than aborting the sweep.
+
+| Mutation | Verdict |
+| --- | --- |
+| M20 drop the turn-lane settlement (keep the drain lane only — the reported P1) | KILLED (HFR-027) |
+| M21 skip `_retire_swept_queue_segments` after a sweep (the reported P2) | KILLED (HFR-028) |
+
+Collateral: seven pre-existing doubles across `tests/test_internal_server.py`,
+`tests/test_scheduled_tasks.py`, and `tests/test_controller_agent_status.py` patched
+`session_turns.dispatch_turn` and now patch `dispatch_turn_with_outcome`, returning a
+`TurnDispatchOutcome`. `internal_server.dispatch_turn` is intentionally untouched — that
+patch targets the legacy streaming `/internal/dispatch` endpoint's own symbol.
+
+### 5.7 Review round 5 (avibe-bot/avibe#1005) — a cancelled task is not always a user stop
+
+**P1 — a backend runtime refresh was reported as if the user pressed Stop (HFR-029).**
+§5.6 mapped every `CancelledError` in `_run` to `SETTLED_BY_STOPPED`, on the reasoning
+that only a stop path cancels a turn. True, but "stop path" quietly included
+`release_for_backend_refresh` (`core/session_turns.py:1487`), which cancels every
+in-flight turn of a backend whose cached process state is about to disappear — exactly
+what the rolling reconciliation after an `agents.*` save does (`core/backend_restart.py:102`,
+`modules/agents/codex/agent.py:396`). So a scheduled run interrupted by routine
+configuration work settled `canceled` with the user-stop text: the callback told the user
+they had stopped a run they never touched, and the failure accounting saw deliberate
+intent where there was an infrastructure fault.
+
+A cancelled task carries no cause, and only the canceller knows it. `Turn` gains
+`cancel_settled_by`, set **before** `task.cancel()`, and `_run` resolves the reason in its
+`finally` off the Turn it pops — the same lifetime trick the flush intents already use, so
+it retires with the turn instead of leaking in a parallel set. The `except
+asyncio.CancelledError` block no longer decides anything. A bare cancellation still reads
+as `stopped`, because `cancel` and `send_now` are the paths that legitimately have no more
+specific reason.
+
+New settlement `SETTLED_BY_BACKEND_REFRESH = "backend_refresh"` → `failed` (an
+infrastructure fault with no user intent, so it stays visible to a failure counter) with
+its own `harness.run.interrupted.backendRefresh` text in `en`/`zh`. It is deliberately
+**not** spelled `restarted`: that value is reserved by `harness-run-reliability.md` for
+the *service* restarting around a run, which `recover_processing_runs` retries, whereas
+this interrupts a live turn inside a healthy process and does not.
+
+| Mutation | Verdict |
+| --- | --- |
+| M22 collapse the cancellation attribution back to `SETTLED_BY_STOPPED` (the reported bug) | KILLED (HFR-029) |
+
+### 5.8 Review round 6 (avibe-bot/avibe#1005) — "the turn ended" is not "the Run ended"
+
+**P1 — a run another owner was still retrying got failed (HFR-030/031/032).**
+`_settle_activity_turn_after_delivery_failure` (`modules/agents/claude_agent.py:1898`)
+closes its origin turn with a silent terminal `result` carrying
+`MessageOutput(completes_turn=True, completes_run=False)`: the completion could not be
+persisted or delivered, so the **REQUEUED Activity keeps the run** and retries it. That
+emit still sets `mutates_turn_lifecycle`, so the release ran through
+`_signal_turn_complete` → `Controller.mark_turn_complete`, whose own default reason is the
+no-dispatch case (`no_terminal_result`). Both settlement lanes then read a settlement that
+means "no result is coming" and terminalized a **live, Activity-owned** run `failed`,
+firing its terminal callback before the retry ever ran.
+
+Two halves, because either alone leaves the hole open:
+
+1. The release site supplies the reason. `mark_turn_complete` takes
+ `settled_by=` (defaulting to `no_terminal_result` for genuine no-dispatch callers) and
+ `_signal_turn_complete` — every one of whose four call sites is a terminal-result emit —
+ defaults to `SETTLED_BY_TERMINAL_RESULT`, resolving per-emit through
+ `_turn_release_settlement(output_semantics)`: `settles_run` → `terminal_result`,
+ otherwise the new `SETTLED_BY_TURN_ONLY_RESULT`. A `TypeError` fallback keeps older
+ controllers/test doubles releasing the waiter.
+2. Both lanes flip from deny-list to allow-list. `core/scheduled_tasks.py` and
+ `core/session_turns.py` now require membership in `SETTLEMENTS_WITHOUT_RESULT` before
+ touching a row, instead of "anything but `terminal_result` is a zombie". So the next
+ "turn ended, run lives on" reason cannot repeat this failure by omission.
+
+`SETTLED_BY_TURN_ONLY_RESULT = "turn_only_result"` is deliberately absent from
+`SETTLEMENTS_WITHOUT_RESULT`, `SETTLEMENT_I18N_KEYS`, and `SETTLEMENT_TERMINAL_STATUS`: like
+`terminal_result` it never reaches a row, so it needs no terminal status and no
+user-visible text.
+
+| Mutation | Verdict |
+| --- | --- |
+| M23 drop the `settled_by` propagation in `_signal_turn_complete` (the reported bug) | KILLED (HFR-030) |
+| M24 turn lane back to `settled_by == terminal_result` deny-list | KILLED (HFR-031) |
+| M25 drain lane back to `settled_by == terminal_result` deny-list | KILLED (HFR-032) |
+
+### 5.9 Review round 7 (avibe-bot/avibe#1005) — a TTL must measure one outage, and the gate's parked rows have no owner
+
+Two P2 findings on `storage/background.py`, both real, both the same underlying mistake:
+the sweep was reasoning about *live* facts from *stale* evidence.
+
+**P2a — a recovered transport made the next outage's TTL retroactive (HFR-033).**
+`metadata.last_skip_reason = transport_unavailable` is stamped once, on transition
+(§4.3, deliberately, to avoid the write → invalidation-probe → reload → re-drain loop).
+Nothing retires it. So: stamped at `t0`; transport recovers; the drain that would
+re-evaluate the row never reaches it (already at `_MAX_CONCURRENT_EXECUTIONS`), so no
+rewrite happens; the sweep exempts the row because `deliverable_run_ids` now contains it.
+Transport drops again at `t2 > t0 + queued_ttl_seconds`, deliverability goes away, and the
+row is aged from `t0` — swept on the very first tick, with none of the reconnect window
+the TTL exists to grant.
+
+The fix retires the evidence at the only moment both halves are visible at once: the sweep
+already holds "the row remembers an outage" and "the row is deliverable right now".
+`_clear_transport_skip_evidence` pops `last_skip_reason`/`last_skip_at` for exactly those
+rows, re-reading each row under the write to skip anything that changed underneath, and
+writes **only** `metadata_json` — never `updated_at`, because the hold class's clock reads
+that column. It is transition-triggered in the same sense as the stamp: once the evidence
+is gone there is nothing left to clear, so a healthy queue costs zero repeat writes.
+
+**P2b — a hold parked behind a live turn was reported by nobody (HFR-034, HFR-035).**
+`submit_scheduled` returning `enqueued` requeues the row with
+`workbench_queue_holds_run = True`; the gate will flush it when the current turn ends.
+But `owned_agent_run_ids()` walks live turn *contexts* and yields only the ids those turns
+are executing themselves — a follower the gate parked is owned by no one. So a turn that
+legitimately runs longer than `harness_run_hold_ttl_seconds` (default 3600) had its own
+queued successor failed underneath it, and the user got an interruption notice for work
+that was still correctly waiting.
+
+The hold class therefore needs a third caller-supplied live fact, alongside
+`owned_run_ids` and `deliverable_run_ids`: `busy_session_ids`, at **session** granularity,
+because that is the granularity the gate occupies. `SessionTurnManager.busy_session_ids()`
+reads `in_flight`; `_busy_session_ids()` raises rather than returning a plausible empty
+set when the provider is missing, and `_sweep_stale_runs` catches that by failing closed —
+`hold_ttl_seconds = 0` disables the class entirely, per the §4.2 posture that an unknown
+live fact must never be read as "nothing is live".
+
+| Mutation | Verdict |
+| --- | --- |
+| M26 drop the recovered-evidence retirement (finding P2a) | KILLED (HFR-033) |
+| M27 drop the `busy_session_ids` exemption on the hold branch (finding P2b) | KILLED (HFR-034) |
+| M28 drop the caller's fail-closed `hold_ttl_seconds = 0` | KILLED (HFR-035) |
+
+### 5.10 Review round 8 (avibe-bot/avibe#1005) — a stop's empty result is not a success
+
+**P1 — every normally-stopped run was reported as `succeeded` (HFR-037).**
+§5.7 gave a user stop the `canceled` terminal it deserves, and recorded in
+`settle_bound_turn_sink` that if the backend's own terminal result landed first the row
+would keep `succeeded` — judged benign, because either reading is "true of a run the
+user stopped". That was wrong twice over.
+
+First, it is not a race. `SessionTurnManager.cancel` awaits `handle_stop`, every backend
+answers an acknowledged stop by emitting an empty silent `result`
+(`modules/agents/codex/agent.py:343`, `modules/agents/claude_agent.py:568`,
+`modules/agents/opencode/agent.py:554`), and only then does `cancel` call
+`turn.task.cancel()`. The emit therefore *always* precedes the stop settlement, so the
+branch dismissed as the unlucky one was the only branch that ever ran: `canceled` was
+reachable in production only when the backend could not emit at all (`stop_failed`, the
+stale-release path, an IM `/stop` with no live turn).
+
+Second, `succeeded` is not true. The row's terminal status is not "did the process
+stop cleanly" but "did this run produce its result", and the body here is empty
+precisely because nobody produced one. A user who ends a run and finds it filed as a
+success has been told the opposite of what happened, and a success counter agrees.
+
+The fix is the same principle as §5.8: the emit knows what it is, so it says so.
+`stop_output_for` (shared, one place) sends the stop with `completes_turn=True` — the
+turn really did end, the dot settles, the SSE waiter closes — and `completes_run=False`,
+so an empty body never becomes a terminal status. On its own that would read as
+`turn_only_result` (§5.8's Activity case, where another owner genuinely holds the row)
+and strand the run `running` until the sweep called it `orphaned`; so the output also
+carries an explicit `settled_by=stopped`, and `_turn_release_settlement` now lets a
+named settlement win over anything it would infer. Both lanes then reach the writer
+that already maps `stopped` to `canceled` with `interrupt_reason=stopped` — no new
+status logic, no duplicated i18n. `settle_bound_turn_sink` stays exactly as it was: a
+fallback for the stop that gets no emit at all.
+
+Built with `dataclasses.replace`, so a request carrying its own output policy (Activity
+lineage, an explicit `run_id`) keeps it and only the lifecycle is overridden.
+
+The defect was copied verbatim into three backends, which is what HFR-040 is for: it
+asserts on the terminal emit inside *every* `handle_stop`, so a fourth backend reaching
+for `terminal_output_for` in its stop path fails a test instead of silently reporting
+stopped runs as successes. (`notify` emits on the refusal paths are excluded — they
+settle nothing and return `False`.)
+
+| Mutation | Verdict |
+| --- | --- |
+| M29 stop output back to `completes_run=True` (the reported bug) | KILLED (HFR-036, HFR-037) |
+| M30 drop the explicit-settlement override in `_turn_release_settlement` | KILLED (HFR-036, HFR-037) |
+| M31 revert the stop emit to `terminal_output_for` — codex | KILLED (HFR-039, HFR-040) |
+| M31 revert the stop emit to `terminal_output_for` — claude | KILLED (HFR-040) |
+| M31 revert the stop emit to `terminal_output_for` — opencode | KILLED (HFR-040) |
+
+## 6. Staging
+
+- **PR-A (Gap A)** — §3.1–3.4. Small, no new config, no sweep. Independently
+ shippable and fixes the only reproducible-on-demand zombie.
+- **PR-B (Gap B)** — §4. Depends on PR-A only for shared constants/i18n keys.
+ Must land after, or be explicitly rebased on, PR2 if PR2 lands first (both touch
+ `_inflight_sessions` release semantics; PR2's teardown cancel makes B3 rarer but
+ not unreachable).
+
+## 7. Design points — resolved at review
+
+- **O1 — canceled vs failed.** Resolved: settle through `defer_run_terminal` +
+ `settle_deferred_run` inside `_execute_agent_run` (§3.3.1); confirmed
+ `update_run_status` has no status predicate and would clobber `canceled`.
+- **O2 — `transport_unavailable` terminal.** Resolved as drafted: `failed` +
+ `interrupt_reason`, per the closed status vocabulary. A `vibe runs retry` helper is a
+ separate feature, not a blocker.
+- **O3 — orphan grace.** Resolved: no race exists (`_spawn_execution` registers the
+ owner synchronously with the claim), so 120 s is headroom, not a mitigation.
+- **O4 — held-row TTL.** Resolved: before declaring `queue_hold_expired`, the sweep
+ makes one `recover_persisted_agent_run_queue(session_id)` attempt (the same call the
+ post-completion hook already makes, `core/scheduled_tasks.py:2464-2478`); only if the
+ row is still held does it terminalize.
+
+ **Not implemented in PR-B (deviation 8, deliberate).** The recovery attempt would have
+ to happen between candidate selection and the terminal write, i.e. inside the store
+ method — and the store cannot call the controller without inverting the layering. The
+ hold class is safe without it: its TTL is 3600 s and its clock is `updated_at`, so any
+ successful recovery (which touches the row) resets it, and the post-completion hook
+ already retries recovery on the normal path. Doing it properly means splitting the
+ sweep into select → caller-side recovery → re-check → settle; worth it only if a real
+ `queue_hold_expired` is ever observed on a session that would have recovered.
+ `test_sweep_retries_queue_recovery_before_expiring_a_hold` is therefore not in the
+ delivered suite; `test_sweep_expires_a_workbench_queue_hold_only_after_its_ttl` covers
+ the TTL itself.
+- **O5 — `agent_run`-only scope.** Resolved: keep the scope for now; `_inflight_executions`
+ already covers `scheduled`/`task_run` uniformly, so widening B3 is a small delta if
+ PR2/PR7 timing slips.
+
+Reviewer's authority question, recorded: PR-A is **not** folded into the approved plan's
+PR2. PR2 handles externally cancelled mid-flight executions; Gap A handles executions
+that return *normally* having never dispatched. Different triggers, same DB symptom —
+and after §3.3.1 both use the same guarded writer, so there is one settlement authority
+in the storage layer even with two call sites.
+
+Deliberately deferred (pre-existing, not caused here): a targeted test for
+`settle_bound_turn_sink` racing a real terminal emit (`core/session_turns.py:1836`).
diff --git a/docs/plans/v2/05_config_model.md b/docs/plans/v2/05_config_model.md
index 2f7425016..96be70ebb 100644
--- a/docs/plans/v2/05_config_model.md
+++ b/docs/plans/v2/05_config_model.md
@@ -39,6 +39,26 @@ V2 stores all user data under `~/.vibe_remote/` as JSON files. The model preserv
- `default_cwd`: default working directory
- `log_level`: `"DEBUG" | "INFO" | "WARNING" | "ERROR"`
- `require_mention`: bool (channel messages require @mention; stored under `slack`)
+- `harness_run_sweep_interval_seconds`: int, default `60` — how often the Harness
+ staleness sweep looks for runs nothing is executing any more. `0` disables the sweep
+ entirely (and with it all three classes below).
+- `harness_run_orphan_grace_seconds`: int, default `120` — how long a `running` agent run
+ with no live owner is tolerated before it is settled `failed` with
+ `interrupt_reason="orphaned"`. `0` disables this class.
+- `harness_run_queued_ttl_seconds`: int, default `1800` — how long a run may sit `queued`
+ because its chat platform never reconnected before it is settled `failed` with
+ `interrupt_reason="transport_unavailable"`. Only rows the dispatcher actually recorded
+ as transport-blocked are eligible; a run merely waiting on a busy session or on
+ capacity is never affected. `0` disables this class.
+- `harness_run_hold_ttl_seconds`: int, default `3600` — how long an untouched workbench
+ queue hold is kept before its run is settled `failed` with
+ `interrupt_reason="queue_hold_expired"`. Any queue activity resets the clock. `0`
+ disables this class.
+
+All four are read per sweep, so a config save takes effect on the next tick without a
+restart. A missing or non-numeric value falls back to the default rather than failing
+the tick. Design rationale and the evidence each class requires:
+`docs/plans/agent-run-zombie-settlement.md` §4.
### agents
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 78d4bcb9e..553284cbe 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -6,7 +6,7 @@ from typing import Callable, Optional
from core.agent_auth_service import classify_auth_error
from core.backend_failure import backend_failure_notification_output, emit_backend_failure
-from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
+from core.message_output import MessageOutput, stop_output_for, terminal_output_for, terminal_turn_output
from core.reply_enhancer import strip_silent_blocks
from core.session_activities import SessionActivity, activity_completion_output
from modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error
@@ -559,13 +559,15 @@ class ClaudeAgent(BaseAgent):
# idle + releases the SSE waiter through the outbound chokepoint
# WITHOUT a bubble. Emit only after cleanup so the next turn cannot
# acquire the gate and reuse a client that this stop is still
- # disconnecting.
+ # disconnecting. ``stop_output_for`` (not the terminal-turn default) keeps
+ # this empty body out of the run's terminal state so the stop settles it
+ # ``canceled`` instead of ``succeeded`` — see its docstring.
await self.controller.emit_agent_message(
request.context,
"result",
"",
level="silent",
- output=terminal_output_for(request),
+ output=stop_output_for(request),
)
except Exception as err:
logger.error("Failed to emit Claude stop result for session %s: %s", composite_key, err, exc_info=True)
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 8c460c224..445ecfda4 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -18,7 +18,7 @@ from config.v2_config import (
from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
from core.caller_context import caller_env_for_platform_payload
-from core.message_output import terminal_output_for
+from core.message_output import stop_output_for, terminal_output_for
from core.services.session_fork import fork_source_state, pending_native_fork
from core.system_prompt_injection import (
build_forked_session_correction_prompt,
@@ -335,12 +335,15 @@ class CodexAgent(BaseAgent):
# bubble. The user already knows they stopped it (avibe shows the dot go
# idle; IM shows the ack reaction removed above). ``level="silent"`` is
# the explicit visibility grade rather than faking it via empty text.
+ # ``stop_output_for`` (not the terminal-turn default) keeps this empty body
+ # out of the run's terminal state so the stop settles it ``canceled``
+ # instead of ``succeeded`` — see its docstring.
await self.controller.emit_agent_message(
request.context,
"result",
"",
level="silent",
- output=terminal_output_for(request),
+ output=stop_output_for(request),
)
logger.info("Codex turn %s interrupted via /stop", turn_id)
return True
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 5fb7dd5f4..fb840ddc0 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -16,7 +16,7 @@ from typing import Dict, Optional
from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
-from core.message_output import terminal_output_for
+from core.message_output import stop_output_for, terminal_output_for
from core.resource_governance import governor_from_controller
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
from modules.agents.base import AgentRequest, BaseAgent
@@ -546,12 +546,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# user-facing message: a single SILENT result settles the dot to idle +
# releases the SSE waiter through the outbound chokepoint without a bubble
# (``level="silent"`` makes that explicit rather than faking it via empty text).
+ # ``stop_output_for`` (not the terminal-turn default) keeps this empty body out
+ # of the run's terminal state so the stop settles it ``canceled`` instead of
+ # ``succeeded`` — see its docstring.
await self.controller.emit_agent_message(
request.context,
"result",
"",
level="silent",
- output=terminal_output_for(request),
+ output=stop_output_for(request),
)
logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")
return True
diff --git a/storage/background.py b/storage/background.py
index c471c11b7..9ad8b912b 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -3,7 +3,8 @@ from __future__ import annotations
import json
import logging
from contextlib import contextmanager
-from datetime import datetime, timezone
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Optional
from zoneinfo import ZoneInfo
@@ -101,6 +102,70 @@ _TERMINAL_STATUS_PRIORITY = {
"canceled": 1,
"failed": 2,
}
+# The closed set of terminal run statuses. Shared so guarded writers and reconcile
+# paths cannot drift apart (this file previously spelled the set inline).
+TERMINAL_RUN_STATUSES = frozenset(_TERMINAL_STATUS_PRIORITY)
+
+
+def _parse_iso_instant(value: Any) -> Optional[datetime]:
+ """Parse a stored ISO timestamp, or ``None`` if it is absent/unusable.
+
+ Callers deciding whether a row is stale must treat ``None`` as "not old enough".
+ A row we cannot date is a row we must not sweep.
+ """
+
+ text = str(value or "").strip()
+ if not text:
+ return None
+ try:
+ instant = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if instant.tzinfo is None:
+ instant = instant.replace(tzinfo=timezone.utc)
+ return instant
+
+
+@dataclass(frozen=True)
+class SweptRun:
+ """One run the staleness sweep terminalized, plus who it belonged to.
+
+ The identity fields are the sweep's report, not its repair: an honest DB row is
+ not enough if the session stays undispatchable, but the in-memory wedge is
+ released from the recorded lock owner (``ScheduledTaskService.
+ _release_leaked_session_locks``) rather than reconstructed from these fields —
+ a lock key is per-conversation, so freeing it from a swept run's identity could
+ free one a different live execution still holds. These fields exist so the
+ caller can log, notify, and test what was swept.
+ """
+
+ run_id: str
+ status: str
+ interrupt_reason: str
+ run_type: Optional[str] = None
+ task_id: Optional[str] = None
+ session_id: Optional[str] = None
+ session_key: Optional[str] = None
+
+
+#: ``metadata.last_skip_reason`` values written by the drain when it defers a queued
+#: run. The sweep requires this recorded evidence rather than re-deriving readiness, so
+#: a run deferred for a reason that still represents progress is never swept.
+#:
+#: Only ``transport_unavailable`` makes a row sweepable. ``session_busy`` is recorded
+#: precisely so it can OVERWRITE a stale ``transport_unavailable``: without it, a run
+#: that was once blocked on a dead transport and is now merely queued behind its own
+#: session's active turn would still look sweepable. Capacity skips are deliberately
+#: not recorded — the drain ``break``s at capacity without examining the remaining
+#: rows, and an unstamped row is never swept, which is the safe direction.
+SKIP_REASON_TRANSPORT_UNAVAILABLE = "transport_unavailable"
+SKIP_REASON_SESSION_BUSY = "session_busy"
+
+#: ``metadata.interrupt_reason`` values the sweep writes. Kept beside the sweep so
+#: the query and the reason cannot drift.
+SWEEP_REASON_ORPHANED = "orphaned"
+SWEEP_REASON_TRANSPORT_UNAVAILABLE = "transport_unavailable"
+SWEEP_REASON_QUEUE_HOLD_EXPIRED = "queue_hold_expired"
def normalize_run_status(status: Any) -> str:
@@ -1389,6 +1454,85 @@ class SQLiteBackgroundTaskStore:
"run": run_payload,
}
+ def settle_run_terminal(
+ self,
+ run_id: str,
+ *,
+ terminal_status: str,
+ error: Optional[str] = None,
+ result_text: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ updated_at: Optional[str] = None,
+ ) -> Optional[str]:
+ """Terminalize a non-terminal run in one guarded write.
+
+ This is the settlement writer for a turn that ended WITHOUT the backend
+ emitting a terminal result (see ``docs/plans/agent-run-zombie-settlement.md``).
+ Unlike ``update_run_status`` — whose UPDATE has no status predicate and would
+ clobber a row another actor already settled — the UPDATE here is scoped to
+ ``queued|running``, so a concurrent ``vibe runs cancel`` that lands first wins
+ and this call becomes a no-op.
+
+ ``cancel_requested`` is read inside the same transaction: a run the user asked
+ to cancel settles ``canceled``, never ``failed``, without needing a second
+ write. Rows carrying a deferred terminal intent are left alone — the Activity
+ lifecycle owns those.
+
+ Returns the terminal status actually written, or ``None`` when nothing was
+ written (already terminal, deferred, or missing).
+ """
+
+ now = updated_at or _utc_now_iso()
+ row_to_publish = None
+ written_status: Optional[str] = None
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row or normalize_run_status(row["status"]) in TERMINAL_RUN_STATUSES:
+ return None
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):
+ # The Activity lifecycle already owns this row's terminal state.
+ return None
+ status = normalize_run_status(terminal_status)
+ if row["cancel_requested"] and status == "failed":
+ status = "canceled"
+ values: dict[str, Any] = {
+ "status": status,
+ "completed_at": now,
+ "updated_at": now,
+ }
+ if error is not None:
+ values["error"] = str(error)
+ if result_text is not None:
+ values["result_text"] = str(result_text)
+ if metadata:
+ merged = _json_loads(row["metadata_json"], {})
+ if not isinstance(merged, dict):
+ merged = {}
+ merged.update(metadata)
+ values["metadata_json"] = _json_dumps(merged)
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ .values(**values)
+ )
+ if transition.rowcount:
+ written_status = status
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
+ return written_status
+
def defer_run_terminal(
self,
run_id: str,
@@ -1406,11 +1550,7 @@ class SQLiteBackgroundTaskStore:
row = conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().first()
- if not row or normalize_run_status(row["status"]) in {
- "succeeded",
- "failed",
- "canceled",
- }:
+ if not row or normalize_run_status(row["status"]) in TERMINAL_RUN_STATUSES:
return False
result_payload = _json_loads(row["result_payload_json"], {})
if not isinstance(result_payload, dict):
@@ -1587,6 +1727,287 @@ class SQLiteBackgroundTaskStore:
_refresh_recovered_coalesced_workbench_runs_in_connection(conn, now=now)
_defer_run_ids_updated_from_connection(conn, recovered_ids)
+ def record_run_skip_reason(self, run_id: str, *, reason: str, at: Optional[str] = None) -> bool:
+ """Record WHY the drain deferred a queued run — only when it changes.
+
+ The sweep must not guess why a row sat in ``queued``, so the drain records it.
+ The subtlety is that this write cannot be tick-triggered.
+ ``ScheduledTaskService._watch_store`` decides whether to drain from
+ ``maybe_reload()`` → ``SqliteInvalidationProbe.has_external_write()``, which
+ bumps on *any* write to the DB file — including ours. Stamping on every drain
+ pass would therefore self-sustain a write → reload → re-drain → write loop for
+ as long as a transport stayed down.
+
+ So the write is transition-triggered: if the stored reason already matches,
+ nothing is written and the probe stays quiet. A permanently unavailable
+ transport costs exactly one write, ever. ``last_skip_at`` consequently means
+ "when this reason started", which is more useful than a refreshed timestamp.
+
+ Deliberately NOT wrapped in ``run_update_event_transaction``: this is
+ diagnostic metadata, not a state change worth an SSE frame. ``updated_at`` is
+ left alone too — bumping it would make a stranded row look freshly touched and
+ would defeat the hold TTL, which reads exactly that column.
+
+ Returns ``True`` when a write actually happened.
+ """
+
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.metadata_json)
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
+ if not row or normalize_run_status(row["status"]) != "queued":
+ return False
+ metadata = _json_loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ metadata = {}
+ if metadata.get("last_skip_reason") == reason:
+ return False
+ metadata["last_skip_reason"] = reason
+ metadata["last_skip_at"] = at or _utc_now_iso()
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(metadata_json=_json_dumps(metadata))
+ )
+ return True
+
+ def _clear_transport_skip_evidence(self, run_ids: set[str]) -> int:
+ """Forget a ``transport_unavailable`` stamp whose outage has demonstrably ended.
+
+ Counterpart to :meth:`record_run_skip_reason`, with the same two properties
+ that keep it from feeding the drain loop: it is TRANSITION-triggered (after the
+ clear there is no reason left to match, so a still-deliverable row costs zero
+ writes on every later sweep), and it leaves ``updated_at`` alone so a queue hold
+ keeps aging from its own clock.
+
+ Scoped to the transport reason on purpose: another writer's reason is not ours
+ to erase, and a row re-stamped between the select and here is left as it is —
+ it will be reconsidered, with a fresh ``last_skip_at``, next sweep.
+ """
+
+ cleared = 0
+ with self.engine.begin() as conn:
+ for run_id in sorted(run_ids):
+ row = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.metadata_json)
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ ).mappings().first()
+ if not row or normalize_run_status(row["status"]) != "queued":
+ continue
+ metadata = _json_loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ continue
+ if metadata.get("last_skip_reason") != SKIP_REASON_TRANSPORT_UNAVAILABLE:
+ continue
+ metadata.pop("last_skip_reason", None)
+ metadata.pop("last_skip_at", None)
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(metadata_json=_json_dumps(metadata))
+ )
+ cleared += 1
+ if cleared:
+ logger.debug("Cleared recovered transport skip evidence on %s harness run(s)", cleared)
+ return cleared
+
+ def sweep_stale_runs(
+ self,
+ *,
+ owned_run_ids: set[str],
+ error_texts: dict[str, str],
+ deliverable_run_ids: Optional[set[str]] = None,
+ busy_session_ids: Optional[set[str]] = None,
+ now: Optional[str] = None,
+ orphan_grace_seconds: int = 0,
+ queued_ttl_seconds: int = 0,
+ hold_ttl_seconds: int = 0,
+ ) -> list[SweptRun]:
+ """Terminalize runs that provably have nothing left to settle them.
+
+ Three evidence-based classes (``docs/plans/agent-run-zombie-settlement.md``
+ §4.2). Each is disabled by passing ``0`` for its window:
+
+ - ``orphaned``: a ``running`` agent run with no live owner, older than
+ ``orphan_grace_seconds``. The grace period is what keeps a run that is
+ legitimately starting up from being swept.
+ - ``transport_unavailable``: a ``queued`` run whose recorded skip reason says
+ its transport is down, whose ``last_skip_at`` (when that reason started, not
+ when the run was enqueued) is older than ``queued_ttl_seconds``, AND which the
+ caller still cannot deliver. The reason is read off the row, never
+ re-derived, so a run deferred for capacity or a session lock — both of which
+ are progress — is never swept.
+ - ``queue_hold_expired``: a ``queued`` run holding a workbench queue slot that
+ has not been touched in ``hold_ttl_seconds``, in a session with no live turn.
+
+ ``owned_run_ids`` exempts a row from **every** class, not just ``orphaned``. A
+ coalesced workbench turn claims its secondary runs and deliberately leaves them
+ ``queued`` while the primary settles them, so a live owner has to outrank the
+ queue TTLs too — otherwise a turn that outlives ``hold_ttl_seconds`` would have
+ its own siblings failed underneath it, reintroducing the turn-duration timeout
+ this design does not have. It must be the union of every ownership source; the
+ caller is responsible for failing closed (passing "everything is owned", or not calling
+ at all) when it cannot enumerate owners. This method cannot tell an empty set
+ meaning "nothing is running" from one meaning "I could not look".
+
+ ``deliverable_run_ids`` is the same contract for the transport class, and it is
+ why the recorded reason alone is not enough. The drain stops at its concurrency
+ cap, so rows below the cut are never re-examined and keep an old
+ ``transport_unavailable`` stamp long after their platform reconnected. Without a
+ live second opinion the sweep would fail a run that is merely waiting for a free
+ slot. Every id listed here is exempt. A listed row also has its stale
+ ``transport_unavailable`` evidence CLEARED, so a later outage is aged from its
+ own start: capacity keeps the drain from re-stamping a row below its cut, so
+ without the clear a recovered-then-failed-again transport would be read as one
+ continuous outage and skip the whole configured reconnect window (Codex P2).
+
+ ``busy_session_ids`` is the same contract again, for the hold class: a run the
+ gate parked behind a live turn is NOT reported by ``owned_agent_run_ids`` (the
+ live turn only owns the ids of the run it is itself executing), so a legitimate
+ Workbench turn outliving ``hold_ttl_seconds`` would have its own queued follower
+ failed even though the gate would flush it on completion (Codex P2). The set is
+ session ids, not run ids, because that is the granularity the gate occupies.
+ ``None`` means "no exemptions", so a caller that cannot enumerate live turns
+ must fail closed by disabling the class (``hold_ttl_seconds=0``), exactly as it
+ does for deliverability.
+
+ Candidate selection is read-only; each row is then terminalized through
+ :meth:`settle_run_terminal`, so every write inherits the same guards — scoped
+ to ``queued|running``, ``cancel_requested`` honored, deferred/Activity-owned
+ rows left alone, ``metadata_json`` merged rather than replaced. A row someone
+ else settles between the select and the write is simply skipped.
+ """
+
+ now_iso = now or _utc_now_iso()
+ now_dt = _parse_iso_instant(now_iso) or datetime.now(timezone.utc)
+
+ def _older_than(value: Any, seconds: int) -> bool:
+ if seconds <= 0:
+ return False
+ instant = _parse_iso_instant(value)
+ if instant is None:
+ # Undateable row: never sweep it.
+ return False
+ return instant <= now_dt - timedelta(seconds=seconds)
+
+ with self.engine.begin() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_runs)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ .where(agent_runs.c.run_type != "watch_runtime")
+ ).mappings()
+ )
+
+ candidates: list[tuple[dict[str, Any], str]] = []
+ recovered_ids: set[str] = set()
+ for row in rows:
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):
+ # The Activity lifecycle owns this row's terminal state.
+ continue
+ metadata = _json_loads(row["metadata_json"], {})
+ metadata = metadata if isinstance(metadata, dict) else {}
+ status = normalize_run_status(row["status"])
+ run_id = str(row["id"])
+ if run_id in owned_run_ids:
+ # A live owner outranks every TTL, whatever the row's status. This is
+ # NOT only about ``running`` rows: a coalesced workbench turn claims its
+ # secondary runs and deliberately leaves them ``queued`` with
+ # ``workbench_queue_holds_run`` while the primary settles them, and
+ # ``owned_agent_run_ids`` reports all of them as owned. Aging those out
+ # would fail live siblings mid-turn — a turn-duration timeout by the back
+ # door, which this design explicitly does not have.
+ continue
+ reason: Optional[str] = None
+ if status == "running":
+ # Restricted to ``agent_run`` on purpose: when ``scheduled``/``watch``
+ # rows settle is owned by a separate plan. Widen only alongside it.
+ if str(row["run_type"] or "") == "agent_run" and _older_than(
+ row["started_at"] or row["created_at"], orphan_grace_seconds
+ ):
+ reason = SWEEP_REASON_ORPHANED
+ elif status == "queued":
+ if (
+ metadata.get("last_skip_reason") == SKIP_REASON_TRANSPORT_UNAVAILABLE
+ and run_id in (deliverable_run_ids or set())
+ ):
+ # The outage this row remembers is OVER. Retire the evidence now,
+ # while we can still see both halves of it: the drain breaks at its
+ # concurrency cap, so a row below the cut is never re-stamped, and a
+ # stale ``last_skip_at`` would make the NEXT outage look like a
+ # continuation of this one and skip its whole TTL (Codex P2).
+ recovered_ids.add(run_id)
+ # Hold before transport: it is the more specific piece of evidence, and
+ # its TTL is deliberately the longest so an actively recovering queue
+ # survives.
+ if (
+ metadata.get("workbench_queue_holds_run")
+ # A live turn in this row's session is why it is parked. The gate
+ # will flush it when that turn ends, and the turn does NOT report
+ # this run as owned — it owns only the ids it is executing itself.
+ and str(row["session_id"] or "") not in (busy_session_ids or set())
+ and _older_than(row["updated_at"], hold_ttl_seconds)
+ ):
+ reason = SWEEP_REASON_QUEUE_HOLD_EXPIRED
+ elif (
+ metadata.get("last_skip_reason") == SKIP_REASON_TRANSPORT_UNAVAILABLE
+ # Two independent facts, both required: the drain recorded that this
+ # row's platform was down, AND the caller still cannot deliver it.
+ # The stamp alone goes stale below the drain's concurrency cap.
+ and run_id not in (deliverable_run_ids or set())
+ # Age from when the transport problem STARTED, not from when the
+ # run was enqueued. ``record_run_skip_reason`` is
+ # transition-triggered, so ``last_skip_at`` is exactly that instant.
+ # Using ``created_at`` would make a run that had already been
+ # queued past the TTL for a healthy reason (capacity, a busy
+ # session) sweepable the moment its transport blinked, skipping the
+ # whole configured reconnect window. Absent or unparseable => never
+ # swept: the reason and its timestamp are written together, so a
+ # reason without one is evidence this writer did not produce.
+ and _older_than(metadata.get("last_skip_at"), queued_ttl_seconds)
+ ):
+ reason = SWEEP_REASON_TRANSPORT_UNAVAILABLE
+ if reason is not None:
+ candidates.append((dict(row), reason))
+
+ if recovered_ids:
+ self._clear_transport_skip_evidence(recovered_ids)
+
+ swept: list[SweptRun] = []
+ for row, reason in candidates:
+ run_id = str(row["id"])
+ written = self.settle_run_terminal(
+ run_id,
+ terminal_status="failed",
+ error=error_texts.get(reason),
+ metadata={"interrupt_reason": reason},
+ updated_at=now_iso,
+ )
+ if written is None:
+ # Settled by someone else in the meantime — nothing to report.
+ continue
+ logger.warning("Harness run %s swept as %s (%s)", run_id, written, reason)
+ swept.append(
+ SweptRun(
+ run_id=run_id,
+ status=written,
+ interrupt_reason=reason,
+ run_type=str(row["run_type"] or "") or None,
+ task_id=str(row["definition_id"] or "") or None,
+ session_id=str(row["session_id"] or "") or None,
+ session_key=str(row["legacy_session_key"] or "") or None,
+ )
+ )
+ return swept
+
def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:
watches = payload.get("watches", {}) if isinstance(payload, dict) else {}
with self.engine.begin() as conn:
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index d7740af8e..a01f4c008 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -6,6 +6,9 @@ capability:
- tests/test_agent_backend_alive.py
- tests/test_agent_service.py
- tests/test_scheduled_tasks.py
+ - tests/test_dispatcher_stream_chunk.py
+ - tests/test_message_dispatcher_result_fallback.py
+ - tests/test_agent_stop_settlement.py
shared_harness: []
status_legend:
covered: deterministic scenario or contract coverage exists
@@ -67,7 +70,234 @@ scenarios:
layer: contract
backend: shared
test: tests/test_scheduled_tasks.py::test_failed_run_records_error_and_enqueues_one_terminal_callback
+ - id: HFR-009
+ name: turn that ends without a terminal result settles its Run
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_agent_run_settles_failed_when_sink_released_without_terminal_result
+ - id: HFR-010
+ name: refused concurrent turn settles its Run instead of stranding it
+ status: covered
+ kind: failure
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_agent_run_settles_when_dispatch_refuses_a_concurrent_turn
+ - id: HFR-011
+ name: cancel landing mid-settlement stays canceled
+ status: covered
+ kind: idempotency
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_agent_run_cancel_racing_settlement_keeps_canceled
+ - id: HFR-012
+ name: user-stopped Run settles canceled, not failed
+ status: covered
+ kind: cancellation
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_agent_run_stopped_by_user_settles_canceled
+ - id: HFR-013
+ name: running Run whose owner vanished is swept terminal
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_terminalizes_orphaned_running_run
+ - id: HFR-014
+ name: Run owned by a live out-of-band turn is never swept
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_skips_running_run_owned_by_workbench_turn
+ - id: HFR-015
+ name: unknown ownership fails closed instead of sweeping
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_fails_closed_when_ownership_is_unknown
+ - id: HFR-016
+ name: queued Run stranded by a dead transport ages out with an explanation
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_terminalizes_queued_run_stranded_by_a_dead_transport
+ - id: HFR-017
+ name: queued Run merely waiting on a busy Session is never swept
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_leaves_a_queued_run_whose_session_is_merely_busy
+ - id: HFR-018
+ name: leaked Session lock is released without freeing a live one
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_releases_a_leaked_session_lock
+ - id: HFR-019
+ name: finishing predecessor cannot steal a successor's Session lock owner
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_execution_completion_does_not_steal_a_later_lock_owner
+ - id: HFR-020
+ name: staleness evidence stamp does not self-feed the drain loop
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_stranded_queued_run_does_not_trigger_repeated_metadata_writes
+ - id: HFR-021
+ name: stale transport evidence never fails a run that is deliverable now
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_spares_a_stale_transport_stamp_once_the_platform_is_back
+ - id: HFR-022
+ name: unknown queue deliverability disables the transport class
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_skips_transport_class_when_deliverability_is_unknown
+ - id: HFR-023
+ name: terminal result cannot overwrite an acknowledged stop's settlement reason
+ status: covered
+ kind: idempotency
+ layer: contract
+ backend: shared
+ test: tests/test_dispatcher_stream_chunk.py::test_result_does_not_overwrite_an_acknowledged_stop_stamp
+ - id: HFR-024
+ name: transport TTL is measured from the outage, not the enqueue
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_ages_a_transport_failure_from_when_it_started
+ - id: HFR-025
+ name: a transport reason with no timestamp is never acted on
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_never_terminalizes_a_transport_reason_with_no_timestamp
+ - id: HFR-026
+ name: live ownership exempts an aged queue hold from its TTL
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_spares_an_aged_queue_hold_a_live_turn_still_owns
+ - id: HFR-027
+ name: gate-owned Workbench turn settles its own Run when no result arrives
+ status: covered
+ kind: failure
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_workbench_turn_settles_its_agent_run_when_no_result_arrives
+ - id: HFR-028
+ name: swept Run's persisted queue segment is retired immediately
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_retires_the_queue_segment_of_the_run_it_expired
+ - id: HFR-029
+ name: backend runtime refresh settles its Run as a refresh, not a user stop
+ status: covered
+ kind: failure
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_backend_refresh_settles_its_run_as_a_refresh_not_a_user_stop
+ - id: HFR-030
+ name: terminal output that keeps the Run elsewhere is stamped turn-only
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_message_dispatcher_result_fallback.py::MessageDispatcherResultFallbackTests::test_turn_only_terminal_release_does_not_claim_the_run
+ - id: HFR-031
+ name: turn lane leaves an Activity-owned Run running
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_turn_only_result_leaves_an_activity_owned_run_alone
+ - id: HFR-032
+ name: drain lane leaves an Activity-owned Run running
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_drain_lane_leaves_a_run_whose_turn_released_without_claiming_it
+ - id: HFR-033
+ name: a recovered transport gives the next outage its own full TTL
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_grants_a_second_outage_its_own_ttl_after_a_recovery
+ - id: HFR-034
+ name: a hold parked behind a live session turn is spared
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_spares_a_hold_parked_behind_a_live_session_turn
+ - id: HFR-035
+ name: unknown live turns disable the hold class instead of failing holds
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_sweep_skips_hold_class_when_live_session_turns_are_unknown
+ - id: HFR-036
+ name: a stop's synthetic result records no run terminal
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_message_dispatcher_result_fallback.py::MessageDispatcherResultFallbackTests::test_stop_output_release_names_the_stop_and_records_no_run_terminal
+ - id: HFR-037
+ name: a stopped run settles canceled rather than succeeded
+ status: covered
+ kind: failure
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_a_stopped_run_settles_canceled_not_succeeded
+ - id: HFR-038
+ name: stop output ends the turn while preserving the request's output policy
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_agent_stop_settlement.py::AgentStopSettlementTests::test_stop_output_ends_the_turn_without_owning_the_run
+ - id: HFR-039
+ name: a backend's live stop path emits stop semantics
+ status: covered
+ kind: failure
+ layer: contract
+ backend: codex
+ test: tests/test_agent_stop_settlement.py::AgentStopSettlementTests::test_codex_stop_emits_stop_semantics
+ - id: HFR-040
+ name: no backend stop may use the terminal-turn default
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_agent_stop_settlement.py::AgentStopSettlementTests::test_no_backend_stop_uses_the_terminal_turn_default
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
+plans:
+ - docs/plans/harness-session-failure-recovery.md
+ - docs/plans/agent-run-zombie-settlement.md
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index 5b4a55389..79d2bbd77 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -63,3 +63,201 @@ observations:
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.
+ - id: HFR-OBS-008
+ date: 2026-07-25
+ source: code-path trace of dispatch_turn and its callers
+ result: confirmed
+ detail: >-
+ A turn sink can be released without ever emitting a terminal result -
+ a blank harness message, or a refusal because the Session already has a
+ streaming turn. dispatch_turn returned success in both cases, so
+ _execute_agent_run reported nothing and the Run stayed running forever.
+ The refusal path returns before any sink exists, so the sink itself
+ cannot carry the reason; the outcome has to be reported by the caller.
+ - id: HFR-OBS-009
+ date: 2026-07-25
+ source: code-path trace of the two ownership lanes
+ result: confirmed
+ detail: >-
+ A running Run is owned by either the drain lane
+ (ScheduledTaskService._inflight_executions) or the turn lane
+ (SessionTurnManager in_flight plus active_turn_sinks), and neither can
+ observe the other. Nothing periodically reconciles rows whose owner
+ disappeared inside a live process, and queued rows never age at all, so
+ a Run stranded by a transport that never reconnected waits with no
+ user-visible explanation and keeps its Session slot.
+ - id: HFR-OBS-010
+ date: 2026-07-25
+ source: code-path trace of SqliteInvalidationProbe.has_external_write
+ result: confirmed
+ detail: >-
+ The store tick's reload gate bumps on any write to the database file,
+ including the service's own. Recording staleness evidence on every skip
+ iteration would therefore become a self-feeding write to reload to
+ re-drain loop for as long as a transport stayed down, plus one
+ runs.updated event per cycle. The evidence stamp must be written only
+ when the recorded reason changes, and must not bump updated_at.
+ - id: HFR-OBS-011
+ date: 2026-07-25
+ source: deterministic startup-recovery fault injection
+ result: confirmed
+ detail: >-
+ recover_processing_runs requeues every running row at service
+ construction, so a restart retries its in-flight Runs rather than
+ leaving them for the sweep. The swept orphan class is therefore about
+ owners lost within a live process, and any staged running fixture must
+ be written after the service is constructed or recovery flips it to
+ queued first.
+ - id: HFR-OBS-012
+ date: 2026-07-25
+ source: review of _drain_requests capacity break against the sweep's evidence read
+ result: confirmed
+ detail: >-
+ The drain breaks at _MAX_CONCURRENT_EXECUTIONS without examining the
+ remaining queue, so rows below the cut keep whatever skip reason they
+ last carried. A transport_unavailable stamp therefore survives long
+ after the platform reconnected, and sweeping on the stamp alone would
+ fail a Run that is merely waiting for a free slot. The transport class
+ needs a live second opinion (deliverable_run_ids) in addition to the
+ recorded reason, and must disable itself when that opinion is
+ unavailable.
+ - id: HFR-OBS-013
+ date: 2026-07-25
+ source: review of the stop-versus-terminal-result ordering in _stream_chunk
+ result: confirmed
+ detail: >-
+ An acknowledged stop stamps settled_by in memory and releases the waiter
+ immediately, while the Run row is only written later when
+ _execute_agent_run reads the stamp back. A terminal result arriving in
+ that window overwrote the reason, so the guarded canceled settlement was
+ skipped and the outcome depended on which coroutine resumed first. The
+ reason the user was already shown must win; the row's terminal status
+ stays first-writer-wins.
+ - id: HFR-OBS-014
+ date: 2026-07-25
+ source: review of the transport TTL clock against a long-queued Run
+ result: confirmed
+ detail: >-
+ A Run can sit in queued far longer than the transport TTL for reasons that
+ are progress, such as capacity or a busy Session. Aging the transport class
+ from created_at therefore made such a Run sweepable on the first tick after
+ its transport blinked, consuming none of the configured reconnect window.
+ The TTL is a reconnect window, so it must be measured from last_skip_at,
+ the instant the transport reason started, which the transition-triggered
+ skip stamp already records.
+ - id: HFR-OBS-015
+ date: 2026-07-25
+ source: review of owned_agent_run_ids against the workbench queue-hold TTL
+ result: confirmed
+ detail: >-
+ A coalesced Workbench turn claims its secondary Runs and deliberately
+ leaves them queued with workbench_queue_holds_run while the primary
+ settles them, and owned_agent_run_ids reports every one of those ids as
+ actively owned. Ownership therefore cannot be a running-only exemption:
+ a hold TTL that ignored it would fail live sibling Runs as soon as the
+ turn outran the TTL, reintroducing a turn-duration timeout by the back
+ door. A live owner outranks every staleness class, whatever the row
+ status, so the check belongs at the top of the candidate loop rather than
+ duplicated per branch.
+ - id: HFR-OBS-016
+ date: 2026-07-25
+ source: review of the avibe gate hand-off against the two settlement lanes
+ result: confirmed
+ detail: >-
+ An avibe-targeted execution hands its prompt to the Session turn gate and
+ returns from _execute_agent_run with complete_on_return false while the
+ turn is still live, so the drain lane deliberately keeps its hands off the
+ row. Only the turn lane can settle it, but the turn lane called the thin
+ dispatch_turn wrapper that discards settled_by, so a turn released without
+ a terminal result left the Run running forever until the sweep grace
+ expired. Whichever lane owns the row must read the settlement vocabulary,
+ not just the error, and settle through the same guarded first-writer-wins
+ writer so racing an honest terminal result is safe in both directions.
+ - id: HFR-OBS-017
+ date: 2026-07-25
+ source: review of a swept queue hold against the persisted Workbench queue
+ result: confirmed
+ detail: >-
+ Terminalizing an agent_runs row is not the whole reclamation: a queue-hold
+ Run also owns a persisted queued messages segment keyed by
+ agent_run:<run_id>. recover_persisted_agent_run_queue ignores references
+ whose Run is no longer queued, so after the sweep expired the hold the
+ Session still displayed stale pending input until an unrelated send forced
+ a flush. The sweep must retire each expired Run's own queue segment,
+ scoped by that run id so it can never touch a live sibling's row, and
+ publish queue.updated so the surface reflects the reclamation immediately.
+ - id: HFR-OBS-018
+ date: 2026-07-25
+ source: review of the turn-lane CancelledError handler against release_for_backend_refresh
+ result: confirmed
+ detail: >-
+ A cancelled turn task carries no cause. release_for_backend_refresh cancels
+ in-flight turns whenever an agents.* save triggers the required rolling
+ backend reconciliation, so reading every CancelledError as a user Stop made
+ a Run killed by routine configuration work settle canceled with the
+ user-stop explanation: the callback told the user they stopped a Run they
+ never touched, and failure accounting saw deliberate intent instead of an
+ infrastructure fault. The canceller is the only party that knows why, so the
+ cause has to be recorded on the Turn before task.cancel() and read back when
+ the turn is popped. The default reading of a bare cancellation stays stopped,
+ because a plain Stop and send-now are the paths that legitimately have no
+ more specific reason.
+ - id: HFR-OBS-019
+ date: 2026-07-25
+ source: review of both settlement lanes against the Claude Activity delivery-failure emit
+ result: confirmed
+ detail: >-
+ "The turn ended" is not "the Run ended". _settle_activity_turn_after_delivery_failure
+ closes its origin turn with a silent terminal result carrying
+ completes_run=False, because the REQUEUED Activity keeps the Run and retries
+ it. That emit still mutates the turn lifecycle, so the release ran through
+ mark_turn_complete, whose own default reason is the no-dispatch case: both
+ lanes then read no_terminal_result and failed a live Activity-owned Run,
+ firing its terminal callback before the retry ever ran. The release site is
+ the only party that knows whether it also owns the Run, so it must supply the
+ reason, and both lanes must allow-list the settlements that genuinely mean no
+ result is coming (SETTLEMENTS_WITHOUT_RESULT) rather than treating everything
+ except terminal_result as a zombie -- otherwise the next "turn ended, run
+ lives on" reason repeats the same failure.
+ - id: HFR-OBS-020
+ result: confirmed
+ detail: >-
+ Staleness evidence is a point-in-time fact, and the sweep is the only party
+ that sees both halves of its lifetime. A queued row stamped
+ transport_unavailable at t0 stays stamped after transport recovers, because
+ re-stamping is transition-triggered and a drain that never reaches the row
+ (at concurrency capacity) rewrites nothing; deliverability then exempts it,
+ so nobody retires the stamp. When transport drops again at t2 > t0 + TTL, the
+ second outage is aged from the FIRST one and is swept with zero reconnect
+ window. Retiring the evidence at the moment deliverability proves the outage
+ is over restores the invariant that a TTL measures one continuous outage.
+ The same shape holds for the hold class: owned_agent_run_ids() reports only
+ the ids a live turn is executing, never the followers the gate parked behind
+ it, so a turn legitimately longer than harness_run_hold_ttl_seconds had its
+ own queued successor failed. Live facts the sweep cannot derive must be
+ supplied by the caller at the granularity the truth lives at -- sessions for
+ the gate, run ids for ownership and deliverability -- and a caller that
+ cannot enumerate them must fail closed by disabling the class rather than
+ guessing.
+ - id: HFR-OBS-021
+ result: confirmed
+ detail: >-
+ A synthetic terminal result is not evidence of a result. Every backend answers
+ an acknowledged stop with an empty silent ``result`` so the dot settles and the
+ SSE waiter closes through the one outbound chokepoint, and all three sent it
+ with the terminal-turn default (completes_run=True). The dispatcher therefore
+ recorded that empty body as the run's ``succeeded`` terminal BEFORE the stop's
+ own guarded write, so first-writer-wins reported every normally-stopped run as
+ a success and left the ``stopped`` -> ``canceled`` mapping reachable only when
+ the backend could not emit at all (stop_failed, stale release, IM /stop). The
+ earlier design accepted this race as benign because either outcome is "true of
+ a run the user stopped"; that was wrong, because the ordering is not a race at
+ all -- SessionTurnManager.cancel awaits the interrupt (which emits) and only
+ then cancels the task, so the losing branch was the ONLY branch. Correcting it
+ means the stop output declaring what it is: completes_turn=True so the turn
+ still ends, completes_run=False so an empty body never becomes a terminal
+ status, and an explicit settled_by so "I do not settle the run" is not confused
+ with the Activity case where somebody else genuinely owns the row. Where an
+ identical emit is copied across backends, the guard has to be cross-backend too
+ -- one behavior test pins one backend and lets the other two regress.
+
diff --git a/tests/test_agent_stop_settlement.py b/tests/test_agent_stop_settlement.py
new file mode 100644
index 000000000..c59c2a312
--- /dev/null
+++ b/tests/test_agent_stop_settlement.py
@@ -0,0 +1,154 @@
+"""Every backend's acknowledged stop must settle its Run as ``canceled``.
+
+A stop is answered by a synthetic empty ``result``: it ends the turn so the dot goes
+idle and the SSE waiter closes, but nobody produced an answer — the user called the
+work off. Emitting it with the terminal-turn default made the dispatcher record that
+empty body as the run's ``succeeded`` terminal, and because that write lands before
+the stop's own guarded write, first-writer-wins reported user-ended runs as
+successes (``docs/plans/agent-run-zombie-settlement.md`` §5.10).
+
+These are cross-backend on purpose. The bug was identical in Codex, Claude, and
+OpenCode because all three copied the same emit, so the guard has to be the kind a
+fourth backend cannot miss.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.message_output import MessageOutput, stop_output_for
+from core.run_settlement import SETTLED_BY_STOPPED, SETTLEMENT_TERMINAL_STATUS
+from modules.agents.claude_agent import ClaudeAgent
+from modules.agents.codex.agent import CodexAgent
+from modules.agents.opencode.agent import OpenCodeAgent
+
+
+def _emitted_message_type(call: ast.Call) -> str | None:
+ """The literal message type an ``emit_agent_message`` call passes, if any."""
+
+ if len(call.args) >= 2 and isinstance(call.args[1], ast.Constant):
+ return call.args[1].value
+ for keyword in call.keywords:
+ if keyword.arg == "message_type" and isinstance(keyword.value, ast.Constant):
+ return keyword.value.value
+ return None
+
+
+class _StubTurnRegistry:
+ def __init__(self) -> None:
+ self._active_turns: dict[str, str] = {}
+
+ def get_active_turn(self, base_session_id):
+ return self._active_turns.get(base_session_id)
+
+ def hide_turn(self, *_args, **_kwargs):
+ return None
+
+
+class AgentStopSettlementTests(unittest.IsolatedAsyncioTestCase):
+ def test_stop_output_ends_the_turn_without_owning_the_run(self):
+ """HFR-038: the shared stop policy, stated once.
+
+ ``completes_turn`` is what settles the dot and releases the waiter;
+ ``completes_run=False`` keeps an empty body out of the run's terminal state;
+ ``settled_by`` is what still lets the settlement lanes reach the ``canceled``
+ writer instead of reading "does not settle the run" as the Activity case.
+ """
+ semantics = stop_output_for(None)
+
+ self.assertTrue(semantics.completes_turn)
+ self.assertFalse(semantics.settles_run)
+ self.assertEqual(semantics.settled_by, SETTLED_BY_STOPPED)
+ self.assertEqual(SETTLEMENT_TERMINAL_STATUS[SETTLED_BY_STOPPED], "canceled")
+
+ def test_stop_output_keeps_a_requests_own_output_policy(self):
+ """HFR-038 (other half): only the lifecycle is overridden.
+
+ A request carrying Activity lineage or an explicit ``run_id`` must keep it, or
+ the settlement lands on the wrong row.
+ """
+ request = SimpleNamespace(
+ output=MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ run_id="run-7",
+ activity_id="act-3",
+ )
+ )
+
+ semantics = stop_output_for(request)
+
+ self.assertEqual(semantics.run_id, "run-7")
+ self.assertEqual(semantics.activity_id, "act-3")
+ self.assertFalse(semantics.settles_run)
+ self.assertEqual(semantics.settled_by, SETTLED_BY_STOPPED)
+
+ async def test_codex_stop_emits_stop_semantics(self):
+ """HFR-039: the live path, not just the helper — Codex as the worked example."""
+ agent = object.__new__(CodexAgent)
+ agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")
+ agent._turn_registry = _StubTurnRegistry()
+ agent._turn_registry._active_turns["session-1"] = "turn-1"
+ agent._transports = {
+ "/tmp": SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))
+ }
+ agent._event_handler = SimpleNamespace(clear_pending=lambda turn_id: SimpleNamespace())
+ agent._remove_ack_reaction = AsyncMock()
+ emit = AsyncMock()
+ agent.controller = SimpleNamespace(emit_agent_message=emit)
+ request = SimpleNamespace(base_session_id="session-1", working_path="/tmp", context=object())
+
+ self.assertTrue(await agent.handle_stop(request))
+
+ semantics = emit.await_args.kwargs["output"]
+ self.assertFalse(semantics.settles_run)
+ self.assertEqual(semantics.settled_by, SETTLED_BY_STOPPED)
+
+ def test_no_backend_stop_uses_the_terminal_turn_default(self):
+ """HFR-040: the guard a fourth backend cannot miss.
+
+ The defect was copied verbatim into three backends, so pinning one behavior
+ test would leave the other two free to regress. Asserting on the emit *in
+ every* ``handle_stop`` is what makes the shared policy enforceable: a new
+ backend that reaches for ``terminal_output_for`` in its stop path fails here
+ instead of silently reporting stopped runs as successes.
+ """
+ for agent_cls in (CodexAgent, ClaudeAgent, OpenCodeAgent):
+ with self.subTest(agent=agent_cls.__name__):
+ tree = ast.parse(inspect.getsource(agent_cls.handle_stop).lstrip())
+ emits = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "emit_agent_message"
+ # Only the terminal ``result`` carries settlement authority. A
+ # stop path may also emit ``notify`` (Claude's "cannot be
+ # interrupted" / "interrupt failed" refusals), which settles
+ # nothing and returns False without ending the turn.
+ and _emitted_message_type(node) == "result"
+ ]
+ self.assertTrue(emits, "a stop must answer with a terminal result")
+ for call in emits:
+ output = next(
+ (kw.value for kw in call.keywords if kw.arg == "output"), None
+ )
+ self.assertIsNotNone(output, "the stop emit must state its semantics")
+ self.assertIsInstance(output, ast.Call)
+ self.assertEqual(
+ getattr(output.func, "id", None),
+ "stop_output_for",
+ "a stop's empty result must not claim the run's terminal state",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_controller_agent_status.py b/tests/test_controller_agent_status.py
index 4de9dcf71..2d7664fb6 100644
--- a/tests/test_controller_agent_status.py
+++ b/tests/test_controller_agent_status.py
@@ -21,6 +21,8 @@ from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.controller import Controller
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from core.services.dispatch import TurnDispatchOutcome
from modules.agents.service import AgentService
@@ -109,8 +111,11 @@ def test_run_marks_running_at_acceptance_before_dispatch(monkeypatch, tmp_path):
async def _dispatch(controller_arg, context, text, **kwargs):
dispatched.append(text)
+ # The manager branches on the outcome to settle a run whose turn ended with no
+ # terminal result, so a double returns one (here: the honest result path).
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- monkeypatch.setattr(session_turns_module, "dispatch_turn", _dispatch)
+ monkeypatch.setattr(session_turns_module, "dispatch_turn_with_outcome", _dispatch)
async def _exercise():
await mgr._run("ses-accept", _ctx("ses-accept"), "hi")
diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.py
index 2b41fa08d..d64eb7f6d 100644
--- a/tests/test_core_services_dispatch.py
+++ b/tests/test_core_services_dispatch.py
@@ -25,10 +25,16 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from core.run_settlement import (
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ SETTLED_BY_TERMINAL_RESULT,
+)
from core.services.dispatch import (
SOURCE_HUMAN,
SOURCE_SCHEDULED,
dispatch_turn,
+ dispatch_turn_with_outcome,
)
from modules.im import MessageContext
@@ -127,6 +133,73 @@ def test_on_chunk_absent_keeps_platform_specific_untouched():
)
+def _streaming_controller(*, sink_settled_by: str | None, in_flight: bool = False) -> MagicMock:
+ """A controller double whose registered sink is released like the real one.
+
+ ``sink_settled_by`` is the stamp the release site would have written:
+ ``terminal_result`` for a real backend result, ``None`` for a release that left
+ no trace (``mark_turn_complete`` on a no-dispatch turn).
+ """
+
+ controller = _build_controller_double()
+ sinks: dict = {}
+
+ def _register(session_key, *, on_chunk, done_event, turn_token=None, context=None):
+ sink = {"on_chunk": on_chunk, "done_event": done_event, "turn_token": turn_token}
+ if sink_settled_by is not None:
+ sink["settled_by"] = sink_settled_by
+ sinks[session_key] = sink
+ done_event.set()
+
+ controller._get_session_key = MagicMock(return_value="slack::C")
+ controller.get_turn_sink = MagicMock(side_effect=lambda key: sinks.get(key))
+ controller.register_turn_sink = MagicMock(side_effect=_register)
+ controller.pop_turn_sink = MagicMock(side_effect=lambda key, done=None: sinks.pop(key, None))
+ if in_flight:
+ # Pre-register a live sink for the same session: a turn is already streaming.
+ sinks["slack::C"] = {"on_chunk": AsyncMock(), "done_event": asyncio.Event()}
+ return controller
+
+
+def test_outcome_reports_terminal_result_settlement():
+ controller = _streaming_controller(sink_settled_by=SETTLED_BY_TERMINAL_RESULT)
+ outcome = asyncio.run(dispatch_turn_with_outcome(controller, _ctx(), "hi", on_chunk=AsyncMock()))
+ assert outcome.settled_by == SETTLED_BY_TERMINAL_RESULT
+
+
+def test_outcome_reports_release_without_terminal_result():
+ # The zombie case: the waiter was released but no terminal result arrived, so a
+ # caller holding a durable run record must settle it itself.
+ controller = _streaming_controller(sink_settled_by=None)
+ outcome = asyncio.run(dispatch_turn_with_outcome(controller, _ctx(), "hi", on_chunk=AsyncMock()))
+ assert outcome.settled_by == SETTLED_BY_NO_TERMINAL_RESULT
+
+
+def test_outcome_reports_refused_concurrent_turn():
+ # The refusal returns BEFORE any sink is registered, so the settlement cannot
+ # ride the sink — it has to be reported directly or the caller's run row would
+ # stay open forever.
+ controller = _streaming_controller(sink_settled_by=None, in_flight=True)
+ controller._t = MagicMock(return_value="already streaming")
+ on_chunk = AsyncMock()
+ outcome = asyncio.run(dispatch_turn_with_outcome(controller, _ctx(), "hi", on_chunk=on_chunk))
+ assert outcome.settled_by == SETTLED_BY_REFUSED_CONCURRENT_TURN
+ assert outcome.error is None
+ on_chunk.assert_awaited_once()
+ controller.register_turn_sink.assert_not_called()
+ controller.message_handler.handle_user_message.assert_not_called()
+
+
+def test_outcome_settled_by_is_none_only_without_on_chunk():
+ # ``None`` must mean exactly one thing — "no streaming caller, so no sink" —
+ # otherwise a durable caller cannot tell an unexplained release apart from a
+ # non-streaming dispatch.
+ controller = _build_controller_double()
+ outcome = asyncio.run(dispatch_turn_with_outcome(controller, _ctx(), "hi"))
+ assert outcome.settled_by is None
+ assert outcome.error == "msg_user_1"
+
+
def test_invalid_source_raises():
"""Future-proof: unknown source must not silently fall through to a
handler that the caller didn't intend."""
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index 25afd7b25..3f5908c35 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -20,6 +20,7 @@ from unittest.mock import AsyncMock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import _stream_chunk
+from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT
from modules.im import MessageContext
@@ -70,6 +71,57 @@ def test_result_kind_sets_done_event():
assert done.is_set(), "a result emit must release the streaming dispatch"
+def test_result_kind_stamps_terminal_settlement_on_sink():
+ # The stamp is what tells a durable caller (an ``agent_runs`` row) that a REAL
+ # terminal result arrived, so the out-of-band writer owns the terminal state.
+ # Without it every honest run would be re-settled as failed.
+ controller = _ControllerDouble()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=asyncio.Event())
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+ assert controller.get_turn_sink("avibe::C")["settled_by"] == SETTLED_BY_TERMINAL_RESULT
+
+
+def test_result_does_not_overwrite_an_acknowledged_stop_stamp():
+ """HFR-023: a terminal result landing after an acknowledged Stop keeps ``stopped``.
+
+ The stop path stamps the sink in memory and sets ``done`` immediately, but the
+ run row is only written later, when ``_execute_agent_run`` reads the stamp back.
+ A result arriving inside that window used to overwrite ``stopped`` with
+ ``terminal_result``, so the guarded ``canceled`` settlement was skipped and the
+ user was told the run was stopped while the row said otherwise. The stamp the
+ user was already shown wins; the row's terminal status stays first-writer-wins.
+ """
+
+ controller = _ControllerDouble()
+ done = asyncio.Event()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)
+ sink = controller.get_turn_sink("avibe::C")
+ # The user's stop: reason recorded, waiter released, row not written yet.
+ sink["settled_by"] = SETTLED_BY_STOPPED
+ done.set()
+
+ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))
+
+ assert sink["settled_by"] == SETTLED_BY_STOPPED
+
+
+def test_notify_kind_leaves_sink_unsettled():
+ # Only a terminal result may claim the honest settlement.
+ controller = _ControllerDouble()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=asyncio.Event())
+ asyncio.run(_stream_chunk(controller, _ctx(), text="thinking", message_id="m1", kind="notify"))
+ assert controller.get_turn_sink("avibe::C").get("settled_by") is None
+
+
+def test_stale_result_does_not_stamp_active_turns_sink():
+ # A superseded turn's late result must not make the live turn look completed —
+ # neither via the done event nor via the settlement stamp.
+ controller = _ControllerDouble()
+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=asyncio.Event(), turn_token="T2")
+ asyncio.run(_stream_chunk(controller, _ctx(turn_token="T1"), text="stale", message_id="m1", kind="result"))
+ assert controller.get_turn_sink("avibe::C").get("settled_by") is None
+
+
def test_notify_kind_leaves_done_event_unset():
controller = _ControllerDouble()
done = asyncio.Event()
diff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.py
new file mode 100644
index 000000000..eee859172
--- /dev/null
+++ b/tests/test_i18n_backend_keys.py
@@ -0,0 +1,82 @@
+"""Key-parity guard for the backend i18n bundles.
+
+``vibe/i18n`` falls back to English for a missing key, so a translation added to
+one bundle and forgotten in the other degrades silently — the user sees English in
+a Chinese conversation, and a typo'd key leaks the raw dotted path into a message.
+Both failure modes are cheap to catch here.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.run_settlement import SETTLEMENT_I18N_KEYS, SWEEP_I18N_KEYS
+from storage.background import (
+ SWEEP_REASON_ORPHANED,
+ SWEEP_REASON_QUEUE_HOLD_EXPIRED,
+ SWEEP_REASON_TRANSPORT_UNAVAILABLE,
+)
+from vibe.i18n import get_supported_languages, t
+
+I18N_DIR = Path(__file__).resolve().parents[1] / "vibe" / "i18n"
+
+
+def _flatten(value: dict, prefix: str = "") -> dict[str, str]:
+ flat: dict[str, str] = {}
+ for key, item in value.items():
+ path = f"{prefix}.{key}" if prefix else key
+ if isinstance(item, dict):
+ flat.update(_flatten(item, path))
+ else:
+ flat[path] = item
+ return flat
+
+
+def _bundle(lang: str) -> dict[str, str]:
+ return _flatten(json.loads((I18N_DIR / f"{lang}.json").read_text(encoding="utf-8")))
+
+
+def test_backend_bundles_have_identical_keys() -> None:
+ en = _bundle("en")
+ zh = _bundle("zh")
+ assert sorted(en) == sorted(zh), (
+ f"missing in zh: {sorted(set(en) - set(zh))}; missing in en: {sorted(set(zh) - set(en))}"
+ )
+
+
+def test_no_backend_translation_is_blank() -> None:
+ for lang in ("en", "zh"):
+ blank = [key for key, value in _bundle(lang).items() if not str(value).strip()]
+ assert blank == [], f"{lang} has blank translations: {blank}"
+
+
+ "reason,key",
+ sorted(SETTLEMENT_I18N_KEYS.items()) + sorted(SWEEP_I18N_KEYS.items()),
+)
+def test_every_run_settlement_reason_resolves(reason: str, key: str) -> None:
+ # These strings land in the run's user-visible ``error`` column, so an unresolved
+ # key would show up verbatim in the Runs UI and the callback message.
+ for lang in get_supported_languages():
+ resolved = t(key, lang)
+ assert resolved != key, f"{key} is not translated in {lang} (reason={reason})"
+ assert resolved.strip()
+
+
+def test_sweep_reason_i18n_map_covers_every_store_sweep_reason() -> None:
+ # ``SWEEP_I18N_KEYS`` spells its keys as literals so ``core.run_settlement``
+ # stays dependency-free (see the comment there). This is the guard that makes
+ # that safe: add a sweep reason in the store without a translation and the
+ # sweep would stamp a run with an empty ``error``, which reads to the user as
+ # "it just failed" with no explanation.
+ assert set(SWEEP_I18N_KEYS) == {
+ SWEEP_REASON_ORPHANED,
+ SWEEP_REASON_TRANSPORT_UNAVAILABLE,
+ SWEEP_REASON_QUEUE_HOLD_EXPIRED,
+ }
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index e735ca393..2ad2e126b 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -29,7 +29,13 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core import internal_server, session_turns
-from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from core.services.dispatch import (
+ SOURCE_HUMAN,
+ SOURCE_SCHEDULED,
+ TurnDispatchOutcome,
+ dispatch_turn,
+)
from modules.im import MessageContext
@@ -620,8 +626,9 @@ def test_dispatch_async_no_terminal_result_keeps_session_in_flight(monkeypatch,
# the turn never settles on its own.
started.set()
await asyncio.sleep(60)
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- monkeypatch.setattr(session_turns, "dispatch_turn", _never_settles)
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _never_settles)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -839,6 +846,7 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
async def long_handler(ctx, text):
started.set()
await asyncio.sleep(5) # held until the test cancels it
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
return None
controller = _build_controller_double(handler=long_handler)
@@ -1286,8 +1294,11 @@ def test_scheduled_gate_idle_runs_turn_with_lifecycle(monkeypatch, tmp_path):
captured["text"] = text
captured["in_flight_while_running"] = "ses_sched" in app.state.in_flight_dispatches
started.set()
+ # The manager now branches on the outcome to settle a run whose turn ended
+ # without a terminal result, so a double has to return one.
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- monkeypatch.setattr(session_turns, "dispatch_turn", _fake_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _fake_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -1356,7 +1367,7 @@ def test_scheduled_gate_busy_enqueues_and_leaves_chat_turn_untouched(monkeypatch
async def _explode_dispatch_turn(*args, **kwargs):
raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")
- monkeypatch.setattr(session_turns, "dispatch_turn", _explode_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _explode_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -1416,7 +1427,7 @@ def test_scheduled_gate_busy_duplicate_native_id_is_skipped(monkeypatch, tmp_pat
async def _explode_dispatch_turn(*args, **kwargs):
raise AssertionError("a busy scheduled run must enqueue, not dispatch a turn")
- monkeypatch.setattr(session_turns, "dispatch_turn", _explode_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _explode_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
@@ -1498,8 +1509,9 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
async def _long_dispatch_turn(ctrl, ctx, text, *, source=SOURCE_HUMAN, on_chunk=None):
started.set()
await asyncio.sleep(5) # held until the test cancels it
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- monkeypatch.setattr(session_turns, "dispatch_turn", _long_dispatch_turn)
+ monkeypatch.setattr(session_turns, "dispatch_turn_with_outcome", _long_dispatch_turn)
controller = _build_controller_double()
app = internal_server.create_app(controller)
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 7ac3f4de3..6561bbc63 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -9,7 +9,14 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
-from core.message_output import MessageOutput
+from core.message_output import MessageOutput, stop_output_for
+from core.run_settlement import (
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+ SETTLED_BY_TURN_ONLY_RESULT,
+ SETTLEMENT_TERMINAL_STATUS,
+ SETTLEMENTS_WITHOUT_RESULT,
+)
from modules.im import MessageContext
@@ -317,9 +324,119 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
)
dispatcher._collapse_status_bubble.assert_awaited_once()
dispatcher._clear_consolidated_state.assert_awaited_once_with(context)
- controller.mark_turn_complete.assert_called_once_with(context)
+ controller.mark_turn_complete.assert_called_once_with(
+ context,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
controller.agent_service.release_runtime_turn.assert_called_once_with(context)
+ def _terminal_lifecycle_controller(self):
+ controller = _StubController(platform="slack")
+ controller.agent_service = type(
+ "Service",
+ (),
+ {
+ "emit_matches_runtime_turn": lambda self, context: True,
+ "release_runtime_turn": mock.Mock(),
+ },
+ )()
+ controller.session_turns = type(
+ "Turns",
+ (),
+ {"on_terminal_result": mock.Mock()},
+ )()
+ controller.mark_turn_complete = mock.Mock()
+ return controller
+
+ async def _emit_silent_terminal(self, controller, *, completes_run: bool, output=None):
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._collapse_status_bubble = mock.AsyncMock()
+ dispatcher._clear_consolidated_state = mock.AsyncMock()
+ dispatcher._record_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "runtime-turn-1",
+ "turn_token": "turn-1",
+ },
+ )
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "",
+ level="silent",
+ output=output
+ or MessageOutput(completes_turn=True, completes_run=completes_run),
+ )
+ return dispatcher, context
+
+ async def test_turn_only_terminal_release_does_not_claim_the_run(self):
+ """HFR-030: a terminal result that completes the turn but NOT the run stamps
+ ``turn_only_result``, so no settlement lane may terminalize the row.
+
+ This is the Claude Activity delivery-failure emit: the origin turn is closed
+ while the REQUEUED Activity keeps the run and retries. Stamping the
+ no-dispatch default here failed an Activity-owned run — and fired its
+ callback — before the retry ever ran.
+ """
+ controller = self._terminal_lifecycle_controller()
+
+ dispatcher, context = await self._emit_silent_terminal(controller, completes_run=False)
+
+ controller.mark_turn_complete.assert_called_once_with(
+ context,
+ settled_by=SETTLED_BY_TURN_ONLY_RESULT,
+ )
+ # The run's terminal state was never written here either — same owner rule.
+ dispatcher._record_agent_run_terminal_result.assert_not_called()
+ self.assertNotIn(SETTLED_BY_TURN_ONLY_RESULT, SETTLEMENTS_WITHOUT_RESULT)
+
+ async def test_run_settling_terminal_release_stamps_terminal_result(self):
+ """HFR-030 (other half): when the same emit DOES own the run, the stamp is
+ the honest ``terminal_result`` — otherwise a durable caller would re-settle a
+ run its backend already completed."""
+ controller = self._terminal_lifecycle_controller()
+
+ dispatcher, context = await self._emit_silent_terminal(controller, completes_run=True)
+
+ controller.mark_turn_complete.assert_called_once_with(
+ context,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ )
+ dispatcher._record_agent_run_terminal_result.assert_called_once()
+
+ async def test_stop_output_release_names_the_stop_and_records_no_run_terminal(self):
+ """HFR-036: the synthetic result a user stop emits must NOT record the run.
+
+ Every backend answers an acknowledged stop with an empty silent ``result``.
+ Sent with the terminal-turn default it recorded that empty body as the run's
+ ``succeeded`` terminal — and because that write lands before the stop's own
+ guarded write, first-writer-wins reported a user-ended run as a success. The
+ stop output must therefore claim no run terminal AND still name ``stopped``,
+ so the settlement lanes reach the writer that maps it to ``canceled``.
+ Deriving the reason from ``settles_run`` alone would say ``turn_only_result``,
+ which no lane may settle, and the row would be left ``running``.
+ """
+ controller = self._terminal_lifecycle_controller()
+
+ dispatcher, context = await self._emit_silent_terminal(
+ controller,
+ completes_run=False,
+ output=stop_output_for(None),
+ )
+
+ controller.mark_turn_complete.assert_called_once_with(
+ context,
+ settled_by=SETTLED_BY_STOPPED,
+ )
+ # A settlement the lanes MAY act on — unlike ``turn_only_result``.
+ self.assertIn(SETTLED_BY_STOPPED, SETTLEMENTS_WITHOUT_RESULT)
+ self.assertEqual(SETTLEMENT_TERMINAL_STATUS[SETTLED_BY_STOPPED], "canceled")
+ dispatcher._record_agent_run_terminal_result.assert_not_called()
+
async def test_slack_result_uses_native_markdown_sender_when_available(self):
im_client = _NativeMarkdownIMClient()
controller = _StubController(platform="slack", im_client=im_client)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index e0717a81e..b0491b2f9 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -3,18 +3,31 @@ from __future__ import annotations
import asyncio
import json
import sys
+from contextlib import suppress
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
+from typing import Any, Optional
from unittest.mock import AsyncMock, Mock
import pytest
-from sqlalchemy import select
+from sqlalchemy import select, update
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
from config.v2_settings import make_thread_native_id
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import stop_output_for
+from core.run_settlement import (
+ SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_TERMINAL_RESULT,
+ SETTLED_BY_TURN_ONLY_RESULT,
+)
+from core.services.dispatch import SOURCE_SCHEDULED, TurnDispatchOutcome
from core.session_activities import SessionActivityRegistry
+from core.session_turns import SessionTurnManager
from core.scheduled_tasks import (
ParsedSessionKey,
ScheduledTaskService,
@@ -30,6 +43,7 @@ from core.scheduled_tasks import (
from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
+from storage.models import agent_runs
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
from storage.agent_session_rows import create_agent_session_row
@@ -1775,8 +1789,11 @@ def test_restart_recovers_persisted_workbench_run_queue_after_older_owner_settle
text="recovered once",
terminal_status="succeeded",
)
+ # The honest path: a real terminal result, so the manager leaves the row to
+ # the out-of-band writer above instead of settling it itself.
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- monkeypatch.setattr("core.session_turns.dispatch_turn", _dispatch)
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _dispatch)
async def _exercise() -> None:
# The older scheduler-owned Run keeps its original FIFO position.
@@ -2221,235 +2238,1936 @@ def test_agent_run_preserves_failed_terminal_status(tmp_path: Path, monkeypatch)
assert completed["result_text"] == "terminal failed"
-def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path: Path, monkeypatch) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(2):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
+class _SettlementControllerDouble:
+ """Controller double for the Gap-A settlement cases.
+
+ Same surface as the ``terminal_result`` doubles above, but the fake turn
+ releases the sink the way a turn that never produced a result does. The session
+ key is a constant so a test can pre-register a live sink for it and drive the
+ concurrent-turn refusal deterministically.
+ """
+
+ SESSION_KEY = "settlement-session"
+
+ def __init__(self, *, on_turn=None) -> None:
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *a, **k: None))
+ self.platform_settings_managers = {"slack": settings_manager}
+ self.active_turn_sinks: dict[str, dict] = {}
+ self._on_turn = on_turn
+ self.turns: list[str] = []
+ self.message_handler = SimpleNamespace(handle_scheduled_message=self._handle_scheduled_message)
+
+ def _t(self, key: str, **_kwargs) -> str:
+ return key
+
+ 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,
)
- run_ids.append(request.id)
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
+ def _get_session_key(self, _context):
+ return self.SESSION_KEY
- async def _submit_scheduled(_sid, _ctx, _text):
- return "duplicate"
+ def get_turn_sink(self, session_key):
+ return self.active_turn_sinks.get(session_key)
- async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
+ self.active_turn_sinks[session_key] = {
+ "on_chunk": on_chunk,
+ "done_event": done_event,
+ "turn_token": turn_token,
+ }
+
+ def pop_turn_sink(self, session_key, done_event=None):
+ self.active_turn_sinks.pop(session_key, None)
+
+ async def _handle_scheduled_message(self, context, message, parsed_session_key=None):
+ self.turns.append(message)
+ if self._on_turn is not None:
+ await self._on_turn(self, context, message)
+ # Release the waiter WITHOUT recording a terminal result — exactly what
+ # ``Controller.mark_turn_complete`` does for a turn that never dispatched.
+ sink = self.get_turn_sink(self._get_session_key(context))
+ assert sink is not None
+ sink["done_event"].set()
return None
- 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,
+
+def _run_single_request(service: ScheduledTaskService, request_id: str) -> None:
+ async def _exercise() -> None:
+ await service._drain_requests()
+ execution = service._inflight_executions.get(request_id)
+ if execution is not None:
+ await execution
+
+ asyncio.run(_exercise())
+
+
+def test_agent_run_settles_failed_when_sink_released_without_terminal_result(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-009: a released waiter with no terminal result must not strand the run.
+
+ Nothing else will ever write this row — the out-of-band terminal writer only
+ runs on a real backend result — so leaving it ``running`` is the zombie.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
)
+ controller = _SettlementControllerDouble()
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
request_store=request_store,
)
- asyncio.run(service._drain_requests())
- stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
+ _run_single_request(service, request.id)
- assert stored[run_ids[0]]["status"] == "succeeded"
- 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)
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "failed"
+ assert settled["completed_at"] is not None
+ assert settled["error"]
+ assert settled["metadata"]["interrupt_reason"] == "no_terminal_result"
-def test_recover_processing_rebuilds_coalesced_metadata_without_queue_rows(
+def test_drain_lane_leaves_a_run_whose_turn_released_without_claiming_it(
tmp_path: Path,
monkeypatch,
) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(3):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- )
- run_ids.append(request.id)
+ """HFR-032: the drain lane must allow-list the settlements, not exclude one value.
+
+ A released waiter usually means "no result is coming", but not always: the Claude
+ Activity delivery-failure path closes its origin turn with ``turn_only_result``
+ while the requeued Activity keeps the run. Testing "anything but
+ ``terminal_result`` is a zombie" settled that live run ``failed`` and fired its
+ terminal callback before the retry ran, so the lane tests membership in
+ ``SETTLEMENTS_WITHOUT_RESULT`` instead.
+ """
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="delivery failed, activity requeued",
+ agent_name="claude",
+ )
- request_store.recover_processing()
- pending = request_store.list_pending()
+ async def _keep_the_run(controller, context, _message) -> None:
+ sink = controller.get_turn_sink(controller._get_session_key(context))
+ assert sink is not None
+ sink["settled_by"] = SETTLED_BY_TURN_ONLY_RESULT
- assert [request.id for request in pending] == [run_ids[0]]
- assert pending[0].metadata["coalesced_queue"]["execution_ids"] == run_ids
- assert _agent_run_message_for_request(pending[0]) == (
- "coalesced prompt 1\n\n---\n\ncoalesced prompt 2\n\n---\n\ncoalesced prompt 3"
+ controller = _SettlementControllerDouble(on_turn=_keep_the_run)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
)
+ _run_single_request(service, request.id)
-def test_recovered_agent_run_retires_stale_queued_native_rows_before_gate(
+ kept = request_store.get_run(request.id)
+ assert kept is not None
+ assert kept["status"] == "running"
+ assert kept["completed_at"] is None
+ assert not kept["error"]
+ assert not (kept["metadata"] or {}).get("interrupt_reason")
+
+
+def test_a_stopped_run_settles_canceled_not_succeeded(
tmp_path: Path,
monkeypatch,
) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
- request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(2):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- )
- run_ids.append(request.id)
-
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
+ """HFR-037: pressing End on a live run must report ``canceled``, not success.
- from storage import messages_service
- from storage.models import agent_sessions, messages
+ The backend answers an acknowledged stop with an empty silent ``result``. Sent
+ with the terminal-turn default that output claimed the run and recorded the empty
+ body as ``succeeded``; since it writes before the stop's own guarded write,
+ first-writer-wins made every normally-stopped run read as a success and left
+ round 5's ``canceled`` mapping unreachable on the path that actually runs.
- engine = create_sqlite_engine()
- with engine.begin() as conn:
- session = conn.execute(
- select(agent_sessions).where(agent_sessions.c.id == session_id).limit(1)
- ).mappings().first()
- assert session is not None
- scope_id = session["scope_id"]
- for run_id in run_ids:
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text=f"stale queued row for {run_id}",
- native_message_id=f"agent_run:{run_id}",
- )
+ The stamp here is derived from the production helpers rather than written as a
+ literal, so changing either the stop output's lifecycle or the release-reason
+ rule fails this test instead of silently reverting the behavior.
+ """
- submitted: list[str] = []
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="a long build the user gives up on",
+ agent_name="codex",
+ )
- async def _submit_scheduled(_sid, ctx, text):
- with engine.connect() as conn:
- if messages_service.native_message_exists(
- conn,
- platform="avibe",
- native_message_id=ctx.message_id,
- ):
- return "duplicate"
- submitted.append(text)
- return "ran"
+ stop_semantics = stop_output_for(None)
+ # A stop must not own the run's terminal state...
+ assert stop_semantics.settles_run is False
+ # ...but must still end the turn, so the dot settles and the SSE waiter closes.
+ assert stop_semantics.completes_turn is True
- async def _handle_scheduled_message(context, message, parsed_session_key=None):
- return None
+ async def _stop_the_turn(controller, context, _message) -> None:
+ sink = controller.get_turn_sink(controller._get_session_key(context))
+ assert sink is not None
+ sink["settled_by"] = ConsolidatedMessageDispatcher._turn_release_settlement(
+ stop_semantics
+ )
- gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
- controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+ controller = _SettlementControllerDouble(on_turn=_stop_the_turn)
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
request_store=request_store,
)
- async def _exercise() -> None:
- await service._drain_requests()
- execution = service._inflight_executions.get(run_ids[0])
- if execution is not None:
- await execution
+ _run_single_request(service, request.id)
- asyncio.run(_exercise())
+ stopped = request_store.get_run(request.id)
+ assert stopped is not None
+ # Called off, not broken, and not a success: the closed vocabulary's ``canceled``.
+ assert stopped["status"] == "canceled"
+ assert stopped["completed_at"] is not None
+ assert stopped["error"]
+ assert stopped["metadata"]["interrupt_reason"] == SETTLED_BY_STOPPED
- assert len(submitted) == 1
- assert "coalesced prompt 1" in submitted[0]
- assert "coalesced prompt 2" in submitted[0]
- with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- dedupe_rows = conn.execute(
- select(messages.c.native_message_id, messages.c.type)
- .where(messages.c.session_id == session_id)
- .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)
- ).all()
- assert {row.native_message_id for row in dedupe_rows} == {f"agent_run:{run_ids[1]}"}
- stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
- assert stored[run_ids[0]]["status"] == "running"
- assert stored[run_ids[1]]["status"] == "queued"
+def test_agent_run_settles_when_dispatch_refuses_a_concurrent_turn(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-010: the refusal returns before any sink exists, so the sink cannot carry it.
-def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path: Path, monkeypatch) -> None:
- session_id = _make_avibe_session(monkeypatch, tmp_path)
+ ``dispatch_turn`` refuses a second streaming turn for a session that already has
+ one in flight. That happens BEFORE ``register_turn_sink``, so an earlier design
+ that only inspected the sink saw ``settled_by=None`` and kept the run open.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
request_store = TaskExecutionStore()
- run_ids: list[str] = []
- for index in range(2):
- request = request_store.enqueue_agent_run(
- session_id=session_id,
- message=f"coalesced prompt {index + 1}",
- agent_name="codex",
- metadata={"workbench_queue_holds_run": True},
- )
- run_ids.append(request.id)
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+ controller = _SettlementControllerDouble()
+ # A turn is already streaming for this session.
+ controller.active_turn_sinks[_SettlementControllerDouble.SESSION_KEY] = {
+ "on_chunk": AsyncMock(),
+ "done_event": asyncio.Event(),
+ "turn_token": "live",
+ }
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
- sqlite_store = request_store._sqlite
- assert sqlite_store is not None
- assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
- request_store.recover_processing()
- claimed = request_store.claim(run_ids[0])
- assert claimed is not None
+ _run_single_request(service, request.id)
- async def _submit_scheduled(_sid, _ctx, _text):
- raise AssertionError("the direct execution path should be patched below")
+ assert controller.turns == [], "the refused turn must never reach the handler"
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "failed"
+ assert settled["completed_at"] is not None
+ assert settled["metadata"]["interrupt_reason"] == "refused_concurrent_turn"
- async def _handle_scheduled_message(context, message, parsed_session_key=None):
- return None
- gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
- controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+def test_agent_run_cancel_racing_settlement_keeps_canceled(tmp_path: Path, monkeypatch) -> None:
+ """HFR-011: a cancel landing mid-settlement must win (§3.3.1 TOCTOU).
+
+ The cancel is applied between the executor deciding to settle and the write
+ itself — the exact window an unguarded ``UPDATE`` would clobber. A fixture that
+ cancels up front would pass even with the unguarded writer, so this interleaves
+ for real.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+ controller = _SettlementControllerDouble()
service = ScheduledTaskService(
controller=controller,
store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
request_store=request_store,
)
- async def _raise_early(**_kwargs):
- raise RuntimeError("target session vanished")
+ original_settle = request_store.settle_without_result
+ raced: list[str] = []
- service._execute_agent_run = _raise_early
+ def _settle_after_cancel(run_id: str, **kwargs):
+ # The user cancels the still-``running`` row right before our write lands,
+ # and the cancel path terminalizes it.
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ sqlite_store.cancel_run(run_id)
+ assert (
+ sqlite_store.settle_run_terminal(run_id, terminal_status="canceled") == "canceled"
+ )
+ raced.append(run_id)
+ return original_settle(run_id, **kwargs)
- asyncio.run(service._execute_claimed_request(claimed))
- stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
+ monkeypatch.setattr(request_store, "settle_without_result", _settle_after_cancel)
- assert stored[run_ids[0]]["status"] == "failed"
- assert stored[run_ids[1]]["status"] == "failed"
- assert stored[run_ids[0]]["completed_at"] is not None
- assert stored[run_ids[1]]["completed_at"] is not None
- assert stored[run_ids[0]]["error"] == "target session vanished"
- assert stored[run_ids[1]]["error"] == "target session vanished"
+ _run_single_request(service, request.id)
+
+ assert raced == [request.id]
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "canceled", "the guarded writer must not clobber a settled row"
+ assert settled["metadata"].get("interrupt_reason") is None
-def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Path, monkeypatch) -> None:
+def test_agent_run_cancel_requested_settles_canceled_not_failed(tmp_path: Path, monkeypatch) -> None:
+ """A run the user asked to cancel reports ``canceled``, not ``failed``.
+
+ ``cancel_run`` on a ``running`` row only records the request; the terminal write
+ is ours, and it must honor that request in the same transaction.
+ """
+
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
- session_id="target-session",
- message="delegated work",
+ session_key="slack::channel::C123",
+ message="summarize the build",
agent_name="codex",
- callback_session_id=caller_session_id,
)
- request_store.complete(request, ok=True, session_id="target-session")
+
+ async def _cancel_mid_turn(_controller, _context, _message) -> None:
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.cancel_run(request.id) is True
+
+ controller = _SettlementControllerDouble(on_turn=_cancel_mid_turn)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, request.id)
+
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "canceled"
+ assert settled["completed_at"] is not None
+ assert settled["metadata"]["interrupt_reason"] == "no_terminal_result"
+
+
+class _StopSinkSettler:
+ """Drives a stop through the REAL ``settle_bound_turn_sink``.
+
+ Hand-stamping ``settled_by="stopped"`` would test the string, not the stamp
+ site. Borrowing the actual methods keeps the ``done.is_set()`` bail-out and the
+ object identity guard under test, which is what decides the ordering against a
+ real terminal result.
+ """
+
+ bind_context_to_turn_sink = SessionTurnManager.bind_context_to_turn_sink
+ settle_bound_turn_sink = SessionTurnManager.settle_bound_turn_sink
+ # Re-wrap: the real one is a staticmethod, and a bare function assigned to a
+ # class attribute would bind ``self`` as its first argument.
+ _sink_identity_matches = staticmethod(SessionTurnManager._sink_identity_matches)
+
+ def __init__(self, controller) -> None:
+ self.controller = controller
+ self.active_turn_sinks = controller.active_turn_sinks
+
+
+def test_agent_run_stopped_by_user_settles_canceled(tmp_path: Path, monkeypatch) -> None:
+ """HFR-012: running-tab End on an agent run terminalizes it as ``canceled``.
+
+ The backend was interrupted without emitting a terminal result, so nothing else
+ will ever write this row. ``canceled`` (not ``failed``) is the honest status:
+ the run did not break, the user called it off.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+
+ async def _stop_mid_turn(controller, context, _message) -> None:
+ settler = _StopSinkSettler(controller)
+ binding = settler.bind_context_to_turn_sink(context)
+ assert binding is not None
+ assert settler.settle_bound_turn_sink(binding) is True
+
+ controller = _SettlementControllerDouble(on_turn=_stop_mid_turn)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, request.id)
+
+ settled = request_store.get_run(request.id)
+ assert settled is not None
+ assert settled["status"] == "canceled", "an explicit stop is a cancellation, not a failure"
+ assert settled["completed_at"] is not None
+ assert settled["metadata"]["interrupt_reason"] == "stopped"
+
+
+def test_stop_defers_to_a_terminal_result_that_already_landed(tmp_path: Path, monkeypatch) -> None:
+ """A stop racing a terminal result that arrived FIRST must not steal the run.
+
+ This is the safe half of the stop race: the backend emitted its result (setting
+ the done event and stamping the honest settlement) before the stop fallback ran.
+ ``settle_bound_turn_sink`` must decline, leaving the out-of-band terminal writer
+ the owner — otherwise a run that really finished would report ``canceled``.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+ declined: list[bool] = []
+
+ async def _terminal_then_stop(controller, context, _message) -> None:
+ session_key = controller._get_session_key(context)
+ # The real terminal emit: stamp the honest settlement and release the waiter.
+ sink = controller.active_turn_sinks[session_key]
+ sink["settled_by"] = SETTLED_BY_TERMINAL_RESULT
+ sink["done_event"].set()
+ # The stop fallback fires afterwards and must be a no-op.
+ settler = _StopSinkSettler(controller)
+ binding = settler.bind_context_to_turn_sink(context)
+ declined.append(settler.settle_bound_turn_sink(binding) is False)
+ assert sink["settled_by"] == SETTLED_BY_TERMINAL_RESULT
+
+ controller = _SettlementControllerDouble(on_turn=_terminal_then_stop)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, request.id)
+
+ assert declined == [True], "a stop after the result landed must not re-settle the sink"
+ still_open = request_store.get_run(request.id)
+ assert still_open is not None
+ assert still_open["status"] == "running", "the terminal result's own writer owns this row"
+ assert still_open["metadata"].get("interrupt_reason") is None
+
+
+def test_late_terminal_result_cannot_reopen_a_stopped_run(tmp_path: Path, monkeypatch) -> None:
+ """The lossy half of the stop race, pinned as deliberate precedence.
+
+ If the backend's terminal result lands only AFTER the stop was acknowledged and
+ the run settled, the terminal write loses — both writers are scoped to
+ ``queued|running``. The row stays ``canceled``, which is still true of a run the
+ user stopped, and the late text is still appended to the run's outputs rather
+ than dropped. Pinned so a future change to either writer's guard is a visible
+ test failure, not a silent flip in who wins.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+
+ async def _stop_mid_turn(controller, context, _message) -> None:
+ settler = _StopSinkSettler(controller)
+ assert settler.settle_bound_turn_sink(settler.bind_context_to_turn_sink(context)) is True
+
+ controller = _SettlementControllerDouble(on_turn=_stop_mid_turn)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, request.id)
+ assert request_store.get_run(request.id)["status"] == "canceled"
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ recorded = sqlite_store.record_run_output(
+ request.id,
+ output_id="late-terminal",
+ text="the answer that arrived too late",
+ terminal_status="succeeded",
+ )
+
+ assert recorded["recorded"] is True, "the late text is still appended, not dropped"
+ assert recorded["terminal_transition"] is False, "but it must not re-terminalize the row"
+ final = request_store.get_run(request.id)
+ assert final is not None
+ assert final["status"] == "canceled", "a stop already settled this run; the late result loses"
+ assert final["metadata"]["interrupt_reason"] == "stopped"
+
+
+# ---------------------------------------------------------------------------
+# Gap B: the staleness sweep (docs/plans/agent-run-zombie-settlement.md §4)
+#
+# Gap A settles a run whose turn REPORTED that it produced nothing. These cases
+# cover the runs nobody will ever report on: the owner vanished without reporting,
+# the transport never came back, the queue gate never reopened. The sweep is the
+# only thing that can close them, which also makes it the only thing that can
+# WRONGLY close a healthy run — so the negative cases matter as much as the positive.
+#
+# Note on staging: ``ScheduledTaskService.__init__`` runs ``recover_processing()``,
+# which requeues every ``running`` row (that is how a restart's in-flight runs get
+# retried, and why the orphan class here is about owners lost WITHIN a live process).
+# So these tests build the service first and stage the stale row afterwards.
+# ---------------------------------------------------------------------------
+
+
+class _SweepControllerDouble:
+ """The controller surface the sweep reads: timing knobs plus the ownership lane.
+
+ ``session_turns`` is injectable so a test can supply the real
+ ``SessionTurnManager`` (the workbench ownership lane) or a broken provider (the
+ fail-closed case) rather than a hand-written answer.
+ """
+
+ def __init__(self, *, session_turns: Any = None, transport_ready: bool = True, **timings) -> None:
+ runtime = {
+ "harness_run_sweep_interval_seconds": 60,
+ "harness_run_orphan_grace_seconds": 120,
+ "harness_run_queued_ttl_seconds": 1800,
+ "harness_run_hold_ttl_seconds": 3600,
+ }
+ runtime.update(timings)
+ self.config = SimpleNamespace(language="en", runtime=SimpleNamespace(**runtime))
+ self.session_turns = SessionTurnManager(self) if session_turns is None else session_turns
+ self._transport_ready = transport_ready
+
+ def is_im_transport_ready(self, _platform: str) -> bool:
+ return self._transport_ready
+
+
+def _sweep_service(
+ tmp_path: Path,
+ request_store: TaskExecutionStore,
+ controller: Any = None,
+) -> ScheduledTaskService:
+ return ScheduledTaskService(
+ controller=controller if controller is not None else _SweepControllerDouble(),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+
+def _ago(seconds: int) -> str:
+ return (datetime.now(timezone.utc) - timedelta(seconds=seconds)).isoformat()
+
+
+def _force_run_columns(request_store: TaskExecutionStore, run_id: str, **columns) -> None:
+ """Write raw ``agent_runs`` columns to stage a state that takes real time to reach.
+
+ Aging a row by hand is the only way to exercise a TTL without sleeping through
+ it, and the sweep classifies purely on stored columns, so a staged row is
+ indistinguishable from one that got there naturally.
+ """
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ with sqlite_store.engine.begin() as conn:
+ conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**columns))
+
+
+def _stage_orphan_run(
+ request_store: TaskExecutionStore,
+ *,
+ message: str = "summarize the build",
+ age_seconds: int = 900,
+) -> str:
+ """A ``running`` agent run whose executor is gone — the post-restart zombie."""
+
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message=message,
+ agent_name="codex",
+ )
+ _force_run_columns(
+ request_store,
+ request.id,
+ status="running",
+ started_at=_ago(age_seconds),
+ created_at=_ago(age_seconds),
+ )
+ return request.id
+
+
+def test_sweep_terminalizes_orphaned_running_run(tmp_path: Path, monkeypatch) -> None:
+ """HFR-013: a ``running`` row with no live owner is the zombie Gap A cannot reach.
+
+ Gap A only fires when a turn in this process reports back. A turn that was taken
+ over out of band and then lost — no sink, no execution task, no settlement — never
+ reports, so without the sweep the row stays ``running`` forever: it blocks its
+ session, shows as active in the UI, and never notifies anyone.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = _stage_orphan_run(request_store)
+
+ service._sweep_stale_runs()
+
+ swept = request_store.get_run(run_id)
+ assert swept is not None
+ assert swept["status"] == "failed"
+ assert swept["completed_at"] is not None
+ assert swept["metadata"]["interrupt_reason"] == "orphaned"
+ # The resolved translation, not a raw dotted key: this column is shown verbatim
+ # in the Runs UI and in the callback message.
+ assert "Avibe Harness" in swept["error"]
+ assert "harness.run.interrupted" not in swept["error"]
+
+
+def test_sweep_respects_the_orphan_grace_period(tmp_path: Path, monkeypatch) -> None:
+ """A run that just started has no owner YET; the grace period is what protects it.
+
+ Ownership registration and the run row are written by different steps, so a
+ freshly claimed run is briefly visible as unowned. Sweeping on that window would
+ fail healthy runs at the moment they start.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = _stage_orphan_run(request_store, age_seconds=5)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "running"
+
+
+def test_sweep_skips_running_run_owned_by_inflight_execution(tmp_path: Path, monkeypatch) -> None:
+ """The drain lane: a claimed request whose execution task is still alive.
+
+ A hung backend looks exactly like an orphan in the database. The difference is
+ only visible in memory, and terminalizing it here would settle a run that is
+ still streaming — and then the real result would have nowhere to land.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = _stage_orphan_run(request_store)
+ # Only membership is read; a real ``asyncio.Task`` would need a running loop.
+ service._inflight_executions[run_id] = Mock(name="live-execution-task")
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "running"
+
+
+def test_sweep_skips_running_run_owned_by_workbench_turn(tmp_path: Path, monkeypatch) -> None:
+ """HFR-014: the second ownership lane, and the trap: it never enters ``_inflight_executions``.
+
+ A workbench/web turn takes the run over out of band, so the drain lane knows
+ nothing about it. A sweep that consulted only ``_inflight_executions`` would look
+ correct in every drain-lane test and still fail live workbench runs. Uses the real
+ ``register_turn_sink`` so the attribution path itself is under test.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ session_turns = SessionTurnManager(controller=None)
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(session_turns=session_turns)
+ )
+ run_id = _stage_orphan_run(request_store)
+ sibling_id = _stage_orphan_run(request_store, message="and the sibling callback")
+
+ context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_execution_id": run_id,
+ # A coalesced turn settles several runs; it owns every one of them, not
+ # just the primary, or the sweep fails the siblings out from under it.
+ "coalesced_queue": {"execution_ids": [sibling_id]},
+ },
+ )
+ session_turns.register_turn_sink(
+ "slack::channel::C123",
+ on_chunk=AsyncMock(),
+ done_event=asyncio.Event(),
+ context=context,
+ )
+ assert service._inflight_executions == {}, "the workbench lane registers nothing here"
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "running"
+ assert request_store.get_run(sibling_id)["status"] == "running"
+
+
+ "session_turns",
+ [
+ pytest.param(SimpleNamespace(), id="provider-missing"),
+ pytest.param(
+ SimpleNamespace(owned_agent_run_ids=Mock(side_effect=RuntimeError("turn state gone"))),
+ id="provider-raises",
+ ),
+ ],
+)
+def test_sweep_fails_closed_when_ownership_is_unknown(
+ tmp_path: Path, monkeypatch, session_turns: Any
+) -> None:
+ """HFR-015: "Nobody owns this run" and "I cannot tell" are opposite answers.
+
+ Both failures degrade to an empty owner set, which reads as "sweep everything".
+ The sweep must refuse to run instead: leaving a zombie for one more interval is
+ recoverable, failing every live run is not.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(session_turns=session_turns)
+ )
+ run_id = _stage_orphan_run(request_store)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "running"
+
+
+def _stage_queued_run(
+ request_store: TaskExecutionStore,
+ *,
+ metadata: Optional[dict] = None,
+ created_age_seconds: int = 0,
+ updated_age_seconds: Optional[int] = None,
+) -> str:
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ )
+ columns: dict[str, Any] = {}
+ if created_age_seconds:
+ columns["created_at"] = _ago(created_age_seconds)
+ if updated_age_seconds is not None:
+ columns["updated_at"] = _ago(updated_age_seconds)
+ if metadata is not None:
+ existing = request_store.get_run(request.id)["metadata"] or {}
+ columns["metadata_json"] = json.dumps({**existing, **metadata})
+ if columns:
+ _force_run_columns(request_store, request.id, **columns)
+ return request.id
+
+
+def test_sweep_terminalizes_queued_run_stranded_by_a_dead_transport(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-016: a queued run whose platform never reconnected is undeliverable, not pending.
+
+ Left alone it waits forever with no user-visible explanation. Two independent facts
+ have to agree before it is failed: the reason the drain recorded, and a live check
+ saying the platform is *still* undeliverable. Here both hold.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(1900)},
+ created_age_seconds=1900,
+ )
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(transport_ready=False)
+ )
+
+ service._sweep_stale_runs()
+
+ swept = request_store.get_run(run_id)
+ assert swept["status"] == "failed"
+ assert swept["metadata"]["interrupt_reason"] == "transport_unavailable"
+ assert "Avibe Harness" in swept["error"]
+
+
+def test_sweep_spares_a_stale_transport_stamp_once_the_platform_is_back(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-021: the recorded reason alone must not fail a run that is deliverable now.
+
+ The drain ``break``s at its concurrency cap without examining the rest of the
+ queue, so a row below the cut keeps its old ``transport_unavailable`` stamp long
+ after its platform reconnected — nothing re-derives it. Sweeping on the stamp
+ alone would fail a run that is merely waiting for a free slot (Codex P1). The live
+ second opinion is what distinguishes the two.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(1900)},
+ created_age_seconds=1900,
+ )
+ # transport_ready=True: Slack is back. The drain cannot say so, because it is at
+ # capacity and never reaches this row to refresh the stamp.
+ service = _sweep_service(tmp_path, request_store)
+ for index in range(service._MAX_CONCURRENT_EXECUTIONS):
+ service._inflight_executions[f"busy{index:08d}"] = Mock(name="live-execution-task")
+
+ asyncio.run(service._drain_requests())
+ assert (
+ request_store.get_run(run_id)["metadata"]["last_skip_reason"] == "transport_unavailable"
+ ), "the stale stamp survives, which is exactly why the sweep needs a second opinion"
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued"
+
+
+def test_sweep_grants_a_second_outage_its_own_ttl_after_a_recovery(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-033: proven recovery retires the evidence, so the NEXT outage ages from itself.
+
+ Deliverability only exempts a row while the transport is up. Since the drain
+ ``break``s at its concurrency cap it never re-stamps a row below the cut, so a stale
+ ``last_skip_at`` survived the recovery — and the moment the platform dropped again
+ the sweep read one continuous outage and failed the run instantly, skipping the whole
+ configured reconnect window (Codex P2). Observing the recovery is the only chance to
+ retire it, so the sweep does that when it sees both halves of the evidence disagree.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(1900)},
+ created_age_seconds=1900,
+ )
+ # Slack is back, and the drain is at capacity so it can never say so itself.
+ controller = _SweepControllerDouble()
+ service = _sweep_service(tmp_path, request_store, controller)
+ for index in range(service._MAX_CONCURRENT_EXECUTIONS):
+ service._inflight_executions[f"busy{index:08d}"] = Mock(name="live-execution-task")
+
+ service._sweep_stale_runs()
+
+ recovered = request_store.get_run(run_id)
+ assert recovered["status"] == "queued", "deliverable => never swept (HFR-021)"
+ assert "last_skip_reason" not in (recovered["metadata"] or {}), "the ended outage is forgotten"
+ assert "last_skip_at" not in (recovered["metadata"] or {})
+
+ # A NEW outage, recorded by the drain now that a slot is free.
+ service._inflight_executions.clear()
+ controller._transport_ready = False
+ asyncio.run(service._drain_requests())
+ restamped = request_store.get_run(run_id)["metadata"]
+ assert restamped["last_skip_reason"] == "transport_unavailable"
+
+ service._last_sweep_at = None # the rate limiter is not what is under test
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued", (
+ "the second outage gets its own full TTL, not the first one's leftover age"
+ )
+
+
+def test_sweep_ages_a_transport_failure_from_when_it_started(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-024: the TTL is a reconnect window, so it runs from the outage, not the enqueue.
+
+ A run can legitimately sit in ``queued`` far longer than the TTL for reasons that
+ are progress — capacity, a busy session. If its transport then blinks, aging from
+ ``created_at`` would make it sweepable on the very next tick and skip the entire
+ configured reconnect window. ``last_skip_at`` is when the reason started (the stamp
+ is transition-triggered), which is the only clock that means "how long has this been
+ undeliverable".
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ # Two hours in the queue, but the transport only just went down.
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(30)},
+ created_age_seconds=7200,
+ )
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(transport_ready=False)
+ )
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued"
+
+
+def test_sweep_never_terminalizes_a_transport_reason_with_no_timestamp(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-025: a reason without its timestamp is unrecognized evidence, not old evidence.
+
+ ``record_run_skip_reason`` writes the reason and ``last_skip_at`` in one statement,
+ so a row carrying one without the other did not come from that writer. Falling back
+ to ``created_at`` there would quietly reintroduce the bug HFR-024 pins, so the row is
+ left alone instead.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable"},
+ created_age_seconds=7200,
+ )
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(transport_ready=False)
+ )
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued"
+
+
+def test_sweep_skips_transport_class_when_deliverability_is_unknown(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-022: if the live deliverability check breaks, the whole class is disabled.
+
+ Same fail-closed posture as unknown ownership: a sweep that cannot prove a run is
+ undeliverable must not fail it. The other classes keep working — only the transport
+ class is suppressed for this tick.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(1900)},
+ created_age_seconds=1900,
+ )
+ controller = _SweepControllerDouble(transport_ready=False)
+ service = _sweep_service(tmp_path, request_store, controller)
+ orphan_id = _stage_orphan_run(request_store)
+
+ def _broken(_platform: str) -> bool:
+ raise RuntimeError("transport registry unavailable")
+
+ controller.is_im_transport_ready = _broken
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued", "unprovable => untouched"
+ assert request_store.get_run(orphan_id)["status"] == "failed", "other classes still sweep"
+
+
+def test_sweep_leaves_a_queued_run_whose_session_is_merely_busy(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-017: ``session_busy`` is progress, and it must be able to clear a stale transport reason.
+
+ A run blocked behind its own session's active turn will run the moment that turn
+ ends. Without the drain overwriting the older ``transport_unavailable`` reason, an
+ aged row that is now making progress would still read as sweepable.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(
+ request_store,
+ metadata={"last_skip_reason": "transport_unavailable", "last_skip_at": _ago(1900)},
+ created_age_seconds=1900,
+ )
+ service = _sweep_service(tmp_path, request_store)
+ # The session is busy: a turn for this conversation holds the lock.
+ lock_key = service._execution_lock_key(request_store.list_pending()[0])
+ assert lock_key is not None
+ service._inflight_sessions.add(lock_key)
+ service._session_lock_owners[lock_key] = "otherrun0001"
+ service._inflight_executions["otherrun0001"] = Mock(name="live-execution-task")
+
+ asyncio.run(service._drain_requests())
+ assert request_store.get_run(run_id)["metadata"]["last_skip_reason"] == "session_busy"
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued"
+
+
+def test_sweep_ignores_queued_run_skipped_only_for_capacity(tmp_path: Path, monkeypatch) -> None:
+ """A row the drain never even looked at must never be swept.
+
+ At capacity the drain ``break``s without examining the rest of the queue, so those
+ rows carry no skip reason. Requiring recorded evidence is what makes that silence
+ safe — a busy service must not look like a broken one.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(request_store, created_age_seconds=7200)
+ service = _sweep_service(tmp_path, request_store)
+ for index in range(service._MAX_CONCURRENT_EXECUTIONS):
+ service._inflight_executions[f"busy{index:08d}"] = Mock(name="live-execution-task")
+
+ asyncio.run(service._drain_requests())
+ assert request_store.get_run(run_id)["metadata"].get("last_skip_reason") is None
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "queued"
+
+
+def test_sweep_expires_a_workbench_queue_hold_only_after_its_ttl(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The hold TTL is the longest one: a recovering queue must be allowed to recover.
+
+ A run holding a workbench queue slot is waiting on the session's turn queue, which
+ legitimately drains slowly. Only a hold nothing has touched for the full TTL is
+ treated as a gate that never reopened.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ recovering = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=1800
+ )
+ abandoned = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=7200
+ )
+ service = _sweep_service(tmp_path, request_store)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(recovering)["status"] == "queued"
+ expired = request_store.get_run(abandoned)
+ assert expired["status"] == "failed"
+ assert expired["metadata"]["interrupt_reason"] == "queue_hold_expired"
+
+
+def test_sweep_spares_an_aged_queue_hold_a_live_turn_still_owns(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-026: ownership outranks the queue TTLs too, not just the orphan grace.
+
+ A coalesced workbench turn deliberately leaves its secondary runs ``queued`` with
+ ``workbench_queue_holds_run`` while the primary settles them, and reports every one
+ of them from ``owned_agent_run_ids``. A hold TTL that ignored ownership would fail
+ those live siblings the moment the turn outran it — a turn-duration timeout by the
+ back door, which this design explicitly does not have. The control row proves the
+ class still works: same age, same flag, no owner.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ session_turns = SessionTurnManager(controller=None)
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(session_turns=session_turns)
+ )
+ primary = _stage_orphan_run(request_store)
+ held = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=7200
+ )
+ unowned = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=7200
+ )
+
+ session_turns.register_turn_sink(
+ "slack::channel::C123",
+ on_chunk=AsyncMock(),
+ done_event=asyncio.Event(),
+ context=MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_execution_id": primary,
+ "coalesced_queue": {"execution_ids": [held]},
+ },
+ ),
+ )
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(held)["status"] == "queued"
+ assert request_store.get_run(unowned)["status"] == "failed"
+
+
+def test_workbench_turn_settles_its_agent_run_when_no_result_arrives(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-027: on the gate lane the TURN settles the run, because the harness cannot.
+
+ ``_execute_agent_run`` hands an avibe-targeted run to
+ ``session_turn_gate.submit_scheduled`` and returns while the turn is still
+ running, so the outcome that turn eventually produces is never seen there. When
+ the turn ends without a terminal result — a stop the backend answered without
+ emitting one — the turn lane is the only place left that can settle the row.
+ Without this the run stays ``running`` until the sweep relabels it ``orphaned``,
+ or forever when the sweep is disabled. A coalesced turn settles every id it owns.
+ """
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ primary = request_store.enqueue_agent_run(
+ session_id=session_id, message="stop me", agent_name="codex"
+ ).id
+ sibling = request_store.enqueue_agent_run(
+ session_id=session_id, message="and the coalesced sibling", agent_name="codex"
+ ).id
+ for run_id in (primary, sibling):
+ _force_run_columns(request_store, run_id, status="running", started_at=_ago(30))
+
+ async def _stopped_without_result(_controller, _context, _text, **_kwargs):
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_STOPPED)
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _stopped_without_result)
+
+ manager = SessionTurnManager(controller=None)
+ manager.controller = SimpleNamespace(
+ scheduled_task_service=service,
+ session_turns=manager,
+ set_agent_status=lambda *_args, **_kwargs: None,
+ _get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",
+ )
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "task_execution_id": primary,
+ "task_trigger_kind": "agent_run",
+ "coalesced_queue": {"execution_ids": [sibling]},
+ },
+ )
+
+ async def _exercise() -> None:
+ assert await manager.submit(session_id, context, "stop me", source=SOURCE_SCHEDULED) == "ran"
+ for _ in range(400):
+ if request_store.get_run(primary)["status"] != "running":
+ break
+ await asyncio.sleep(0.005)
+
+ asyncio.run(_exercise())
+
+ for run_id in (primary, sibling):
+ settled = request_store.get_run(run_id)
+ # ``stopped`` is user intent, so ``canceled`` — not ``failed`` — is the honest
+ # terminal, exactly as on the drain lane (HFR-012).
+ assert settled["status"] == "canceled", run_id
+ assert settled["metadata"]["interrupt_reason"] == "stopped", run_id
+ assert settled["error"], run_id
+
+
+def test_backend_refresh_settles_its_run_as_a_refresh_not_a_user_stop(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-029: a runtime refresh is not a user Stop, and must not be reported as one.
+
+ ``release_for_backend_refresh`` cancels every in-flight turn of a backend whose
+ cached process state is about to disappear — which is what an ``agents.*`` save's
+ rolling reconciliation does. That arrives in ``_run`` as a bare
+ ``CancelledError``, indistinguishable from the Stop button unless the canceller
+ says so. Reading every cancellation as a stop made a run killed by routine
+ configuration reconciliation settle ``canceled`` with the user-stop explanation,
+ so the callback told the user they had stopped a run they never touched and the
+ failure accounting saw deliberate intent instead of an infrastructure fault.
+ """
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = request_store.enqueue_agent_run(
+ session_id=session_id, message="interrupted by a config save", agent_name="codex"
+ ).id
+ _force_run_columns(request_store, run_id, status="running", started_at=_ago(30))
+
+ dispatch_started = asyncio.Event()
+
+ async def _never_returns(_controller, _context, _text, **_kwargs):
+ dispatch_started.set()
+ await asyncio.Event().wait() # held open until the refresh cancels the turn
+ raise AssertionError("unreachable")
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _never_returns)
+
+ manager = SessionTurnManager(controller=None)
+ manager.controller = SimpleNamespace(
+ scheduled_task_service=service,
+ session_turns=manager,
+ set_agent_status=lambda *_args, **_kwargs: None,
+ _get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",
+ )
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "task_execution_id": run_id,
+ "task_trigger_kind": "agent_run",
+ "agent_session_target": {"agent_backend": "codex"},
+ },
+ )
+
+ async def _exercise() -> None:
+ assert (
+ await manager.submit(session_id, context, "interrupted by a config save", source=SOURCE_SCHEDULED)
+ == "ran"
+ )
+ await asyncio.wait_for(dispatch_started.wait(), timeout=5)
+ released = await manager.release_for_backend_refresh(
+ backend="codex", base_session_ids={session_id}
+ )
+ assert released == 1
+ for _ in range(400):
+ if request_store.get_run(run_id)["status"] != "running":
+ break
+ await asyncio.sleep(0.005)
+
+ asyncio.run(_exercise())
+
+ settled = request_store.get_run(run_id)
+ # An infrastructure fault with no user intent behind it, so ``failed`` — it stays
+ # visible to a failure counter — and the reason names the refresh, not a stop.
+ assert settled["status"] == "failed"
+ assert settled["metadata"]["interrupt_reason"] == SETTLED_BY_BACKEND_REFRESH
+ assert settled["error"]
+ assert "stop" not in settled["error"].lower()
+
+
+def test_turn_only_result_leaves_an_activity_owned_run_alone(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-031: "the turn ended" is not "the run ended" — leave a run somebody still owns.
+
+ The Claude Activity delivery-failure path closes its origin turn with a silent
+ terminal ``result`` carrying ``completes_run=False`` while the REQUEUED Activity
+ keeps the run and retries. That release stamps ``turn_only_result``, which is
+ deliberately NOT in ``SETTLEMENTS_WITHOUT_RESULT``: settling here would fail a
+ live Activity-owned run and fire its terminal callback before the retry ran.
+ Both lanes therefore allow-list the settlements that mean "no result is coming"
+ instead of treating everything but ``terminal_result`` as a zombie.
+ """
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = request_store.enqueue_agent_run(
+ session_id=session_id, message="delivery failed, activity requeued", agent_name="claude"
+ ).id
+ _force_run_columns(request_store, run_id, status="running", started_at=_ago(30))
+
+ async def _turn_closed_run_kept(_controller, _context, _text, **_kwargs):
+ return TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TURN_ONLY_RESULT)
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _turn_closed_run_kept)
+
+ manager = SessionTurnManager(controller=None)
+ manager.controller = SimpleNamespace(
+ scheduled_task_service=service,
+ session_turns=manager,
+ set_agent_status=lambda *_args, **_kwargs: None,
+ _get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",
+ )
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={
+ "task_execution_id": run_id,
+ "task_trigger_kind": "agent_run",
+ },
+ )
+
+ async def _exercise() -> None:
+ assert (
+ await manager.submit(
+ session_id, context, "delivery failed, activity requeued", source=SOURCE_SCHEDULED
+ )
+ == "ran"
+ )
+ for _ in range(400):
+ if session_id not in manager.in_flight:
+ break
+ await asyncio.sleep(0.005)
+ assert session_id not in manager.in_flight
+
+ asyncio.run(_exercise())
+
+ kept = request_store.get_run(run_id)
+ # Still owned, still running: the retry gets to write the honest terminal state.
+ assert kept["status"] == "running"
+ assert not (kept["metadata"] or {}).get("interrupt_reason")
+ assert not kept["error"]
+
+
+def test_sweep_skips_hold_class_when_live_session_turns_are_unknown(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-035: an unanswerable "is this session busy?" disables the hold class.
+
+ Same fail-closed posture as ownership and deliverability: "no session is busy" and
+ "I could not look" are opposite answers, and acting on the second fails a run the
+ gate is about to flush. Only the hold class is suppressed for this tick.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ manager = SessionTurnManager(controller=None)
+
+ def _broken() -> set[str]:
+ raise RuntimeError("turn manager unavailable")
+
+ manager.busy_session_ids = _broken
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(session_turns=manager)
+ )
+ held = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=7200
+ )
+ orphan_id = _stage_orphan_run(request_store)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(held)["status"] == "queued", "unprovable => untouched"
+ assert request_store.get_run(orphan_id)["status"] == "failed", "other classes still sweep"
+
+
+def test_sweep_spares_a_hold_parked_behind_a_live_session_turn(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-034: a hold with a live turn to wait for is not abandoned (Codex P2).
+
+ The gate answers ``enqueued`` when a run arrives at a session that already has a
+ turn in flight, and the run is requeued with ``workbench_queue_holds_run``. Nobody
+ reports it as owned — the live turn owns only the ids it is executing itself — so a
+ legitimate Workbench turn outliving ``harness_run_hold_ttl_seconds`` had its own
+ queued follower failed underneath it, even though ``flush_queue`` would have picked
+ it up on completion. Ownership cannot express this; live session occupancy can. The
+ control row proves the class still works: same flag, same age, no live turn.
+ """
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ manager = SessionTurnManager(controller=None)
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(session_turns=manager)
+ )
+ manager.controller = SimpleNamespace(
+ scheduled_task_service=service,
+ session_turns=manager,
+ set_agent_status=lambda *_args, **_kwargs: None,
+ _get_session_key=lambda ctx: f"avibe::{ctx.channel_id}",
+ )
+ live = request_store.enqueue_agent_run(
+ session_id=session_id, message="the long legitimate turn", agent_name="codex"
+ ).id
+ _force_run_columns(request_store, live, status="running", started_at=_ago(30))
+ held = request_store.enqueue_agent_run(
+ session_id=session_id, message="parked behind that turn", agent_name="codex"
+ ).id
+ _force_run_columns(
+ request_store,
+ held,
+ updated_at=_ago(7200),
+ metadata_json=json.dumps({"workbench_queue_holds_run": True}),
+ )
+ abandoned = _stage_queued_run(
+ request_store, metadata={"workbench_queue_holds_run": True}, updated_age_seconds=7200
+ )
+
+ dispatch_started = asyncio.Event()
+
+ async def _never_returns(_controller, _context, _text, **_kwargs):
+ dispatch_started.set()
+ await asyncio.Event().wait() # the long turn, still going
+ raise AssertionError("unreachable")
+
+ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", _never_returns)
+
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={"task_execution_id": live, "task_trigger_kind": "agent_run"},
+ )
+
+ async def _exercise() -> None:
+ assert (
+ await manager.submit(
+ session_id, context, "the long legitimate turn", source=SOURCE_SCHEDULED
+ )
+ == "ran"
+ )
+ await asyncio.wait_for(dispatch_started.wait(), timeout=5)
+ assert manager.busy_session_ids() == {session_id}
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(held)["status"] == "queued", "the gate will flush it"
+ assert request_store.get_run(live)["status"] == "running", "owned, so never swept"
+ assert request_store.get_run(abandoned)["status"] == "failed", "no live turn => abandoned"
+
+ turn = manager.in_flight.get(session_id)
+ assert turn is not None
+ turn.task.cancel()
+ with suppress(asyncio.CancelledError):
+ await turn.task
+
+ asyncio.run(_exercise())
+
+
+def test_sweep_retires_the_queue_segment_of_the_run_it_expired(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-028: terminalizing the row is not enough — the queued segment must go too.
+
+ ``recover_persisted_agent_run_queue`` ignores references whose run is no longer
+ ``queued``, so a swept run's persisted ``messages`` row is nobody's to reclaim: the
+ Session keeps showing stale pending input until an unrelated user send happens to
+ force ``flush_queue`` to retire it. The sweep already knows the session, so it
+ reconciles immediately.
+ """
+
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ held = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message="held behind a gate that never reopened",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ ).id
+ _force_run_columns(request_store, held, updated_at=_ago(7200))
+ 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="held behind a gate that never reopened",
+ native_message_id=f"agent_run:{held}",
+ )
+ assert len(messages_service.list_queued(conn, session_id)) == 1
+ service = _sweep_service(tmp_path, request_store)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(held)["metadata"]["interrupt_reason"] == "queue_hold_expired"
+ with create_sqlite_engine().connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+
+
+def test_sweep_leaves_watch_runtime_and_deferred_rows_alone(tmp_path: Path, monkeypatch) -> None:
+ """Two row classes look stale and are not: neither is ours to settle.
+
+ ``watch_runtime`` is a singleton bookkeeping row that is ``running`` by design, and
+ a deferred terminal belongs to the Activity lifecycle. Terminalizing either would
+ corrupt state the sweep does not own.
+
+ Both are defended twice on purpose. Mutation testing shows the deferred row
+ survives even with the sweep's own candidate check removed, because
+ ``settle_run_terminal`` refuses a deferred row as well — so read the candidate
+ check as belt-and-braces, not as the load-bearing guard. The watch_runtime row
+ needs both the query filter and the ``agent_run`` restriction gone before it is
+ touched.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ watch_runtime = _stage_orphan_run(request_store, message="watch runtime bookkeeping")
+ _force_run_columns(request_store, watch_runtime, run_type="watch_runtime")
+ deferred = _stage_orphan_run(request_store, message="activity-owned run")
+ _force_run_columns(
+ request_store,
+ deferred,
+ result_payload_json=json.dumps({"deferred_terminal_status": "succeeded"}),
+ )
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(watch_runtime)["status"] == "running"
+ assert request_store.get_run(deferred)["status"] == "running"
+
+
+def test_sweep_releases_a_leaked_session_lock(tmp_path: Path, monkeypatch) -> None:
+ """HFR-018: an honest row is only half the repair; the wedge is in memory.
+
+ ``_inflight_sessions`` gates dispatch for the whole conversation, so a lock that
+ outlived its execution keeps the session undispatchable no matter how the run row
+ reads. A lock a LIVE execution holds must survive the same pass — freeing that one
+ would let two turns run at once in one session.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ service._inflight_sessions.update({"key:leaked", "key:live"})
+ service._session_lock_owners.update({"key:leaked": "deadrun00001", "key:live": "liverun00001"})
+ service._inflight_executions["liverun00001"] = Mock(name="live-execution-task")
+ service._drain_dirty = False
+
+ service._sweep_stale_runs()
+
+ assert service._inflight_sessions == {"key:live"}
+ assert service._session_lock_owners == {"key:live": "liverun00001"}
+ assert service._drain_dirty is True, "the freed session must be re-checked immediately"
+
+
+def test_execution_completion_does_not_steal_a_later_lock_owner(tmp_path: Path, monkeypatch) -> None:
+ """HFR-019: the owner map must not be clobbered by a finishing predecessor.
+
+ Two executions can reuse one lock key in sequence. If the first one's completion
+ callback removed the owner entry the second one wrote, the sweep would read the
+ live lock as leaked and free it mid-turn.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ service._inflight_sessions.add("key:shared")
+ service._session_lock_owners["key:shared"] = "secondrun001"
+ service._inflight_executions["secondrun001"] = Mock(name="live-execution-task")
+
+ service._on_execution_done("firstrun0001", "key:shared", Mock(cancelled=lambda: True))
+
+ assert service._session_lock_owners == {"key:shared": "secondrun001"}
+ service._sweep_stale_runs()
+ assert service._session_lock_owners == {"key:shared": "secondrun001"}
+
+
+def test_stranded_queued_run_does_not_trigger_repeated_metadata_writes(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-020: the skip stamp must be transition-only, or it becomes a self-feeding hot loop.
+
+ Every write bumps the store's invalidation probe, which is what wakes the drain —
+ so a per-tick stamp would make a permanently-down transport spin the service
+ forever. It must also leave ``updated_at`` alone: the hold TTL reads that column,
+ and bumping it would keep any hold permanently fresh.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ run_id = _stage_queued_run(request_store)
+ before = request_store.get_run(run_id)["updated_at"]
+ service = _sweep_service(tmp_path, request_store, _SweepControllerDouble(transport_ready=False))
+
+ wrote: list[bool] = []
+ original = request_store.record_skip_reason
+
+ def _record(target_id: str, *, reason: str) -> bool:
+ result = original(target_id, reason=reason)
+ wrote.append(result)
+ return result
+
+ monkeypatch.setattr(request_store, "record_skip_reason", _record)
+
+ for _ in range(4):
+ asyncio.run(service._drain_requests())
+
+ assert wrote == [True, False, False, False], "the reason is stamped once, not once per tick"
+ after = request_store.get_run(run_id)
+ assert after["metadata"]["last_skip_reason"] == "transport_unavailable"
+ assert after["updated_at"] == before, "stamping a skip must not refresh the hold TTL"
+
+
+def test_swept_run_notifies_the_session_that_launched_it(tmp_path: Path, monkeypatch) -> None:
+ """An honest row nobody is told about is still a silent failure.
+
+ A delegated run (``vibe agent run``) reports back to its caller's session when it
+ reaches a terminal state. The sweep goes through the same guarded writer, so the
+ callback becomes owed automatically — this pins that, because the whole point of
+ settling a zombie is that the waiting side stops waiting.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="summarize the build",
+ agent_name="codex",
+ callback_session_id="ses_parent",
+ )
+ _force_run_columns(
+ request_store, request.id, status="running", started_at=_ago(900), created_at=_ago(900)
+ )
+ assert request_store.list_pending_callbacks() == [], "nothing is owed while it runs"
+
+ service._sweep_stale_runs()
+
+ owed = request_store.list_pending_callbacks()
+ assert [run["id"] for run in owed] == [request.id]
+ assert owed[0]["status"] == "failed"
+ assert owed[0]["callback_session_id"] == "ses_parent"
+
+
+def test_sweep_publishes_a_run_update_event(tmp_path: Path, monkeypatch) -> None:
+ """The Runs UI is SSE-driven, so a swept row must announce itself.
+
+ Without the event the run keeps rendering as active until something else happens
+ to refresh, which looks exactly like the bug the sweep exists to fix.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core import inbox_events
+
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ run_id = _stage_orphan_run(request_store)
+
+ published: list[tuple[str, dict]] = []
+ # The bus is process-global and this subscription is not one-shot, so it has to be
+ # removed again or it leaks into every later test in this process.
+ sub_id = inbox_events.bus.subscribe_callback(
+ lambda event_type, data: published.append((event_type, data))
+ )
+ try:
+ service._sweep_stale_runs()
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+
+ assert published[-1][0] == "runs.updated"
+ assert published[-1][1]["run_id"] == run_id
+ assert published[-1][1]["status"] == "failed"
+
+
+def test_sweep_is_rate_limited_to_the_configured_interval(tmp_path: Path, monkeypatch) -> None:
+ """The sweep rides a 2 s tick, so its own interval is the only thing bounding cost.
+
+ Without the guard this becomes a full scan of every open run twice a second.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(tmp_path, request_store)
+ first = _stage_orphan_run(request_store)
+
+ service._sweep_stale_runs()
+ assert request_store.get_run(first)["status"] == "failed"
+
+ second = _stage_orphan_run(request_store, message="a later orphan")
+ service._sweep_stale_runs()
+ assert request_store.get_run(second)["status"] == "running", "still inside the interval"
+
+ # Rewind the last-sweep stamp instead of the clock: same effect, no time travel.
+ service._last_sweep_at -= 61
+ service._sweep_stale_runs()
+ assert request_store.get_run(second)["status"] == "failed"
+
+
+def test_sweep_is_disabled_by_a_zero_interval(tmp_path: Path, monkeypatch) -> None:
+ """A zero interval is the documented off switch — an operator must be able to stop it."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ service = _sweep_service(
+ tmp_path, request_store, _SweepControllerDouble(harness_run_sweep_interval_seconds=0)
+ )
+ run_id = _stage_orphan_run(request_store)
+
+ service._sweep_stale_runs()
+
+ assert request_store.get_run(run_id)["status"] == "running"
+
+
+def test_agent_run_with_blank_message_fails_instead_of_hanging(tmp_path: Path, monkeypatch) -> None:
+ """A whitespace-only prompt is rejected at the door instead of hanging.
+
+ ``MessageHandler`` returns early for a blank prompt without dispatching an agent,
+ so such a run could never receive a terminal result. A row enqueued before this
+ guard existed (bypassing ``enqueue_agent_run``) must still terminalize.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+
+ with pytest.raises(ValueError):
+ request_store.enqueue_agent_run(session_key="slack::channel::C123", message=" \n ")
+
+ legacy = request_store.enqueue(
+ TaskExecutionRequest(
+ id="blankrun0001",
+ request_type="agent_run",
+ session_key="slack::channel::C123",
+ message=" \n ",
+ prompt=" \n ",
+ source_kind="cli",
+ )
+ )
+ controller = _SettlementControllerDouble()
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ _run_single_request(service, legacy.id)
+
+ assert controller.turns == []
+ settled = request_store.get_run(legacy.id)
+ assert settled is not None
+ assert settled["status"] == "failed"
+ assert settled["completed_at"] is not None
+
+
+def test_duplicate_recovered_coalesced_agent_run_settles_held_children(tmp_path: Path, monkeypatch) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ run_ids: list[str] = []
+ for index in range(2):
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=f"coalesced prompt {index + 1}",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ run_ids.append(request.id)
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+ request_store.recover_processing()
+
+ async def _submit_scheduled(_sid, _ctx, _text):
+ return "duplicate"
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ return None
+
+ 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"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_requests())
+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
+
+ assert stored[run_ids[0]]["status"] == "succeeded"
+ 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(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ run_ids: list[str] = []
+ for index in range(3):
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=f"coalesced prompt {index + 1}",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ run_ids.append(request.id)
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+
+ request_store.recover_processing()
+ pending = request_store.list_pending()
+
+ assert [request.id for request in pending] == [run_ids[0]]
+ assert pending[0].metadata["coalesced_queue"]["execution_ids"] == run_ids
+ assert _agent_run_message_for_request(pending[0]) == (
+ "coalesced prompt 1\n\n---\n\ncoalesced prompt 2\n\n---\n\ncoalesced prompt 3"
+ )
+
+
+def test_recovered_agent_run_retires_stale_queued_native_rows_before_gate(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ run_ids: list[str] = []
+ for index in range(2):
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=f"coalesced prompt {index + 1}",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ run_ids.append(request.id)
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+ request_store.recover_processing()
+
+ from storage import messages_service
+ from storage.models import agent_sessions, messages
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == session_id).limit(1)
+ ).mappings().first()
+ assert session is not None
+ scope_id = session["scope_id"]
+ for run_id in run_ids:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text=f"stale queued row for {run_id}",
+ native_message_id=f"agent_run:{run_id}",
+ )
+
+ submitted: list[str] = []
+
+ async def _submit_scheduled(_sid, ctx, text):
+ with engine.connect() as conn:
+ if messages_service.native_message_exists(
+ conn,
+ platform="avibe",
+ native_message_id=ctx.message_id,
+ ):
+ return "duplicate"
+ submitted.append(text)
+ return "ran"
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ return None
+
+ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ async def _exercise() -> None:
+ await service._drain_requests()
+ execution = service._inflight_executions.get(run_ids[0])
+ if execution is not None:
+ await execution
+
+ asyncio.run(_exercise())
+
+ assert len(submitted) == 1
+ assert "coalesced prompt 1" in submitted[0]
+ assert "coalesced prompt 2" in submitted[0]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ dedupe_rows = conn.execute(
+ select(messages.c.native_message_id, messages.c.type)
+ .where(messages.c.session_id == session_id)
+ .where(messages.c.type == messages_service.HARNESS_DEDUPE_TYPE)
+ ).all()
+ assert {row.native_message_id for row in dedupe_rows} == {f"agent_run:{run_ids[1]}"}
+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
+ assert stored[run_ids[0]]["status"] == "running"
+ assert stored[run_ids[1]]["status"] == "queued"
+
+
+def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path: Path, monkeypatch) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ run_ids: list[str] = []
+ for index in range(2):
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ message=f"coalesced prompt {index + 1}",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ run_ids.append(request.id)
+
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.claim_queued_runs_for_workbench(run_ids) == run_ids
+ request_store.recover_processing()
+ claimed = request_store.claim(run_ids[0])
+ assert claimed is not None
+
+ async def _submit_scheduled(_sid, _ctx, _text):
+ raise AssertionError("the direct execution path should be patched below")
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ return None
+
+ gate = SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={})
+ controller = _avibe_controller_double(gate=gate, handle_scheduled_message=_handle_scheduled_message)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ async def _raise_early(**_kwargs):
+ raise RuntimeError("target session vanished")
+
+ service._execute_agent_run = _raise_early
+
+ asyncio.run(service._execute_claimed_request(claimed))
+ stored = {run_id: request_store.get_run(run_id) for run_id in run_ids}
+
+ assert stored[run_ids[0]]["status"] == "failed"
+ assert stored[run_ids[1]]["status"] == "failed"
+ assert stored[run_ids[0]]["completed_at"] is not None
+ assert stored[run_ids[1]]["completed_at"] is not None
+ assert stored[run_ids[0]]["error"] == "target session vanished"
+ assert stored[run_ids[1]]["error"] == "target session vanished"
+
+
+def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="codex",
+ callback_session_id=caller_session_id,
+ )
+ request_store.complete(request, ok=True, session_id="target-session")
store = SQLiteBackgroundTaskStore()
try:
store.record_run_message(
@@ -4214,8 +5932,15 @@ def test_drain_requests_agent_run_passes_agent_name(tmp_path: Path) -> None:
assert context.channel_id == "C123"
assert context.message_id == f"agent_run:{request.id}"
assert context.platform_specific["vibe_agent_name"] == "release-reviewer"
- payload = json.loads((request_store.processing_dir / f"{request.id}.json").read_text(encoding="utf-8"))
+ # The fake handler releases the turn sink without emitting a terminal result, so
+ # no out-of-band writer will ever settle this run. The legacy file store has no
+ # guarded writer, so the run is completed here rather than left in ``processing``
+ # forever. See docs/plans/agent-run-zombie-settlement.md.
+ assert not (request_store.processing_dir / f"{request.id}.json").exists()
+ payload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))
assert payload["request_type"] == "agent_run"
+ assert payload["ok"] is False
+ assert "Agent producing a result" in payload["error"]
def test_run_task_request_does_not_disable_one_shot(tmp_path: Path) -> None:
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ffe7f1425..631e563de 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -30,6 +30,17 @@
"messagesLabel": "Coalesced callback messages:",
"latestLabel": "Latest callback message after {additional} additional trigger(s):",
"burstHint": "This callback source is firing frequently. Inspect the related watch/task and pause, remove, or update it if it is looping."
+ },
+ "run": {
+ "interrupted": {
+ "noTerminalResult": "[Avibe Harness] This run ended without the Agent producing a result. The turn was released before the Agent replied, so no output was recorded. Check the Agent logs, then run it again if the work still needs doing.",
+ "stopped": "[Avibe Harness] This run was stopped before the Agent produced a result, so it has no final result. Any output the Agent had already sent is still kept on the run.",
+ "refusedConcurrentTurn": "[Avibe Harness] This run was skipped because another turn was already in flight for the same session. A session runs one turn at a time; trigger it again once the current turn finishes.",
+ "backendRefresh": "[Avibe Harness] This run was interrupted because its Agent runtime was refreshed while the run was in flight, usually right after an Agent setting was saved. Nothing is wrong with the run itself — trigger it again.",
+ "orphaned": "[Avibe Harness] This run was left marked as running with nothing executing it, most likely because the service restarted while it was in flight. Any output it had already sent is still kept on the run. Run it again if the work still needs doing.",
+ "transportUnavailable": "[Avibe Harness] This run stayed queued because its chat platform never reconnected, so it was never delivered. Check the platform connection in Settings, then trigger it again.",
+ "queueHoldExpired": "[Avibe Harness] This run stayed queued behind its session's turn queue for too long and was never started. Check whether that session has a stuck turn, then trigger this run again."
+ }
}
},
"common": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index a617acb6f..fc253e1b8 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -30,6 +30,17 @@
"messagesLabel": "已合并的 callback 消息:",
"latestLabel": "后续又触发 {additional} 次后的最新 callback 消息:",
"burstHint": "这个 callback 来源正在频繁触发。请检查相关 watch/task;如果它在循环触发,请 pause、remove 或 update。"
+ },
+ "run": {
+ "interrupted": {
+ "noTerminalResult": "[Avibe Harness] 本次 run 结束时 Agent 没有产出结果。turn 在 Agent 回复前就被释放,因此没有记录任何输出。请检查 Agent 日志;如果这项工作仍需完成,请重新运行。",
+ "stopped": "[Avibe Harness] 本次 run 在 Agent 产出结果前被停止,因此没有最终结果。Agent 此前已经发出的输出仍会保留在这次 run 上。",
+ "refusedConcurrentTurn": "[Avibe Harness] 本次 run 被跳过:同一 session 已有另一个 turn 正在执行。一个 session 同时只运行一个 turn,请在当前 turn 结束后重新触发。",
+ "backendRefresh": "[Avibe Harness] 本次 run 执行途中,它所用的 Agent 运行时被刷新,因此被中断,通常发生在刚保存 Agent 设置之后。这次 run 本身没有问题,请重新触发。",
+ "orphaned": "[Avibe Harness] 本次 run 一直标记为 running,但已经没有任何执行在推进它,通常是服务在它执行途中重启导致的。它此前已经发出的输出仍会保留在这次 run 上。如果这项工作仍需完成,请重新运行。",
+ "transportUnavailable": "[Avibe Harness] 本次 run 一直排队等待,因为它对应的聊天平台始终没有重新连接,消息也就无法送达。请在设置中检查该平台连接,然后重新触发。",
+ "queueHoldExpired": "[Avibe Harness] 本次 run 在所属 session 的 turn 队列后面排队过久,始终没有开始执行。请检查该 session 是否有卡住的 turn,然后重新触发这次 run。"
+ }
}
},
"common": {