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): stop orphaning pinned sessions, harden reservation (#1064)

Qi Qi4397100f90ba
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index 1aa900506..6ca79fe2b 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -328,7 +328,11 @@ class SessionsStore:
self._ensure_service()
deleted = 0
for scope_key in scope_keys:
- deleted += self._service.delete_agent_sessions(scope_key=str(scope_key))
+ # Tearing down a scope that no longer exists: nothing survives it,
+ # including superseded rows, which would otherwise have no owner.
+ deleted += self._service.delete_agent_sessions(
+ scope_key=str(scope_key), include_superseded=True
+ )
return deleted
def _ensure_user_namespace(self, user_id: str) -> None:
@@ -489,23 +493,33 @@ class SessionsStore:
return max(removed, max(before - after, 0))
def clear_session_base(self, user_id: str, base_session_id: str) -> int:
+ """Clear a thread's sessions, keeping the local map equal to what SQL kept.
+
+ HFR-274. This used to hand-prune ``state.session_mappings`` by the same prefix
+ rule the SQL uses -- ``key == base or key.startswith(base + ':')`` -- which stopped
+ being the same rule when the delete grew its ``include_superseded=False`` guard
+ (HFR-240/241). A superseded row is anchored ``<base>:superseded:<id>``, so the
+ database DELIBERATELY KEEPS it (its native id is write-once and its transcript is
+ not recoverable) while the prefix scan deleted the only pointer this process had
+ to it, and ``save_state`` made that permanent: the row survives with nothing able
+ to reach it, which is the opposite of what the guard was added for.
+
+ So the map is re-read from the service instead of predicted, exactly as its two
+ siblings above already do -- the local half cannot disagree with a delete whose
+ rules it no longer has to reimplement. The count keeps the same ``max()`` shape
+ for the same reason they do: rows and mapping entries are not one-to-one.
+ """
+
self._ensure_service()
+ self._ensure_user_namespace(user_id)
+ before = self._count_session_mappings(self.state.session_mappings[user_id])
removed = self._service.delete_agent_sessions(
scope_key=user_id,
session_anchor_prefix=base_session_id,
)
- self._ensure_user_namespace(user_id)
- cleared = 0
- for agent_map in self.state.session_mappings[user_id].values():
- keys_to_remove = [
- mapping_key
- for mapping_key in list(agent_map.keys())
- if mapping_key == base_session_id or mapping_key.startswith(f"{base_session_id}:")
- ]
- for mapping_key in keys_to_remove:
- del agent_map[mapping_key]
- cleared += 1
- return max(removed, cleared)
+ self._sync_session_mappings_for_user(user_id)
+ after = self._count_session_mappings(self.state.session_mappings[user_id])
+ return max(removed, max(before - after, 0))
def get_thread_map(self, user_id: str, channel_id: str) -> Dict[str, float]:
self.maybe_reload()
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 29e81acab..ae8e464ad 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -537,14 +537,41 @@ class CommandHandlers(BaseHandler):
session_anchor = self._session_anchor_for_new(context)
sessions = getattr(self.controller, "sessions", None)
clear_base = getattr(sessions, "clear_session_base", None)
- for key in self._compat_session_keys_for_new(context, session_key):
- await self.controller.agent_service.clear_sessions(key)
- if callable(clear_base):
- try:
- clear_base(key, session_anchor)
- except Exception:
- logger.debug("Failed to clear session base for %s:%s", key, session_anchor, exc_info=True)
+ # ``/new`` deletes the session rows that scheduled tasks and watches may
+ # be pinned to. Storage pauses those definitions rather than orphaning
+ # them (archive soft-deletes because it is terminal; ``/new`` is an
+ # everyday command), and names ``/new`` as the cause. The ledger is how
+ # that count reaches this reply without every layer in between — four
+ # backend adapters included — growing a return value.
+ # Imported lazily: ``core.handlers`` must stay importable without
+ # sqlite3 (``storage/__init__`` pulls in the migration importer), an
+ # invariant the native-session lightweight-import test pins.
+ from storage.session_reclaim import session_teardown_context
+
+ with session_teardown_context(reason=self._t("command.new.pausedReason")) as reclaimed:
+ for key in self._compat_session_keys_for_new(context, session_key):
+ await self.controller.agent_service.clear_sessions(key)
+ if callable(clear_base):
+ try:
+ clear_base(key, session_anchor)
+ except Exception:
+ logger.debug("Failed to clear session base for %s:%s", key, session_anchor, exc_info=True)
full_response = f"🆕 {self._t('command.new.started')}"
+ # Split by definition type: tasks and watches are paused by the same
+ # reclaim but are managed by two different command groups, and
+ # ``vibe task resume <watch-id>`` fails with ``task_not_found``. One
+ # combined notice therefore hands half the audience directions that
+ # cannot work.
+ paused_by_type: dict[str, int] = {}
+ for entry in reclaimed:
+ if entry.get("mode") != "pause":
+ continue
+ kind = "watch" if str(entry.get("definition_type") or "") == "watch" else "task"
+ paused_by_type[kind] = paused_by_type.get(kind, 0) + 1
+ for kind, key in (("task", "command.new.pausedTasks"), ("watch", "command.new.pausedWatches")):
+ count = paused_by_type.get(kind, 0)
+ if count:
+ full_response += "\n" + self._t(key, count=count)
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, full_response)
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 16ae0fcdf..3f0b0ad41 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -315,6 +315,27 @@ class MessageHandler(BaseHandler):
effective_reasoning_effort = session_target_reasoning or scope_reasoning_override or (
vibe_agent.reasoning_effort if vibe_agent else None
)
+ # A session may pin a setting to NOTHING on purpose. The cascade above
+ # cannot express that: every `or` reads NULL as "inherit", which is the
+ # correct reading for the whole existing table and the WRONG one for a
+ # preserved `create_once` rebind, whose whole point is that the session
+ # it replaced pinned no model and must keep pinning none (D3). Only
+ # sessions carrying the explicit-override marker are re-read here, so
+ # the global meaning of NULL is untouched -- reinterpreting it would
+ # silently re-route every session that is merely inheriting.
+ explicit_overrides: set[str] = set()
+ if isinstance(session_target, dict):
+ session_meta = session_target.get("metadata")
+ if isinstance(session_meta, dict):
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+
+ marked = session_meta.get(SESSION_SETTINGS_OVERRIDE_KEY)
+ if isinstance(marked, (list, tuple, set)):
+ explicit_overrides = {str(name) for name in marked}
+ if "model" in explicit_overrides:
+ effective_model = session_target.get("model")
+ if "reasoning_effort" in explicit_overrides:
+ effective_reasoning_effort = session_target.get("reasoning_effort")
# Materialize the resolved route into EMPTY workbench session
# columns NOW, at turn start. A session created on an inherited
# default carries NULLs (dispatch resolves the live Agent default);
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index a6afa8f01..f7ac29f26 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -46,6 +46,8 @@ 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 (
+ DefinitionWriteConflict,
+ DefinitionWriteExpectation,
SKIP_REASON_SESSION_BUSY,
SKIP_REASON_TRANSPORT_UNAVAILABLE,
SQLiteBackgroundTaskStore,
@@ -57,6 +59,7 @@ from storage.background import (
)
from storage.models import agent_sessions, scope_settings, scopes
from storage.pagination import PageRequest, PageResult, page_sequence
+from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
from vibe import runtime
from vibe.i18n import t as i18n_t
@@ -246,6 +249,116 @@ class AgentRunExecutionResult:
settled_out_of_band: bool = False
+#: Durable definition-metadata key recording the last binding recovery, so a
+#: definition that keeps hitting the same dead session is reported once and not
+#: once per cron minute.
+BINDING_RECOVERY_METADATA_KEY = "binding_recovery"
+
+#: Durable definition-metadata flag: this definition deliberately pins NO Agent
+#: of its own and follows whatever Agent its bound Session carries.
+#:
+#: A reset rebind clears ``agent_name`` because the Agent the definition pinned
+#: is the one that was just found unusable. An absent ``agent_name`` alone cannot
+#: say that: it is also what "the user never pinned one" looks like, and
+#: ``vibe task update`` re-resolves an omitted Agent for every non-``existing``
+#: policy and writes the result back -- so an unrelated ``--name`` edit silently
+#: re-pinned an Agent the recovery had deliberately dropped, and the definition
+#: went back to dispatching under it. The flag makes "follow the Session" an
+#: explicit, durable state that ordinary edits preserve; an explicit ``--agent``
+#: clears it (the user is pinning again).
+BINDING_FOLLOWS_SESSION_METADATA_KEY = "binding_follows_session"
+
+#: Durable definition-metadata list of reserved sessions this definition's own
+#: recovery path handed out and then could NOT give back (HFR-276).
+#:
+#: ``_release_reserved_session`` is best-effort by design -- it runs on a path that
+#: is already reporting a failure and must not raise a second one -- so a locked
+#: database or an I/O fault leaves it returning ``False`` with the reservation still
+#: live. HFR-270's promise (a refused rebind leaves nothing behind) then depends on
+#: a cleanup that may not have happened, and NOTHING named the row: its id is random,
+#: it is never written to the definition, and the next fire that loses the same race
+#: reserves and leaks another one.
+#:
+#: Recording the id here converts an untracked leak into a tracked, retryable one.
+#: The definition that reserved it is the only thing that ever knew the id, the row
+#: is where the binding-recovery record already lives, and it survives a restart --
+#: so the next fire of the same definition can retry the release
+#: (``_retry_orphaned_reservations``) and drop the entries it resolves.
+#: ``ScheduledTaskStore.list_orphaned_reservations`` is the read side.
+#:
+#: Each entry: ``{"session_id": str, "reason": str, "at": iso8601}``.
+ORPHANED_RESERVATIONS_METADATA_KEY = "orphaned_reservations"
+
+#: What a fire reports when its terminal stamp was REFUSED by the guarded
+#: full-row write (HFR-261/HFR-264). Plain text, like every other value that
+#: reaches ``last_error`` and the run ledger's ``error`` from this module (the
+#: rebind/pause details right below, ``str(exc)``, the reclaim's pause reason), so
+#: one outcome channel does not carry two different string conventions.
+_TASK_RESULT_NOT_RECORDED_ERROR = (
+ "the result of this run could not be recorded: the task was reclaimed, "
+ "repointed or removed while it was running, so its stored state is unchanged"
+)
+
+#: "No value was supplied", as distinct from "the supplied value is ``None``".
+#: A reclaim snapshot records a session's ``model`` / ``reasoning_effort`` as
+#: NULL when the session pinned neither, and D3 requires the rebind to write
+#: that NULL through unchanged. Collapsing both meanings into ``None`` makes a
+#: session silently acquire whatever model its Agent happens to carry at rebind
+#: time, while the recovery is still recorded as settings-preserving. Mirrors
+#: the ``_UNSET`` sentinel in ``core/vibe_agents.py``.
+_UNSET: Any = object()
+
+
+class UnresolvableSessionTarget(ValueError):
+ """A pinned ``session_id`` that can never resolve until something rebinds it.
+
+ A distinct type rather than a message match, because it selects the one error
+ class a definition may be auto-paused or rebound for. Transient faults (a DB
+ error, a refused turn) must NOT land here: pausing a user's task because
+ SQLite was momentarily unavailable is a worse bug than the one this fixes.
+
+ Subclasses ``ValueError`` so every existing ``except ValueError`` caller —
+ the CLI, the API, watches — keeps its current behaviour.
+ """
+
+ def __init__(self, message: str, *, session_id: str, reason: str) -> None:
+ super().__init__(message)
+ self.session_id = session_id
+ self.reason = reason
+
+
+@dataclass
+class SessionBindingChange:
+ """What the scheduler did about a pinned session that no longer exists."""
+
+ # "rebound" -- a replacement session was reserved AND stored
+ # "paused" -- the definition was user-pinned, so it was disabled instead
+ # "reclaimed" -- a replacement was reserved but the guarded write refused it, so
+ # nothing was stored and the fire did not run (HFR-268), AND the
+ # replacement was given back (HFR-270)
+ # "orphaned" -- the same refusal, but giving the replacement back FAILED, so the
+ # session is still live and is recorded for a later attempt
+ # (HFR-276). Distinct from "reclaimed" because the cleanup is the
+ # only difference between them and the user is told which happened.
+ action: str
+ task_id: str
+ reason: str
+ previous_session_id: Optional[str]
+ detail: str
+ new_session_id: Optional[str] = None
+ settings_preserved: bool = False
+ #: The reserved session that could not be released, on the "orphaned" action.
+ orphaned_session_id: Optional[str] = None
+ #: Whether that id was durably recorded on the definition for a later attempt.
+ orphan_tracked: bool = False
+
+ @property
+ def signature(self) -> str:
+ """One broken binding, one notification — not one per fire."""
+
+ return f"{self.action}:{self.reason}:{self.previous_session_id or ''}"
+
+
def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None) -> ResolvedSessionIdTarget:
raw = (session_id or "").strip()
if not raw:
@@ -284,13 +397,17 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
engine.dispose()
if row is None:
- raise ValueError(f"agent session id not found: {raw}")
+ raise UnresolvableSessionTarget(
+ f"agent session id not found: {raw}", session_id=raw, reason="missing"
+ )
# Archived sessions are terminal + inert. A task/watch/run that still targets
# one by id must NOT fire into it — treat it as an unresolvable target so the
# run is skipped (archive also reclaims bound definitions, so this is defense
# in depth for manual ``--session-id`` runs and any stragglers).
if str(row["status"] or "") == "archived":
- raise ValueError(f"agent session is archived: {raw}")
+ raise UnresolvableSessionTarget(
+ f"agent session is archived: {raw}", session_id=raw, reason="archived"
+ )
persisted_scope_id = str(row["scope_id"] or "").strip() or None
platform = str(row["platform"] or "")
scope_type = str(row["scope_type"] or "")
@@ -308,15 +425,27 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
native_scope_id = raw
else:
if not platform or not native_scope_id:
- raise ValueError(f"agent session id cannot be used as a task target: {raw}")
+ raise UnresolvableSessionTarget(
+ f"agent session id cannot be used as a task target: {raw}",
+ session_id=raw,
+ reason="unusable",
+ )
if scope_type == "thread":
try:
native_scope_id, scoped_thread_id = split_thread_native_id(native_scope_id)
except ValueError as exc:
- raise ValueError(f"agent session id cannot be used as a task target: {raw}") from exc
+ raise UnresolvableSessionTarget(
+ f"agent session id cannot be used as a task target: {raw}",
+ session_id=raw,
+ reason="unusable",
+ ) from exc
scope_type = "channel"
elif scope_type not in {"channel", "user", "project"}:
- raise ValueError(f"agent session id cannot be used as a task target: {raw}")
+ raise UnresolvableSessionTarget(
+ f"agent session id cannot be used as a task target: {raw}",
+ session_id=raw,
+ reason="unusable",
+ )
anchor = str(row["session_anchor"] or "")
thread_id = scoped_thread_id
@@ -645,6 +774,9 @@ class ScheduledTaskStore:
self._sqlite = SQLiteBackgroundTaskStore() if path is None else None
self._signature: Optional[tuple[int, int, int]] = None
self._tasks: Dict[str, ScheduledTask] = {}
+ #: Set when a failed write left this mirror INCOMPLETE, cleared by the reload
+ #: that repairs it. See ``maybe_reload`` and ``_reload_after_lost_write``.
+ self._reload_required = False
self.load()
def load(self) -> None:
@@ -653,10 +785,12 @@ class ScheduledTaskStore:
item["id"]: ScheduledTask.from_dict(item)
for item in self._sqlite.list_scheduled_tasks()
}
+ self._reload_required = False
return
if not self.path.exists():
self._tasks = {}
self._signature = None
+ self._reload_required = False
return
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
@@ -675,15 +809,47 @@ class ScheduledTaskStore:
tasks[task.id] = task
self._tasks = tasks
self._signature = _path_signature(self.path)
+ self._reload_required = False
def maybe_reload(self) -> bool:
+ """Refresh the mirror when the database changed -- or when WE know it is stale.
+
+ HFR-277, the watch store's twin. ``PRAGMA data_version`` (the probe behind
+ ``self._sqlite.maybe_reload``) only reports a COMMITTED write by another
+ connection, and the write that drops an entry in ``_reload_after_lost_write``
+ ROLLED BACK: data_version is unchanged, so every later call here saw "nothing
+ changed" and the dropped definition stayed invisible in-process while its row sat
+ enabled in SQLite. That is durable until a restart or an unrelated commit happens
+ to bump the counter -- and ``reconcile_jobs`` schedules out of exactly this dict,
+ so the task simply never fires again.
+
+ ``_reload_required`` is the fix: an in-process flag, not a database column,
+ because the state it records is a property of THIS mirror, not of the data. A
+ restart reloads from SQLite anyway, so there is nothing for it to survive; making
+ it durable would mean writing to the very database that was just proven
+ unwritable. It is cleared only by the reload that repairs the mirror (``load``),
+ so a reload that fails again keeps retrying on every later tick.
+ """
+
if self._sqlite is not None:
changed = self._sqlite.maybe_reload()
+ if self._reload_required:
+ try:
+ self.load()
+ except Exception:
+ # Still unreachable. Keep the flag and the incomplete mirror, and
+ # report "nothing changed" -- the retry is the next tick's.
+ logger.exception(
+ "Could not reload scheduled tasks after a lost write; the live "
+ "store stays incomplete until a later attempt succeeds"
+ )
+ return False
+ return True
if changed:
self.load()
return changed
signature = _path_signature(self.path)
- if signature == self._signature:
+ if signature == self._signature and not self._reload_required:
return False
self.load()
return True
@@ -711,13 +877,95 @@ class ScheduledTaskStore:
def get_task(self, task_id: str) -> Optional[ScheduledTask]:
return self._tasks.get(task_id)
+ @staticmethod
+ def _read_state(task: ScheduledTask) -> DefinitionWriteExpectation:
+ """The guarded state a full-row payload for ``task`` is derived from.
+
+ Called BEFORE the mutation, because the in-memory task IS the read: every
+ caller here loaded it from SQLite (``load`` / ``maybe_reload``), edits a few
+ fields, and then writes every column back. ``deleted_at`` is not a field of
+ ``ScheduledTask`` at all -- the store only ever lists live rows -- which is
+ why the full-row write would otherwise resurrect a removed task.
+ """
+
+ return DefinitionWriteExpectation.from_read(
+ session_id=task.session_id,
+ enabled=task.enabled,
+ deleted_at=None,
+ metadata=task.metadata,
+ )
+
+ def _write_task(self, task: ScheduledTask, expect: DefinitionWriteExpectation) -> bool:
+ """Persist a whole task row; ``False`` means the guard refused the write.
+
+ On refusal the in-memory mirror is reloaded, so the store never keeps serving
+ the mutated task that the database rejected -- and on a RAISED write too
+ (HFR-272, the watch store's twin). A rolled-back transaction and a refused one
+ leave the database in exactly the same place; only the ``False`` return was ever
+ being handled, so a disk error or a locked database left every in-process reader
+ (``reconcile_jobs`` schedules from this dict, ``_read_state`` derives the next
+ compare-and-set's expectation from it) serving an edit that does not exist.
+ """
+
+ try:
+ if self._sqlite is None:
+ self._save()
+ return True
+ landed = self._sqlite.upsert_scheduled_task(task.to_dict(), expect=expect)
+ except Exception:
+ self._reload_after_lost_write(task.id)
+ raise
+ if landed:
+ return True
+ self.load()
+ return False
+
+ def _reload_after_lost_write(self, task_id: str) -> None:
+ """Drop a mirror entry the database did not accept, reloading if it can.
+
+ The watch store's twin, and for the same reason: the reload can fail too, and a
+ missing definition is a safer thing for the scheduler to act on than a mutated
+ one that was never stored. ``maybe_reload`` restores it once the database is
+ reachable again -- which it can only do because dropping the entry also marks
+ the mirror as needing an UNCONDITIONAL reload (HFR-277). The failed write rolled
+ back, so ``PRAGMA data_version`` never moved and the probe alone would report
+ "nothing changed" forever.
+ """
+
+ try:
+ self.load()
+ except Exception:
+ logger.exception(
+ "Could not reload scheduled tasks after a failed write; dropping the "
+ "stale mirror entry for %s",
+ task_id,
+ )
+ self._tasks.pop(task_id, None)
+ self._signature = None
+ self._reload_required = True
+
def upsert_task(self, task: ScheduledTask) -> ScheduledTask:
+ """Create or adopt a whole task row (unguarded: the payload is not a re-read).
+
+ The mirror rolls back with the write here too (HFR-275, the watch store's twin).
+ This is the one entry point that can add an id the database has never seen, and a
+ phantom is worse than a stale edit: ``reconcile_jobs`` would SCHEDULE a task whose
+ creation the caller was told had FAILED and fire its prompt into a channel, with
+ no durable row to stop it and nothing to reload it away.
+ """
+
task.updated_at = _utc_now_iso()
self._tasks[task.id] = task
- if self._sqlite is not None:
- self._sqlite.upsert_scheduled_task(task.to_dict())
- return task
- self._save()
+ try:
+ if self._sqlite is not None:
+ # No ``expect``: this is the create/adopt entry point (``add_task``),
+ # where the payload is not derived from a stored row.
+ self._sqlite.upsert_scheduled_task(task.to_dict())
+ return task
+ self._save()
+ except Exception:
+ self._reload_after_lost_write(task.id)
+ raise
return task
def add_task(
@@ -758,23 +1006,37 @@ class ScheduledTaskStore:
return self.upsert_task(task)
def remove_task(self, task_id: str) -> bool:
+ """Delete a task; the mirror rolls back with the delete (HFR-275).
+
+ The safer direction of the same class -- an entry dropped here reads as "gone"
+ and stops the schedule -- but silently, and NOT self-healing: with the row still
+ there and unchanged, ``maybe_reload`` sees no external write, so the task the user
+ was told could not be deleted just stops firing until the process restarts.
+ """
+
if task_id not in self._tasks:
return False
del self._tasks[task_id]
- if self._sqlite is not None:
- self._sqlite.remove_task(task_id)
- return True
- self._save()
+ try:
+ if self._sqlite is not None:
+ self._sqlite.remove_task(task_id)
+ return True
+ self._save()
+ except Exception:
+ self._reload_after_lost_write(task_id)
+ raise
return True
def set_enabled(self, task_id: str, enabled: bool) -> ScheduledTask:
task = self._tasks[task_id]
+ expect = self._read_state(task)
task.enabled = enabled
task.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_scheduled_task(task.to_dict())
- return task
- self._save()
+ if not self._write_task(task, expect):
+ # A pause/resume that lost to a teardown must not be reported as applied:
+ # this write also restores ``last_error`` and ``session_id`` from the stale
+ # mirror, so letting it "succeed" would erase the reclaim's pause reason.
+ raise DefinitionWriteConflict(task_id, definition_type="scheduled task")
return task
def update_task(
@@ -798,6 +1060,10 @@ class ScheduledTaskStore:
metadata: Optional[dict[str, Any]] = None,
) -> ScheduledTask:
task = self._tasks[task_id]
+ # Captured before the first mutation: this is the state the CALLER read
+ # (``vibe task update`` resolved Agents and Sessions from this very object),
+ # and it is what the write below re-asserts.
+ expect = self._read_state(task)
task.name = name
task.session_key = session_key
task.session_id = session_id
@@ -817,27 +1083,93 @@ class ScheduledTaskStore:
if metadata is not None:
task.metadata = dict(metadata)
task.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_scheduled_task(task.to_dict())
- return task
- self._save()
+ if not self._write_task(task, expect):
+ # The edit did NOT land, and its payload would have restored the Session
+ # binding, enabled state and reclaim snapshot the teardown just changed.
+ # Raising is the contract: ``cmd_task_update`` prints an error and exits
+ # non-zero instead of echoing a task the database never accepted.
+ raise DefinitionWriteConflict(task_id, definition_type="scheduled task")
return task
+ def record_binding_recovery(self, task_id: str, payload: dict[str, Any]) -> bool:
+ """Durably stamp what was done about a broken session binding.
+
+ Written through the store (not by mutating a task the next
+ ``maybe_reload`` may replace) because it is what makes the notification
+ once-per-transition instead of once-per-fire.
+ """
+
+ self.maybe_reload()
+ task = self._tasks.get(task_id)
+ if task is None:
+ return False
+ expect = self._read_state(task)
+ metadata = dict(task.metadata or {})
+ metadata[BINDING_RECOVERY_METADATA_KEY] = dict(payload)
+ task.metadata = metadata
+ task.updated_at = _utc_now_iso()
+ # A runtime stamp, not a user action: a lost write is reported by the return
+ # value (the caller already treats ``False`` as "nothing recorded") rather than
+ # by an exception through the fire path.
+ return self._write_task(task, expect)
+
+ def list_orphaned_reservations(self, task_id: str) -> list[dict[str, Any]]:
+ """The reserved sessions recorded against ``task_id`` that were never given back."""
+
+ task = self._tasks.get(task_id)
+ if task is None or not isinstance(task.metadata, dict):
+ return []
+ entries = task.metadata.get(ORPHANED_RESERVATIONS_METADATA_KEY)
+ if not isinstance(entries, list):
+ return []
+ return [dict(entry) for entry in entries if isinstance(entry, dict)]
+
+ def record_orphaned_reservations(self, task_id: str, entries: list[dict[str, Any]]) -> bool:
+ """Durably record (or clear) the reservations this definition could not release.
+
+ HFR-276. Written through the store, from a FRESH read, for the same reason
+ ``record_binding_recovery`` is: the caller reaches here on a path where the
+ previous full-row write was already refused, so the mirror it holds is stale
+ and ``_write_task`` has since reloaded the cache. Deriving the expectation from
+ the reloaded row is what makes this write land in the very race that produced
+ the orphan, instead of being refused by the same teardown twice.
+
+ ``False`` means nothing was recorded -- the definition was removed, or a second
+ teardown refused this write too -- and the caller MUST consume it: the whole
+ point of the record is that the id is otherwise unrecoverable, so silently
+ losing it is the same defect one layer further in.
+ """
+
+ self.maybe_reload()
+ task = self._tasks.get(task_id)
+ if task is None:
+ return False
+ expect = self._read_state(task)
+ metadata = dict(task.metadata or {})
+ if entries:
+ metadata[ORPHANED_RESERVATIONS_METADATA_KEY] = [dict(entry) for entry in entries]
+ else:
+ metadata.pop(ORPHANED_RESERVATIONS_METADATA_KEY, None)
+ task.metadata = metadata
+ task.updated_at = _utc_now_iso()
+ return self._write_task(task, expect)
+
def mark_task_result(self, task_id: str, *, error: Optional[str], disable_one_shot: bool = True) -> bool:
self.maybe_reload()
task = self._tasks.get(task_id)
if task is None:
return False
+ expect = self._read_state(task)
task.last_run_at = _utc_now_iso()
task.last_error = error
if disable_one_shot and task.schedule_type == "at":
task.enabled = False
task.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_scheduled_task(task.to_dict())
- return True
- self._save()
- return True
+ # Same reasoning as ``record_binding_recovery``, and the same reason it must be
+ # guarded: this payload carries the mirror's ``session_id`` and ``enabled``, so
+ # a run result landing after a ``/new`` reclaim would re-enable the definition
+ # and re-point it at the session the reclaim just tore down.
+ return self._write_task(task, expect)
class TaskExecutionStore:
@@ -850,6 +1182,18 @@ class TaskExecutionStore:
self._ensure_dirs()
self._signature = self._state_signature()
+ @property
+ def sqlite_backend(self) -> Optional[SQLiteBackgroundTaskStore]:
+ """The SQLite backend behind this store, or ``None`` for the file backend.
+
+ Exposed so a caller that must commit an outbox row TOGETHER with another
+ write can find out whether the two live in one database (HFR-269). The file
+ backend keeps runs in a directory of JSON files and can share a transaction
+ with nothing.
+ """
+
+ return self._sqlite
+
def _ensure_dirs(self) -> None:
if self._sqlite is not None:
return
@@ -899,12 +1243,23 @@ class TaskExecutionStore:
continue
path.replace(pending_path)
+ @staticmethod
+ def queued_run_payload(request: TaskExecutionRequest) -> dict[str, Any]:
+ """The ``agent_runs`` payload ``enqueue`` would write for *request*.
+
+ Exposed so a caller that commits the outbox row inside ANOTHER transaction
+ (HFR-269) writes exactly the row this store would have written, rather than a
+ second, drifting copy of the same mapping.
+ """
+
+ payload = request.to_dict()
+ payload["status"] = "queued"
+ payload["updated_at"] = request.created_at
+ return payload
+
def enqueue(self, request: TaskExecutionRequest) -> TaskExecutionRequest:
if self._sqlite is not None:
- payload = request.to_dict()
- payload["status"] = "queued"
- payload["updated_at"] = request.created_at
- self._sqlite.enqueue_run(payload)
+ self._sqlite.enqueue_run(self.queued_run_payload(request))
return request
self._ensure_dirs()
path = self._request_path(request.id, state="pending")
@@ -1005,25 +1360,65 @@ class TaskExecutionStore:
metadata: Optional[dict[str, Any]] = None,
) -> TaskExecutionRequest:
return self.enqueue(
- TaskExecutionRequest(
- id=uuid4().hex[:12],
- request_type=run_type,
- task_id=definition_id,
+ self.build_hook_send(
session_key=session_key,
session_id=session_id,
+ prompt=prompt,
post_to=post_to,
deliver_key=deliver_key,
- prompt=prompt,
- message=prompt,
+ agent_name=agent_name,
+ session_policy=session_policy,
+ run_type=run_type,
+ definition_id=definition_id,
source_kind=source_kind,
source_actor=source_actor,
parent_run_id=parent_run_id,
- agent_name=agent_name,
- session_policy=session_policy,
- metadata=dict(metadata or {}),
+ metadata=metadata,
)
)
+ def build_hook_send(
+ self,
+ *,
+ session_key: str,
+ session_id: Optional[str] = None,
+ prompt: str,
+ post_to: Optional[str] = None,
+ deliver_key: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
+ run_type: str = "hook_send",
+ definition_id: Optional[str] = None,
+ source_kind: str = "cli",
+ source_actor: Optional[str] = None,
+ parent_run_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ ) -> TaskExecutionRequest:
+ """Build a hook request WITHOUT queueing it.
+
+ For the caller that must make the outbox row durable inside someone else's
+ transaction (HFR-269): the request is composed here, so its shape cannot drift
+ from ``enqueue_hook_send``, and becomes durable only where that caller commits.
+ """
+
+ return TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type=run_type,
+ task_id=definition_id,
+ session_key=session_key,
+ session_id=session_id,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ prompt=prompt,
+ message=prompt,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
+ agent_name=agent_name,
+ session_policy=session_policy,
+ metadata=dict(metadata or {}),
+ )
+
def enqueue_agent_run(
self,
*,
@@ -1931,6 +2326,12 @@ class ScheduledTaskService:
self.reconcile_jobs()
except Exception as exc:
logger.error("Initial scheduled task reconcile failed: %s", exc, exc_info=True)
+ try:
+ # Startup integrity check: a broken binding is otherwise invisible until
+ # the next fire, which for a weekly cron is a week of silence.
+ self.audit_definition_bindings()
+ except Exception as exc:
+ logger.error("Harness definition binding audit failed: %s", exc, exc_info=True)
def _spawn_watch_store(self) -> None:
self._reconcile_task = asyncio.create_task(self._watch_store())
@@ -2875,6 +3276,13 @@ class ScheduledTaskService:
error: Optional[str] = None
session_id = task.session_id
session_key = task.session_key
+ binding_change: Optional[SessionBindingChange] = None
+ # HFR-276: an earlier fire of THIS definition may have reserved a replacement
+ # session it could not give back. The id is recorded on the definition, so the
+ # retry belongs here -- before the fire, so a cleanup that succeeds is off the
+ # books whatever this run does, and outside the ``try`` because it reports
+ # itself and must never be mistaken for the run's own failure.
+ self._retry_orphaned_reservations(task)
try:
if task.session_policy == "create_per_run":
session_id = self._reserve_runtime_session(
@@ -2898,10 +3306,67 @@ class ScheduledTaskService:
except asyncio.CancelledError:
self.reconcile_jobs()
raise
+ except UnresolvableSessionTarget as exc:
+ # The pinned session no longer resolves. Left alone this definition
+ # re-fires and re-fails on every schedule with nobody told, so classify
+ # first: a ``create_once`` definition reserved its own session and may
+ # re-reserve one, anything else is user-pinned and gets paused. Either
+ # way the user is told exactly once.
+ logger.error("Scheduled task %s has an unresolvable session binding: %s", task.id, exc)
+ binding_change = self._recover_pinned_session_binding(task, exc)
+ error = binding_change.detail
+ if binding_change.action == "rebound" and binding_change.new_session_id:
+ session_id = binding_change.new_session_id
+ session_key = ""
+ try:
+ error = await self._execute_request(
+ session_key=session_key,
+ session_id=session_id,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ prompt=task.prompt,
+ execution_id=execution_id,
+ task_id=task.id,
+ trigger_kind="scheduled",
+ agent_name=task.agent_name,
+ )
+ except asyncio.CancelledError:
+ self.reconcile_jobs()
+ raise
+ except Exception as retry_exc:
+ error = str(retry_exc)
+ logger.error(
+ "Scheduled task %s failed after rebinding to %s: %s",
+ task.id,
+ session_id,
+ retry_exc,
+ exc_info=True,
+ )
except Exception as exc:
error = str(exc)
logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
- self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot)
+ if not self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot):
+ # The TERMINAL STAMP was refused (HFR-261): the definition was reclaimed,
+ # repointed, soft-deleted or removed while this fire was running, so
+ # ``last_run_at`` / ``last_error`` / the one-shot disable are NOT stored.
+ # Returning a result whose ``error`` is ``None`` here made
+ # ``_execute_claimed_request`` complete the run ``ok=True`` -- the database
+ # refused the stale stamp and both the caller AND the run ledger reported
+ # success, while an ``at`` task that was never disabled can fire again.
+ # Carried on the EXISTING error channel: a non-empty ``error`` is already
+ # what makes ``complete(ok=not error)`` record the run as failed and what
+ # the CLI and the Harness detail pane show, so no new settlement path is
+ # needed. A real failure keeps its own message; only a would-be success
+ # gains one.
+ logger.warning(
+ "Scheduled task %s produced a result the store refused to stamp; "
+ "reporting the run as failed",
+ task.id,
+ )
+ if not error:
+ error = _TASK_RESULT_NOT_RECORDED_ERROR
+ if binding_change is not None:
+ await self._emit_binding_change(binding_change)
self.reconcile_jobs()
return TaskExecutionResult(error=error, session_key=session_key, session_id=session_id)
@@ -3113,14 +3578,441 @@ class ScheduledTaskService:
)
return True
+ # --- pinned session binding recovery -------------------------------------
+ #
+ # One choke point: classify -> maybe rebind -> maybe pause -> notify once.
+ # The pause predicate is task-scoped (only a task has a definition to pause)
+ # but the notification is not, so a run type added later inherits the
+ # behaviour by default rather than by remembering to wire it.
+
+ def _recover_pinned_session_binding(
+ self,
+ task: ScheduledTask,
+ exc: UnresolvableSessionTarget,
+ ) -> SessionBindingChange:
+ previous = str(exc.session_id or task.session_id or "") or None
+ snapshot = None
+ if isinstance(task.metadata, dict):
+ candidate = task.metadata.get(SESSION_SETTINGS_SNAPSHOT_KEY)
+ if isinstance(candidate, dict):
+ snapshot = candidate
+
+ scope_id = ""
+ if isinstance(task.metadata, dict):
+ scope_id = str(task.metadata.get("session_scope_id") or "").strip()
+
+ # ``existing`` is user-pinned: re-pointing it would lose the continuity the
+ # pin exists to guarantee, so it is never rebound. Only ``create_once``
+ # reserved its own session and may reserve another; ``create_per_run``
+ # never reaches here because it reserves before every fire.
+ if task.session_policy == "create_once" and (scope_id or task.deliver_key):
+ rebound = self._rebind_create_once_session(task, snapshot)
+ if rebound is not None:
+ new_session_id, settings_preserved = rebound
+ if not settings_preserved:
+ # Record the choice as an explicit, durable state, not as an
+ # absent ``agent_name``: ``vibe task update`` re-resolves an
+ # omitted Agent and writes it back, so without the flag the
+ # next unrelated edit re-pins the Agent this recovery dropped.
+ task.metadata = {
+ **(task.metadata if isinstance(task.metadata, dict) else {}),
+ BINDING_FOLLOWS_SESSION_METADATA_KEY: True,
+ }
+ if not settings_preserved and task.agent_name:
+ # The reset rebind could not use the definition's own Agent --
+ # that is WHY it reset. Leaving the pin in place makes the
+ # storage fix cosmetic: ``_build_context`` sends it as
+ # ``vibe_agent_name``, which ``MessageHandler`` prioritises
+ # OVER the session row's Agent, so every fire would dispatch
+ # under the Agent that was just found unusable while the row
+ # says otherwise. Dropping the pin hands authority back to the
+ # rebound session, which is where a ``create_once``
+ # definition's Agent identity belongs -- and persisting it
+ # below is what makes the choice survive to the NEXT fire, not
+ # just this retry.
+ logger.info(
+ "Task %s dropped its stale Agent pin %r during a reset rebind; "
+ "the rebound session's Agent now governs",
+ task.id,
+ task.agent_name,
+ )
+ task.agent_name = None
+ if not self._persist_task_session_id(task, new_session_id):
+ # THE REBIND DID NOT LAND (HFR-268). ``new_session_id`` is left
+ # unset on purpose: it is what ``_execute_task`` reads to decide
+ # whether to retry the fire, so an unstored rebind cannot dispatch
+ # a turn. The action is its own transition rather than "rebound" so
+ # that the durable ``binding_recovery`` marker and the notice both
+ # describe what actually happened -- reporting a rebind here is the
+ # HFR-266 lie one layer up.
+ #
+ # AND THE REPLACEMENT IS GIVEN BACK (HFR-270). The reservation
+ # already COMMITTED -- a different store, a different transaction,
+ # and for a standalone placement a mkdir as well -- so a refusal
+ # that only declined to dispatch left a live, unreferenced
+ # background session and its workspace behind, one more per fire
+ # that loses this race, with nothing that will ever run, list or
+ # delete them.
+ #
+ # AND THE ANSWER TO "WAS IT?" IS CONSUMED (HFR-276). The release is
+ # deliberately never fatal, so a locked database or an I/O fault
+ # returns ``False`` with the reservation still live: reporting
+ # "reclaimed" there is HFR-266's lie one layer inside HFR-270's fix,
+ # and the id -- random, never written to the definition -- would be
+ # lost with the log line. The losing branch records it instead, so
+ # the leak is TRACKED and a later fire can finish the job.
+ release_reason = f"the rebind of harness definition {task.id} was refused"
+ prefix = (
+ f"not rebound: {exc}. The definition was reclaimed, re-pointed or "
+ "removed while a replacement session was being reserved, so the "
+ "rebind was not stored and this run did not execute."
+ )
+ if self._release_reserved_session(new_session_id, reason=release_reason):
+ return SessionBindingChange(
+ action="reclaimed",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=(
+ f"{prefix} The next run re-resolves from the stored definition."
+ ),
+ )
+ tracked = self._track_orphaned_reservation(
+ task.id, new_session_id, release_reason
+ )
+ if tracked == "recorded":
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back and is recorded on this definition; the next run retries "
+ "the cleanup."
+ )
+ elif tracked == "stamped":
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back, and the record of it could not be stored either; its own "
+ "row names this definition, so the next run recovers it from "
+ "that stamp."
+ )
+ else:
+ cleanup = (
+ f"The replacement session {new_session_id} could NOT be given "
+ "back, and this definition no longer exists, so no later run "
+ "will look for it; it is reported here and in the logs only."
+ )
+ return SessionBindingChange(
+ action="orphaned",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=f"{prefix} {cleanup}",
+ orphaned_session_id=new_session_id,
+ orphan_tracked=tracked != "untracked",
+ )
+ if settings_preserved:
+ detail = (
+ f"rebound to a new agent session {new_session_id}; the previous session "
+ f"({previous}) was deleted. Its workdir/agent/model were preserved."
+ )
+ else:
+ detail = (
+ f"rebound to a new agent session {new_session_id}; the previous session "
+ f"({previous}) was deleted and its settings could not be recovered, so "
+ "scope defaults were used."
+ )
+ return SessionBindingChange(
+ action="rebound",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=detail,
+ new_session_id=new_session_id,
+ settings_preserved=settings_preserved,
+ )
+
+ self._pause_task(task)
+ return SessionBindingChange(
+ action="paused",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=(
+ f"paused: {exc}. The bound agent session no longer exists, so this "
+ "definition would fail on every run. Re-point it with "
+ f"`vibe task update {task.id} --session-id <id>` and resume it with "
+ f"`vibe task resume {task.id}`."
+ ),
+ )
+
+ def _rebind_create_once_session(
+ self,
+ task: ScheduledTask,
+ snapshot: Optional[dict[str, Any]],
+ ) -> Optional[tuple[str, bool]]:
+ """Reserve a replacement session, preserving the lost one's settings.
+
+ Returns ``(session_id, settings_preserved)``, or ``None`` when no session
+ could be reserved at all. The snapshot is written by the reclaim that ran
+ when the old row was deleted; where it is absent — a definition orphaned
+ before that landed — the rebind falls back to scope defaults and says so,
+ so the user can tell a preserved rebind from a reset one.
+ """
+
+ # Local, like every other ``core.vibe_agents`` use in this module (the Agent
+ # catalog pulls in migrations/importer, which must not run at import time).
+ from core.vibe_agents import AgentUnavailableError
+
+ attempts: list[tuple[dict[str, Any], bool]] = []
+ if snapshot:
+ attempts.append(
+ (
+ {
+ "agent_name": snapshot.get("agent_name") or task.agent_name,
+ "workdir": snapshot.get("workdir") or task.cwd,
+ "model": snapshot.get("model"),
+ "reasoning_effort": snapshot.get("reasoning_effort"),
+ },
+ True,
+ )
+ )
+ # The non-preserving attempt must NOT re-send the definition's own Agent.
+ # For a ``create_once`` definition ``task.agent_name`` is the same name the
+ # snapshot carries, so when that Agent has been deleted or disabled the
+ # fallback repeats the identical ``require_enabled`` failure and the
+ # definition is paused -- when degrading to scope defaults is the entire
+ # reason this attempt exists, and is what its own notice claims it did.
+ # ``None`` is unambiguous here: ``_reserve_runtime_session`` reads it as
+ # "resolve the scope Agent, else the default Agent", which is precisely
+ # the intent. Only ``model``/``reasoning_effort`` need a sentinel, because
+ # for them ``None`` is also a value a snapshot can legitimately carry.
+ attempts.append(({"agent_name": None, "workdir": task.cwd}, False))
+
+ for overrides, preserved in attempts:
+ try:
+ session_id = self._reserve_runtime_session(
+ deliver_key=task.deliver_key,
+ metadata=task.metadata,
+ definition_id=task.id,
+ **overrides,
+ )
+ except AgentUnavailableError as exc:
+ # THE ONLY CONDITION THIS FALLBACK IS FOR: a snapshot naming an Agent
+ # the user has since deleted or disabled must degrade to scope
+ # defaults, not to a permanent failure (HFR-243).
+ #
+ # NARROW ON PURPOSE (HFR-265). A bare ``except Exception`` here read
+ # SQLite contention, a migration failure and a filesystem error as
+ # "that Agent is gone": the retry then succeeded against scope
+ # defaults, ``_persist_task_session_id`` wrote the reset route, and the
+ # definition PERMANENTLY lost the Agent/model the snapshot was holding
+ # for it -- a transient fault turned into data loss, with the notice
+ # claiming the settings "could not be recovered". Same shape as a broad
+ # ``OperationalError`` retry, and the reason the deleted/disabled case
+ # now has a type of its own instead of being inferred from a failure.
+ logger.warning(
+ "Rebind reservation for task %s cannot use Agent %r (%s, preserved=%s): %s",
+ task.id,
+ exc.agent_name,
+ exc.reason,
+ preserved,
+ exc,
+ )
+ continue
+ if session_id:
+ return session_id, preserved
+ return None
+
+ def _persist_task_session_id(self, task: ScheduledTask, session_id: str) -> bool:
+ """Store the rebind. ``False`` means the guard refused it — do NOT act on it.
+
+ HFR-268. This used to swallow the conflict and return ``None``, and the comment
+ said "the rebind stands for THIS fire only". It does not. The refusal is the
+ database saying the definition was reclaimed, repointed or SOFT-DELETED inside
+ the window (``expect.deleted_at`` is ``None``, so a ``RECLAIM_DELETE`` refuses
+ here too), and the caller went on to dispatch the prompt and post the reply
+ into the freshly reserved session anyway: the same shape as HFR-267, except the
+ guard WAS asked first and its answer was dropped rather than never requested.
+ A ``/new`` that pauses a ``create_once`` task mid-fire would tell the user the
+ task was paused and then deliver a turn for it.
+ """
+
+ try:
+ self._write_task_session_id(task, session_id)
+ except DefinitionWriteConflict as exc:
+ logger.warning("Could not persist the rebind for task %s: %s", task.id, exc)
+ return False
+ return True
+
+ def _write_task_session_id(self, task: ScheduledTask, session_id: str) -> None:
+ self.store.update_task(
+ task.id,
+ name=task.name,
+ session_key=task.session_key,
+ session_id=session_id,
+ prompt=task.prompt,
+ schedule_type=task.schedule_type,
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ cwd=task.cwd,
+ update_cwd=False,
+ metadata=task.metadata,
+ )
+
+ def _pause_task(self, task: ScheduledTask) -> None:
+ try:
+ self.store.set_enabled(task.id, False)
+ except KeyError:
+ logger.debug("Task %s vanished before it could be paused", task.id)
+ except DefinitionWriteConflict:
+ # A teardown got there first (``/new`` pauses, the archive dialog
+ # soft-deletes). The definition is already off; re-writing the whole row
+ # from this stale mirror would only restore what the teardown cleared.
+ logger.debug("Task %s was already reclaimed before it could be paused", task.id)
+
+ async def _emit_binding_change(self, change: SessionBindingChange) -> None:
+ """Notify once per binding transition, never once per fire.
+
+ A daily cron on a dead session would otherwise notify every day. The
+ dedup key is the transition, so a rebind (whose previous session id
+ differs each time) always notifies while a definition re-fired against the
+ same dead session stays quiet.
+
+ The dedup marker IS the guarantee, so the notification is conditional on it
+ landing: ``record_binding_recovery`` is a guarded write (HFR-261) that
+ refuses when the definition was reclaimed, repointed or removed inside the
+ window, and ignoring that ``False`` delivered a notice with nothing durable
+ behind it — "once per transition" for a marker that was never stored, i.e.
+ once per fire, forever, describing a recovery the stored definition no
+ longer reflects (HFR-266).
+ """
+
+ task = self.store.get_task(change.task_id)
+ if task is None:
+ return
+ recorded = task.metadata.get(BINDING_RECOVERY_METADATA_KEY) if isinstance(task.metadata, dict) else None
+ if isinstance(recorded, dict) and recorded.get("signature") == change.signature:
+ return
+ if not self.store.record_binding_recovery(
+ change.task_id,
+ {
+ "signature": change.signature,
+ "action": change.action,
+ "reason": change.reason,
+ "previous_session_id": change.previous_session_id,
+ "new_session_id": change.new_session_id,
+ "settings_preserved": change.settings_preserved,
+ "at": _utc_now_iso(),
+ # Only on the HFR-276 branch, so the recorded shape of every other
+ # transition is unchanged.
+ **(
+ {
+ "orphaned_session_id": change.orphaned_session_id,
+ "orphan_tracked": change.orphan_tracked,
+ }
+ if change.orphaned_session_id
+ else {}
+ ),
+ },
+ ):
+ logger.warning(
+ "Not notifying the binding %s for task %s: the recovery record was "
+ "refused, so the definition was reclaimed, repointed or removed and "
+ "this transition no longer describes it",
+ change.action,
+ change.task_id,
+ )
+ return
+ await self._notify_binding_change(task, change)
+
+ async def _notify_binding_change(self, task: ScheduledTask, change: SessionBindingChange) -> None:
+ """Single delivery seam for a binding change.
+
+ Deliberately the only place that decides how the user hears about this. The
+ durable half is already written (``last_error`` plus
+ ``metadata.binding_recovery``), which the CLI and the Harness detail pane
+ read today; the delivery ladder for definitions whose session is gone is
+ built on top of this seam and is not this change's job.
+ """
+
+ logger.warning(
+ "Harness definition %s binding %s (reason=%s previous=%s new=%s preserved=%s): %s",
+ task.id,
+ change.action,
+ change.reason,
+ change.previous_session_id,
+ change.new_session_id,
+ change.settings_preserved,
+ change.detail,
+ )
+
+ def audit_definition_bindings(self) -> list[tuple[str, str]]:
+ """Report enabled definitions whose pinned session no longer resolves.
+
+ Startup integrity check: a broken binding is otherwise invisible until the
+ next fire, which for a weekly cron is a week of silence.
+ """
+
+ broken: list[tuple[str, str]] = []
+ for task in self.store.list_tasks():
+ if not task.enabled or not task.session_id:
+ continue
+ try:
+ resolve_session_id_target(task.session_id)
+ except UnresolvableSessionTarget as exc:
+ broken.append((task.id, str(exc)))
+ except Exception:
+ # Never let an integrity probe take down startup.
+ logger.debug("Binding audit skipped task %s", task.id, exc_info=True)
+ if broken:
+ logger.warning(
+ "%d harness definition(s) point at an unresolvable agent session: %s",
+ len(broken),
+ "; ".join(f"{task_id} ({reason})" for task_id, reason in broken),
+ )
+ return broken
+
def _reserve_runtime_session(
self,
*,
- agent_name: Optional[str],
+ agent_name: Optional[str] = None,
deliver_key: Optional[str],
metadata: Optional[dict[str, Any]] = None,
workdir: Optional[str] = None,
+ model: Any = _UNSET,
+ reasoning_effort: Any = _UNSET,
+ definition_id: Optional[str] = None,
) -> str:
+ """Reserve a background session for a run.
+
+ ``model`` / ``reasoning_effort`` override the resolved Agent's values. A
+ ``create_once`` rebind passes the snapshot of the session it lost (D3):
+ without them this re-resolves the CURRENT Agent and silently changes the
+ task's settings, because ``run_definitions`` has no column for either.
+
+ Both take ``_UNSET`` rather than ``None`` as "not supplied". An explicit
+ ``None`` means the reclaimed session pinned nothing and must keep pinning
+ nothing; treating that as "not supplied" hands it the Agent's current
+ model, which is a settings change recorded as a settings-preserving
+ recovery. Omitting them is unchanged: the Agent's values are used.
+
+ ``agent_name=None`` (or omitted) means "resolve the scope Agent, else the
+ default Agent" -- the deliberate reset the non-preserving rebind wants.
+
+ ``definition_id`` stamps the reserved row with the reserving definition's id,
+ inside the reservation's own transaction (HFR-276): if the reservation
+ committed, the durable handle committed with it, so an orphan whose
+ ``orphaned_reservations`` record write is later refused by the same fault that
+ refused the release is still recoverable from the row itself. Passed ONLY by
+ the ``create_once`` recovery rebind, whose fires serialize on the pinned
+ session's lock -- a ``create_per_run`` reservation is legitimately unbound and
+ unreferenced between its reserve and its dispatch, and fires of such a
+ definition can overlap, so stamping one would put a live reservation inside
+ the sweep's definition of an orphan.
+ """
scope_id = ""
if isinstance(metadata, dict):
scope_id = str(metadata.get("session_scope_id") or "").strip()
@@ -3136,7 +4028,7 @@ class ScheduledTaskService:
except ValueError:
pass
from config import paths as config_paths
- from core.vibe_agents import VibeAgentStore
+ from core.vibe_agents import AgentUnavailableError, VibeAgentStore
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.sessions_service import SQLiteSessionsService
@@ -3150,11 +4042,48 @@ class ScheduledTaskService:
finally:
agent_store.close()
if agent is None:
- raise ValueError("no enabled default Agent is available for session creation")
+ # Also the deleted/disabled-Agent condition, one step further out: the
+ # default Agent itself is absent or off. Typed for the same reason
+ # ``require_enabled`` is -- it is a settled catalog fact, not a fault --
+ # so the non-preserving rebind attempt keeps degrading to a pause instead
+ # of raising past its narrow catch. Message unchanged.
+ raise AgentUnavailableError(
+ "no enabled default Agent is available for session creation",
+ agent_name=str(resolved_agent_name or ""),
+ reason="no_default",
+ )
agent_backend = agent.backend
+ # Which settings this session pins EXPLICITLY. Storing the value is not
+ # enough: a preserved rebind writes NULL, and NULL already means "inherit
+ # from the Agent at dispatch time" for every session in the table. Without
+ # this marker the rebound session re-inherits at the next fire and D3 is
+ # kept only until the Agent is next edited -- the storage layer preserves
+ # it and the dispatch layer throws it away.
+ from storage.session_reclaim import reconcile_explicit_overrides
+
+ explicit_overrides = [
+ key
+ for key, value in (("model", model), ("reasoning_effort", reasoning_effort))
+ if value is not _UNSET
+ ]
+ # Through the shared reconciler so this writer and every other writer of
+ # these columns agree on the marker's shape.
+ session_metadata = (
+ reconcile_explicit_overrides(None, explicit=explicit_overrides)
+ if explicit_overrides
+ else None
+ )
+ if definition_id:
+ from storage.sessions_service import RESERVED_BY_DEFINITION_METADATA_KEY
+
+ session_metadata = {
+ **(session_metadata or {}),
+ RESERVED_BY_DEFINITION_METADATA_KEY: str(definition_id),
+ }
service = SQLiteSessionsService(config_paths.get_sqlite_state_path())
try:
common = {
+ "metadata": session_metadata,
"agent_backend": agent_backend,
"session_anchor": (
f"{session_anchor_for_target(target)}:runtime_{uuid4().hex[:12]}"
@@ -3163,8 +4092,12 @@ class ScheduledTaskService:
),
"agent_id": agent.id if agent else None,
"agent_name": agent.name if agent else None,
- "model": agent.model if agent else None,
- "reasoning_effort": agent.reasoning_effort if agent else None,
+ "model": (agent.model if agent else None) if model is _UNSET else model,
+ "reasoning_effort": (
+ (agent.reasoning_effort if agent else None)
+ if reasoning_effort is _UNSET
+ else reasoning_effort
+ ),
"workdir": workdir,
"visibility": "background",
}
@@ -3181,6 +4114,297 @@ class ScheduledTaskService:
raise ValueError("failed to reserve runtime session")
return session_id
+ def _release_reserved_session(self, session_id: str, *, reason: str) -> bool:
+ """Give back a session ``_reserve_runtime_session`` handed out and nothing adopted.
+
+ WHY A RECLAIM AND NOT ONE ATOMIC OPERATION. The reservation and the write that
+ adopts it are two different stores with two different engines
+ (``SQLiteSessionsService`` and the definition store), and the standalone
+ reservation also mkdirs a workspace -- a side effect no SQL transaction can roll
+ back. Making them one operation would mean threading a single connection through
+ both stores and still leaving the directory behind on a rollback. Naming the one
+ row this call created and giving it back is smaller, is exact about WHICH row it
+ may touch, and its safety does not depend on two stores continuing to live in the
+ same database.
+
+ Never fatal: this runs on a path that is already reporting a failure to the user,
+ and a leaked reservation must not turn into a second exception on top of it.
+ """
+
+ from config import paths as config_paths
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(config_paths.get_sqlite_state_path())
+ try:
+ return service.release_reserved_agent_session(session_id, reason=reason)
+ except Exception:
+ logger.exception(
+ "Could not release the reserved agent session %s (%s); it is now orphaned",
+ session_id,
+ reason,
+ )
+ return False
+ finally:
+ service.close()
+
+ def _classify_reserved_session(self, session_id: str) -> str:
+ """Which retry fact holds for a recorded reservation (HFR-279).
+
+ The absence-only predecessor of this probe kept an ADOPTED row on the retry
+ record forever: ``release_reserved_agent_session`` answers ``False`` for it,
+ the row is not absent, so every later fire of the original definition took
+ SQLite's write lock again to retry a cleanup that can never succeed. The
+ classification makes the three ``False`` facts explicit -- ``absent`` and
+ ``adopted`` entries are resolved and dropped, only a genuine ``reserved``
+ orphan is worth a release attempt -- and it runs BEFORE the release, so an
+ adopted winner never pays the release's ``BEGIN IMMEDIATE`` for the loser's
+ bookkeeping. ``unknown`` is the fault verdict: a probe that could not read
+ must keep the entry, never guess.
+ """
+
+ from config import paths as config_paths
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(config_paths.get_sqlite_state_path())
+ try:
+ return service.classify_reserved_agent_session(str(session_id))
+ except Exception:
+ logger.exception("Could not classify reserved agent session %s", session_id)
+ return "unknown"
+ finally:
+ service.close()
+
+ def _list_stamped_reservations(self, task_id: str) -> list[str]:
+ """The reservations whose only surviving record is the stamp on their own row.
+
+ HFR-276, the durable half: ``metadata.orphaned_reservations`` is written after
+ a release fails, through the same database, so the fault that refused the
+ release can refuse the record too. The reservation row itself committed before
+ the fault -- that is what makes it an orphan -- and it carries the reserving
+ definition's id in its metadata, stamped inside the same INSERT transaction.
+ This listing recovers those ids. Never raises: the sweep is a cleanup and a
+ fire must not fail because a cleanup could not even be enumerated.
+ """
+
+ from config import paths as config_paths
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(config_paths.get_sqlite_state_path())
+ try:
+ return service.list_reserved_agent_sessions_for_definition(str(task_id))
+ except Exception:
+ logger.exception(
+ "Could not list stamped reserved sessions for harness definition %s", task_id
+ )
+ return []
+ finally:
+ service.close()
+
+ def _track_orphaned_reservation(self, task_id: str, session_id: str, reason: str) -> str:
+ """Record a reservation that could not be released. Answers HOW a later fire
+ finds it: ``"recorded"``, ``"stamped"``, or ``"untracked"``.
+
+ HFR-276. Appends rather than replaces: a definition that keeps losing the same
+ race leaks one row per fire, and each of them needs its own id kept. Idempotent
+ on the id so a retry that fails again does not grow the list.
+
+ The record is the FAST half of the tracking, not the only half. It is written
+ through the same database whose fault may just have refused the release, so
+ the stated production cases -- a locked database, an I/O fault -- can refuse
+ this write too. The reservation's own row already carries the reserving
+ definition's id, stamped inside the reservation's transaction, so a refused
+ record no longer loses the id: as long as the definition exists, its next fire
+ sweeps the stamped rows (``_retry_orphaned_reservations``) and recovers it from
+ the row itself -- that is ``"stamped"``. ``"untracked"`` is only the case with
+ no next fire: the definition itself is gone (or its mirror was lost to the same
+ fault, in which case the HFR-277 reload restores it and the sweep still runs --
+ this answer under-claims rather than over-claims).
+ """
+
+ entries = self.store.list_orphaned_reservations(task_id)
+ if any(str(entry.get("session_id") or "") == str(session_id) for entry in entries):
+ return "recorded"
+ entries.append({"session_id": str(session_id), "reason": reason, "at": _utc_now_iso()})
+ # ``record_orphaned_reservations`` -> ``_write_task`` RAISES on a faulted write
+ # (HFR-272) after reloading the mirror; only a guard REFUSAL comes back as
+ # ``False``. This caller sits on a path that is already reporting a failure to
+ # the user, and the stated production fault -- a locked database -- is exactly
+ # the one that raises here, so both answers must land in the same "the record
+ # did not happen" branch instead of the exception unwinding past the notice.
+ try:
+ recorded = self.store.record_orphaned_reservations(task_id, entries)
+ except Exception:
+ logger.exception(
+ "Could not store the orphan record for reserved agent session %s on "
+ "harness definition %s",
+ session_id,
+ task_id,
+ )
+ recorded = False
+ if recorded:
+ logger.warning(
+ "Recorded reserved agent session %s as orphaned on harness definition %s (%s); "
+ "the next run retries the release",
+ session_id,
+ task_id,
+ reason,
+ )
+ return "recorded"
+ if self.store.get_task(task_id) is not None:
+ logger.warning(
+ "Reserved agent session %s could not be released, and the orphan record on "
+ "harness definition %s could not be stored either (%s); the row itself is "
+ "stamped with the definition id, so the next run recovers it from that stamp",
+ session_id,
+ task_id,
+ reason,
+ )
+ return "stamped"
+ logger.error(
+ "Reserved agent session %s could not be released OR recorded against harness "
+ "definition %s (%s), and that definition no longer exists, so no later run will "
+ "look for it; it is a live, unreferenced session and its row's definition stamp "
+ "and this log line are the only records of its id",
+ session_id,
+ task_id,
+ reason,
+ )
+ return "untracked"
+
+ def _retry_orphaned_reservations(self, task: ScheduledTask) -> None:
+ """Finish a release that failed on an earlier fire of this definition.
+
+ The retry is bounded and self-limiting on purpose: it runs only once per fire
+ and only against ids this definition's own recovery reserved -- the ones on the
+ ``orphaned_reservations`` record, plus the ones whose record write itself was
+ refused and whose only surviving handle is the definition-id stamp on their own
+ row (HFR-276). Entries are dropped when the row is gone or was adopted after
+ all, released when it is still a reservation, and kept when the release failed
+ again or the classification could not read, so a database that is down keeps
+ the fact rather than losing it. Never raises: a fire must not fail because a
+ cleanup did.
+
+ CLASSIFY, THEN RELEASE (HFR-279). The release's own ``False`` conflates "gone",
+ "adopted" and "faulted", and the absence-only probe that used to disambiguate
+ it resolved only the first: an adopted reservation stayed on the record forever
+ and every fire re-took SQLite's write lock to retry a cleanup that can never
+ succeed. The classification runs first, without the write lock, so an adopted
+ winner's row is never even read under ``BEGIN IMMEDIATE`` again -- it is
+ resolved off the record WITHOUT being touched. Only a row that is still
+ empty-native and unreferenced is worth the guarded release, whose predicates
+ re-assert both facts under the write lock, so a classification that raced an
+ adoption destroys nothing: the release backs off, the entry stays, and the next
+ fire classifies it as adopted and drops it.
+ """
+
+ from storage.sessions_service import (
+ RESERVATION_ABSENT,
+ RESERVATION_ADOPTED,
+ RESERVATION_RESERVED,
+ )
+
+ entries = task.metadata.get(ORPHANED_RESERVATIONS_METADATA_KEY) if isinstance(task.metadata, dict) else None
+ if not isinstance(entries, list):
+ entries = []
+ recorded_ids = {
+ str(entry.get("session_id") or "").strip()
+ for entry in entries
+ if isinstance(entry, dict)
+ }
+ # The durable backstop: reservations this definition stamped but whose record
+ # write was refused by the same fault that refused the release. Recovered from
+ # the rows themselves, appended after the recorded entries so a recorded id is
+ # handled exactly once.
+ stamped = [
+ {"session_id": session_id}
+ for session_id in self._list_stamped_reservations(task.id)
+ if session_id not in recorded_ids
+ ]
+ if not entries and not stamped:
+ return
+ remaining: list[dict[str, Any]] = []
+ released: list[str] = []
+ for entry in [*entries, *stamped]:
+ if not isinstance(entry, dict):
+ continue
+ session_id = str(entry.get("session_id") or "").strip()
+ if not session_id:
+ continue
+ reason = str(entry.get("reason") or "") or f"the rebind of harness definition {task.id} was refused"
+ state = self._classify_reserved_session(session_id)
+ if state in (RESERVATION_ABSENT, RESERVATION_ADOPTED):
+ if state == RESERVATION_ADOPTED:
+ logger.info(
+ "Reserved agent session %s recorded on harness definition %s was "
+ "adopted and is somebody's live binding; dropping it from the "
+ "retry record without touching it",
+ session_id,
+ task.id,
+ )
+ released.append(session_id)
+ elif state == RESERVATION_RESERVED and self._release_reserved_session(
+ session_id, reason=reason
+ ):
+ released.append(session_id)
+ else:
+ # Still a reservation but the release failed, or the classification
+ # could not read: both keep the entry. A stamped id that stays here is
+ # promoted onto the record, so the fact survives even if the row's
+ # stamp is somehow lost later.
+ remaining.append(dict(entry))
+ if not released and not stamped:
+ return
+ # Same shape as ``_track_orphaned_reservation``: a faulted write RAISES out of
+ # the store (HFR-272) and this method promises a fire never fails because a
+ # cleanup did, so the raise and the refusal are one branch here.
+ try:
+ recorded = self.store.record_orphaned_reservations(task.id, remaining)
+ except Exception:
+ logger.exception(
+ "Could not update the orphan record on harness definition %s", task.id
+ )
+ recorded = False
+ # Keep the object THIS fire is acting from in step with what the sweep just
+ # established, on BOTH branches: the store write may have reloaded the cache
+ # out from under it (``record_orphaned_reservations`` starts with
+ # ``maybe_reload``, and a raised write reloads too), and the very next thing a
+ # ``create_once`` recovery does is hand ``task.metadata`` back to
+ # ``update_task`` as a full-row payload. Left unreconciled on the failure
+ # branch, that later write would durably RE-RECORD entries this very fire just
+ # resolved. ``remaining`` is correct either way: it holds exactly the entries
+ # still worth a retry, so a later full-row write that carries it repairs the
+ # record the failed write left stale.
+ self._forget_orphaned_reservations(task, remaining)
+ if recorded:
+ if released:
+ logger.info(
+ "Resolved orphaned reservation(s) %s recorded on harness definition %s",
+ ", ".join(released),
+ task.id,
+ )
+ return
+ # The cleanup landed but the bookkeeping did not, so the durable entries stay
+ # and the next fire retries them: ``release_reserved_agent_session`` names one
+ # row by id and an already-released id simply reports "gone" under the
+ # classification, so a repeat is a no-op rather than a second delete. A stamped
+ # entry that could not be promoted is equally safe: its stamp still names this
+ # definition, so the next sweep finds it again from the row itself.
+ logger.warning(
+ "Resolved orphaned reservation(s) %s for harness definition %s, but the "
+ "record could not be updated; the next run re-checks them",
+ ", ".join(released) or "(none)",
+ task.id,
+ )
+
+ @staticmethod
+ def _forget_orphaned_reservations(task: ScheduledTask, remaining: list[dict[str, Any]]) -> None:
+ metadata = dict(task.metadata) if isinstance(task.metadata, dict) else {}
+ if remaining:
+ metadata[ORPHANED_RESERVATIONS_METADATA_KEY] = [dict(entry) for entry in remaining]
+ else:
+ metadata.pop(ORPHANED_RESERVATIONS_METADATA_KEY, None)
+ task.metadata = metadata
+
def _resolve_scope_agent_target(self, deliver_key: str) -> "_ScopeAgentTarget":
try:
target = parse_scope_id(deliver_key)
diff --git a/core/services/agent_run_target.py b/core/services/agent_run_target.py
index 3b8c1cab3..09f4b601b 100644
--- a/core/services/agent_run_target.py
+++ b/core/services/agent_run_target.py
@@ -26,7 +26,11 @@ from core.message_context import (
)
from config.v2_settings import make_thread_native_id
from modules.im import MessageContext
-from storage.agent_session_rows import create_agent_session_row, utc_now_iso
+from storage.agent_session_rows import (
+ create_agent_session_row,
+ get_or_create_agent_session_row,
+ utc_now_iso,
+)
from storage.models import agent_sessions, scope_settings, scopes
logger = logging.getLogger(__name__)
@@ -273,7 +277,11 @@ def resolve_agent_run_target(
),
)
- new_session_id = create_agent_session_row(
+ # Keyed get-or-create: the SELECT above took no write lock, so a concurrent
+ # inbound message on the same thread can win this (scope_id, session_anchor)
+ # slot between then and now. Losing that race must re-read the winner's row,
+ # not surface the UNIQUE violation to the user.
+ new_session_id, _created = get_or_create_agent_session_row(
conn,
scope_id=str(scope_id),
session_anchor=anchor,
@@ -286,6 +294,35 @@ def resolve_agent_run_target(
workdir=resolved_new_workdir,
metadata={"created_via": "agent_run_target", "source": source, "legacy_scope_key": session_key},
)
+ if new_session_id is None:
+ # NO usable session: the keyed get-or-create resolved onto an existing row
+ # for this anchor, tried to claim it for this turn's backend, and lost that
+ # race to a writer that ARCHIVED the row. An archive is terminal and
+ # vacates the anchor, so there is nothing to resolve onto -- and minting a
+ # replacement row here would be a second write decided from the same stale
+ # snapshot the claim was just refused for.
+ #
+ # Degrade to the UNPERSISTED target, the same answer this function already
+ # gives when there is no scope to persist against: the turn runs with a
+ # resolved workdir and Agent route but no ``agent_session_id``, which every
+ # consumer already tolerates. Without this the row read below -- a
+ # ``.one()`` on ``id IS NULL`` -- would raise ``NoResultFound`` out of
+ # inbound message handling.
+ return _cache_target(
+ context,
+ _unpersisted_target(
+ scope_row,
+ controller=controller,
+ platform=platform,
+ settings_key=settings_key,
+ session_key=session_key,
+ anchor=anchor,
+ source=source,
+ workdir=resolved_new_workdir,
+ workdir_source="scope_read",
+ agent_target=agent_target,
+ ),
+ )
created = conn.execute(
select(
agent_sessions,
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index f92b860de..7a15757e9 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -156,6 +156,7 @@ def reserve_forked_session(
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.models import agent_sessions
+ from storage.session_reclaim import reconcile_explicit_overrides
path = db_path or paths.get_sqlite_state_path()
if db_path is None:
@@ -261,6 +262,38 @@ def reserve_forked_session(
if target_scope_id != row["scope_id"]:
metadata["fork_target_scope_id"] = target_scope_id
metadata["legacy_scope_key"] = target_scope_id
+ # The copied metadata carries the SOURCE session's explicit-override
+ # marker. Whether that claim is still TRUE depends on whether this fork
+ # copied the column or replaced it, and the two cases are opposites:
+ #
+ # - OMITTED (``model is None``): ``target_model`` above is
+ # ``row["model"]`` -- the column is copied verbatim, so the source's
+ # marker is a true claim about the value the fork now holds and must
+ # be PRESERVED. Dropping it converts a fork of an explicit-null
+ # session into an ordinary inherited-null one, and the next Agent
+ # default change silently hands the fork settings the source had
+ # deliberately pinned away.
+ # - SUPPLIED: the fork owns the setting. It is an explicit pin only
+ # when the resolved value is empty (pin nothing); a concrete value
+ # needs no marker, because dispatch reads a non-null column anyway.
+ #
+ # Only the supplied fields are reconciled. This is the inverse of the
+ # first version of this guard, which cleared exactly the copied fields.
+ resolved_forked_settings = {"model": target_model, "reasoning_effort": target_effort}
+ supplied_settings = [
+ name
+ for name, value in (("model", model), ("reasoning_effort", reasoning_effort))
+ if value is not None
+ ]
+ metadata = reconcile_explicit_overrides(
+ metadata,
+ cleared=[
+ name for name in supplied_settings if resolved_forked_settings[name] is not None
+ ],
+ explicit=[
+ name for name in supplied_settings if resolved_forked_settings[name] is None
+ ],
+ )
session_id = create_agent_session_row(
conn,
scope_id=target_scope_id,
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index 088aaeb5c..1d5ececaf 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -31,6 +31,35 @@ SUPPORTED_AGENT_BACKENDS = {"codex", "claude", "opencode"}
_UNSET = object()
+class AgentUnavailableError(ValueError):
+ """The named Agent cannot be used: it does not exist, or it is disabled.
+
+ A TYPED contract for the one condition a caller may legitimately degrade for.
+ Resolution can fail two ways that look identical as strings but must not be
+ treated identically: the Agent is GONE (the user deleted or disabled it — a
+ settled fact, so falling back to scope/default settings is the recovery), or
+ the CATALOG could not be read (SQLite contention, a migration failure, a
+ filesystem error — transient, and falling back would convert an infrastructure
+ fault into a permanent settings change on the definition that retried).
+
+ ``core/scheduled_tasks.py``'s preserved ``create_once`` rebind is the caller
+ that made the distinction load-bearing: it catches this type NARROWLY, so an
+ operational fault propagates with the definition's route and lifecycle
+ untouched instead of being recorded as "settings could not be recovered".
+
+ Subclasses ``ValueError`` so every existing ``except ValueError`` caller — the
+ CLI, the UI server, the controller's route resolution — keeps its current
+ behaviour and its current message.
+ """
+
+ def __init__(self, message: str, *, agent_name: str, reason: str) -> None:
+ super().__init__(message)
+ #: The name as requested, which for ``missing`` is all there is.
+ self.agent_name = str(agent_name)
+ #: ``"missing"``, ``"disabled"``, or ``"no_default"``.
+ self.reason = str(reason)
+
+
def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -141,13 +170,19 @@ class VibeAgentStore:
def require(self, name: str) -> VibeAgent:
agent = self.get(name)
if agent is None:
- raise ValueError(f"agent '{name}' not found")
+ # Same message as before, now with a type: "this Agent is gone" is the
+ # only resolution failure a caller may degrade for, and it has to be
+ # distinguishable from "the catalog could not be read" (which raises
+ # OperationalError from ``get`` and now propagates past the narrow catch).
+ raise AgentUnavailableError(f"agent '{name}' not found", agent_name=name, reason="missing")
return agent
def require_enabled(self, name: str) -> VibeAgent:
agent = self.require(name)
if not agent.enabled:
- raise ValueError(f"agent '{agent.name}' is disabled")
+ raise AgentUnavailableError(
+ f"agent '{agent.name}' is disabled", agent_name=agent.name, reason="disabled"
+ )
return agent
def create(
diff --git a/core/watches.py b/core/watches.py
index 8fe253e2a..c72a95a8a 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -32,9 +32,11 @@ from core.process_isolation import (
terminate_process_group_by_pgid,
terminate_process_tree_by_pid,
)
-from core.scheduled_tasks import TaskExecutionStore
+from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStore
from storage.background import (
DEFINITION_CYCLE_COLUMNS,
+ DefinitionWriteConflict,
+ DefinitionWriteExpectation,
SQLiteBackgroundTaskStore,
definition_resume_clear_columns,
)
@@ -216,6 +218,9 @@ class ManagedWatchStore:
self._sqlite = SQLiteBackgroundTaskStore() if path is None else None
self._signature: Optional[tuple[int, int, int]] = None
self._watches: dict[str, ManagedWatch] = {}
+ #: Set when a failed write left this mirror INCOMPLETE, cleared by the reload
+ #: that repairs it. See ``maybe_reload`` and ``_reload_after_lost_write``.
+ self._reload_required = False
self.load()
def load(self) -> None:
@@ -224,10 +229,12 @@ class ManagedWatchStore:
item["id"]: ManagedWatch.from_dict(item)
for item in self._sqlite.list_watches()
}
+ self._reload_required = False
return
if not self.path.exists():
self._watches = {}
self._signature = None
+ self._reload_required = False
return
try:
payload = json.loads(self.path.read_text(encoding="utf-8"))
@@ -246,15 +253,45 @@ class ManagedWatchStore:
watches[watch.id] = watch
self._watches = watches
self._signature = _path_signature(self.path)
+ self._reload_required = False
def maybe_reload(self) -> bool:
+ """Refresh the mirror when the database changed -- or when WE know it is stale.
+
+ HFR-277, the task store's twin. The probe behind ``self._sqlite.maybe_reload``
+ is ``PRAGMA data_version``, which only moves for a COMMITTED write by another
+ connection. The write that drops an entry in ``_reload_after_lost_write`` ROLLED
+ BACK, so data_version is unchanged and every later call here answered "nothing
+ changed": the dropped watch stayed invisible to ``reconcile_watches`` -- which
+ picks what runs out of exactly this dict -- while its row sat enabled in SQLite,
+ durably, until a restart or an unrelated commit bumped the counter.
+
+ ``_reload_required`` is in-process state rather than a database column on
+ purpose: it describes THIS mirror, not the data, and a restart reloads from
+ SQLite anyway, so there is nothing for it to survive. Making it durable would
+ also mean writing to the database that was just proven unwritable. Only ``load``
+ clears it, so a reload that fails again is retried on every later tick.
+ """
+
if self._sqlite is not None:
changed = self._sqlite.maybe_reload()
+ if self._reload_required:
+ try:
+ self.load()
+ except Exception:
+ # Still unreachable. Keep the flag and the incomplete mirror, and
+ # report "nothing changed" -- the retry is the next tick's.
+ logger.exception(
+ "Could not reload managed watches after a lost write; the live "
+ "store stays incomplete until a later attempt succeeds"
+ )
+ return False
+ return True
if changed:
self.load()
return changed
signature = _path_signature(self.path)
- if signature == self._signature:
+ if signature == self._signature and not self._reload_required:
return False
self.load()
return True
@@ -317,13 +354,128 @@ class ManagedWatchStore:
def get_watch(self, watch_id: str) -> Optional[ManagedWatch]:
return self._watches.get(watch_id)
+ @staticmethod
+ def _read_state(watch: ManagedWatch) -> DefinitionWriteExpectation:
+ """The guarded state a full-row payload for ``watch`` is derived from.
+
+ The task-store twin, for the same reason: ``ManagedWatch`` is a mirror of the
+ stored row, every writer below edits a few fields and writes them ALL back,
+ and the dataclass has no ``deleted_at`` to write back at all.
+ """
+
+ return DefinitionWriteExpectation.from_read(
+ session_id=watch.session_id,
+ enabled=watch.enabled,
+ deleted_at=None,
+ metadata=watch.metadata,
+ )
+
+ @property
+ def sqlite_backend(self) -> Optional[SQLiteBackgroundTaskStore]:
+ """The SQLite backend behind this store, or ``None`` for the file backend.
+
+ The guard ``_write_watch`` applies lives in SQLite; the file backend has no
+ compare-and-set at all. Exposed so a caller can ask whether a guarded stamp and
+ an outbox row can be committed together (HFR-269).
+ """
+
+ return self._sqlite
+
+ def _write_watch(
+ self,
+ watch: ManagedWatch,
+ expect: DefinitionWriteExpectation,
+ *,
+ queued_run: Optional[dict[str, Any]] = None,
+ ) -> bool:
+ """Persist a whole watch row; ``False`` means the guard refused the write.
+
+ ``queued_run`` is an ``agent_runs`` outbox payload this write AUTHORISES; it is
+ committed in the SAME transaction as the row (HFR-269), so a refusal or a
+ failure leaves neither behind. Only the SQLite backend can do that, and passing
+ one to the file backend is a caller bug -- see ``sqlite_backend``.
+
+ EVERY way this write can fail to land reloads the mirror (HFR-271). This store is
+ a write-through cache: each caller mutates the cached ``ManagedWatch`` and hands
+ the whole row here, so if the write does not stick, the mutation must not either.
+ Reloading on the ``False`` return alone was half the job -- a raised exception
+ rolls the transaction back just as completely, and left the process serving edits
+ the database never accepted. ``reconcile_watches`` chooses which watches keep
+ running from this dict, ``_read_state`` derives the NEXT compare-and-set's
+ expectation from it, and ``_watch_store_call`` swallows the exception, so nothing
+ downstream would ever have corrected it.
+ """
+
+ try:
+ if self._sqlite is None:
+ if queued_run is not None:
+ raise ValueError(
+ "a file-backed watch store cannot commit a queued run with the watch row"
+ )
+ self._save()
+ return True
+ if queued_run is None:
+ landed = self._sqlite.upsert_watch(watch.to_dict(), expect=expect)
+ else:
+ landed = self._sqlite.upsert_watch_with_queued_run(
+ watch.to_dict(), expect=expect, run_payload=queued_run
+ )
+ except Exception:
+ self._reload_after_lost_write(watch.id)
+ raise
+ if landed:
+ return True
+ self.load()
+ return False
+
+ def _reload_after_lost_write(self, watch_id: str) -> None:
+ """Drop a mirror entry the database did not accept, reloading if it can.
+
+ The reload itself can fail -- the fault that killed the write is usually still
+ there. Keeping the mutated entry would be the worse answer of the two, so it is
+ dropped: an absent watch reads as "gone" to ``reconcile_watches`` and stops that
+ watch, where a stale one keeps it running against state the database never had,
+ and ``maybe_reload`` restores it as soon as the database is reachable again --
+ which it can only do because dropping the entry also marks the mirror as needing
+ an UNCONDITIONAL reload (HFR-277). The failed write rolled back, so ``PRAGMA
+ data_version`` never moved and the probe alone would report "nothing changed"
+ forever.
+ """
+
+ try:
+ self.load()
+ except Exception:
+ logger.exception(
+ "Could not reload managed watches after a failed write; dropping the "
+ "stale mirror entry for %s",
+ watch_id,
+ )
+ self._watches.pop(watch_id, None)
+ self._signature = None
+ self._reload_required = True
+
def upsert_watch(self, watch: ManagedWatch) -> ManagedWatch:
+ """Create or adopt a whole watch row (unguarded: the payload is not a re-read).
+
+ The mirror rolls back with the write here too (HFR-275). This is the one entry
+ point that can add an id the database has never seen, and a phantom is worse than
+ a stale edit: ``reconcile_watches`` would START a watch whose creation the caller
+ was told had FAILED, spawning its command and posting its output on every tick,
+ with no durable row to stop it and nothing to reload it away.
+ """
+
watch.updated_at = _utc_now_iso()
self._watches[watch.id] = watch
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return watch
- self._save()
+ try:
+ if self._sqlite is not None:
+ # No ``expect``: the create/adopt entry point (``add_watch``), whose
+ # payload is not derived from a stored row.
+ self._sqlite.upsert_watch(watch.to_dict())
+ return watch
+ self._save()
+ except Exception:
+ self._reload_after_lost_write(watch.id)
+ raise
return watch
def add_watch(
@@ -372,17 +524,30 @@ class ManagedWatchStore:
return self.upsert_watch(watch)
def remove_watch(self, watch_id: str) -> bool:
+ """Delete a watch; the mirror rolls back with the delete (HFR-275).
+
+ The safer direction of the same class -- an entry dropped here reads as "gone"
+ and stops the watch -- but silently, and NOT self-healing: with the row still
+ there and unchanged, ``maybe_reload`` sees no external write, so the watch the
+ user was told could not be deleted just stops until the process restarts.
+ """
+
if watch_id not in self._watches:
return False
del self._watches[watch_id]
- if self._sqlite is not None:
- self._sqlite.remove_task(watch_id)
- return True
- self._save()
+ try:
+ if self._sqlite is not None:
+ self._sqlite.remove_task(watch_id)
+ return True
+ self._save()
+ except Exception:
+ self._reload_after_lost_write(watch_id)
+ raise
return True
def set_enabled(self, watch_id: str, enabled: bool) -> ManagedWatch:
watch = self._watches[watch_id]
+ expect = self._read_state(watch)
if enabled and not watch.enabled:
# Same field split the storage layer applies to the Harness UI's
# toggle, so the two doorways cannot drift apart again.
@@ -392,10 +557,11 @@ class ManagedWatchStore:
)
watch.enabled = enabled
watch.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return watch
- self._save()
+ if not self._write_watch(watch, expect):
+ # Same as the task side: this payload also restores ``last_error`` and the
+ # Session binding, so a pause/resume that lost to a teardown must fail
+ # loudly rather than quietly undo it.
+ raise DefinitionWriteConflict(watch_id, definition_type="watch")
return watch
def update_watch(
@@ -422,6 +588,9 @@ class ManagedWatchStore:
metadata: Optional[dict[str, Any]] = None,
) -> ManagedWatch:
watch = self._watches[watch_id]
+ # Captured before the first mutation: the state ``vibe watch update`` read and
+ # resolved its payload from.
+ expect = self._read_state(watch)
if mode != watch.mode:
# A mode change starts a new lifecycle. Completion and failure
# metadata from the old mode remains available in run history, but
@@ -449,10 +618,10 @@ class ManagedWatchStore:
if metadata is not None:
watch.metadata = dict(metadata)
watch.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return watch
- self._save()
+ if not self._write_watch(watch, expect):
+ # The edit did NOT land. ``cmd_watch_update`` turns this into a non-zero
+ # exit with an error payload instead of echoing an unwritten watch.
+ raise DefinitionWriteConflict(watch_id, definition_type="watch")
return watch
@staticmethod
@@ -467,14 +636,13 @@ class ManagedWatchStore:
watch = self._watches.get(watch_id)
if watch is None:
return False
+ expect = self._read_state(watch)
watch.last_started_at = _utc_now_iso()
watch.last_error = None
watch.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return True
- self._save()
- return True
+ # A runtime stamp: a lost write is reported by the return value, not by an
+ # exception through the supervisor loop.
+ return self._write_watch(watch, expect)
def mark_cycle_result(
self,
@@ -484,11 +652,21 @@ class ManagedWatchStore:
error: Optional[str],
event_detected: bool = False,
disable: bool = False,
+ queued_run: Optional[dict[str, Any]] = None,
) -> bool:
+ """Stamp a cycle's outcome; ``False`` means the store refused the write.
+
+ ``queued_run`` is the completion-hook outbox row this stamp AUTHORISES. Passing
+ it makes the stamp and the hook ONE transaction (HFR-269): both land or neither
+ does, so no teardown can commit between them and no failure can disable a
+ ``once`` watch while losing the hook that tells the user it finished.
+ """
+
self.maybe_reload()
watch = self._watches.get(watch_id)
if watch is None:
return False
+ expect = self._read_state(watch)
now = _utc_now_iso()
# Retirement is state, not a conclusion drawn from cycle history.
# Only the cycle that changes enabled -> disabled may write it. A cycle
@@ -505,11 +683,10 @@ class ManagedWatchStore:
if disable:
watch.enabled = False
watch.updated_at = _utc_now_iso()
- if self._sqlite is not None:
- self._sqlite.upsert_watch(watch.to_dict())
- return True
- self._save()
- return True
+ # Guarded for the reason ``mark_task_result`` is: a cycle result landing after a
+ # ``/new`` reclaim would otherwise re-enable the watch and restore the binding
+ # the teardown cleared.
+ return self._write_watch(watch, expect, queued_run=queued_run)
class WatchRuntimeStateStore:
@@ -564,6 +741,30 @@ class WatchRuntimeStateStore:
return payload
+def _shared_run_ledger_backend(
+ store: ManagedWatchStore,
+ request_store: TaskExecutionStore,
+) -> Optional[SQLiteBackgroundTaskStore]:
+ """The one SQLite database holding BOTH the watch definitions and the run outbox.
+
+ ``None`` when the two stores cannot share a transaction, which is what decides
+ whether a guarded stamp and the hook it authorises can be committed together
+ (HFR-269). In production both stores default to the same
+ ``paths.get_sqlite_state_path()`` database, so the answer is always the shared
+ backend; file-backed stores (tests, legacy state) keep watches in a JSON file and
+ runs in a directory of JSON files, and the ``db_path`` comparison also refuses two
+ SQLite stores that happen to point at different databases.
+ """
+
+ watch_backend = store.sqlite_backend
+ run_backend = request_store.sqlite_backend
+ if watch_backend is None or run_backend is None:
+ return None
+ if watch_backend.db_path != run_backend.db_path:
+ return None
+ return watch_backend
+
+
@dataclass
class _CycleResult:
exit_code: int
@@ -1040,13 +1241,41 @@ class ManagedWatchService:
exc_info=True,
)
- def _watch_store_call(self, watch_id: str, operation: str, callback) -> bool:
+ def _watch_store_call(self, watch_id: str, operation: str, callback, *, guarded: bool = False) -> bool:
+ """Run a store call for ``watch_id``; ``False`` means "do not proceed".
+
+ TWO ways a store call can fail to happen, and the supervisor has to stop for
+ BOTH. An exception fuses the store, as before. ``guarded=True`` says the
+ callback's OWN return value is the answer as well: ``mark_cycle_start`` and
+ ``mark_cycle_result`` are compare-and-set writes (HFR-261) that return
+ ``False`` when a ``/new`` reclaim or an archive committed after the payload
+ was read, and this wrapper used to DISCARD that -- ``callback(); return True``
+ reported a refused write to the loop as a landed one, so the cycle went on to
+ spawn its command and enqueue its hook against a definition the database had
+ already torn down.
+
+ Not the default, because a ``False`` return is not universally a refusal:
+ ``maybe_reload`` returns ``False`` for "nothing changed", which is the common
+ case and must not stop the watch. Only the guarded writers opt in.
+ """
+
try:
- callback()
- return True
+ result = callback()
except Exception as exc:
self._fuse_store_after_error(operation, exc, watch_id=watch_id)
return False
+ if guarded and result is False:
+ # NOT a store error: the row is fine, this write simply lost to a
+ # concurrent lifecycle change. Fusing would disable reconciliation for a
+ # healthy database, so the watch is stopped and the store left alone.
+ logger.warning(
+ "Watch %s stopping: the store refused %s because the definition's "
+ "Session binding, enabled state, deletion or reclaim snapshot changed",
+ watch_id,
+ operation,
+ )
+ return False
+ return True
def _current_asyncio_task(self) -> Optional["asyncio.Task[Any]"]:
try:
@@ -1095,27 +1324,22 @@ class ManagedWatchService:
elapsed = asyncio.get_running_loop().time() - lifetime_started
remaining_lifetime = watch.lifetime_timeout_seconds - elapsed
if remaining_lifetime <= 0:
- self._enqueue_hook(
+ # ONE DECISION (HFR-269), not a stamp followed by a hook. See
+ # ``_commit_cycle_result``.
+ self._commit_cycle_result(
watch,
- prefix=watch.message or watch.prefix or "Watch stopped after reaching its lifetime timeout.",
- body=(
- f"Watch '{watch.name or watch.id}' reached its lifetime timeout after "
- f"{int(watch.lifetime_timeout_seconds)} second(s)."
- ),
- )
- self._watch_store_call(
- watch.id,
- "mark_cycle_result",
# Running out of lifetime is a timeout, and the row has
# to be able to say so: ``definition_lifecycle_detail``
# reads the exit code, and a ``None`` here made the
# supervisor's own deadline read as a normal ending.
# 124 is the same convention the per-cycle timeout uses.
- lambda: self.store.mark_cycle_result(
- watch.id,
- exit_code=124,
- error=None,
- disable=True,
+ exit_code=124,
+ error=None,
+ disable=True,
+ prefix=watch.message or watch.prefix or "Watch stopped after reaching its lifetime timeout.",
+ body=(
+ f"Watch '{watch.name or watch.id}' reached its lifetime timeout after "
+ f"{int(watch.lifetime_timeout_seconds)} second(s)."
),
)
return
@@ -1127,7 +1351,17 @@ class ManagedWatchService:
else:
cycle_timeout = watch.timeout_seconds
- if not self._watch_store_call(watch.id, "mark_cycle_start", lambda: self.store.mark_cycle_start(watch.id)):
+ # ``guarded=True``: a REFUSED start stamp stops the cycle here, BEFORE
+ # ``_run_cycle`` spawns the waiter and before any hook is enqueued. The
+ # refusal means a teardown (``/new`` reclaim, archive) committed after this
+ # loop read the watch, so the definition it is about to run no longer
+ # exists in the state this iteration decided from.
+ if not self._watch_store_call(
+ watch.id,
+ "mark_cycle_start",
+ lambda: self.store.mark_cycle_start(watch.id),
+ guarded=True,
+ ):
return
cwd_error = _missing_watch_cwd_error(watch)
if cwd_error:
@@ -1153,19 +1387,15 @@ class ManagedWatchService:
return
if result.exit_code == 0:
- prompt = _build_prompt(watch.message or watch.prefix, result.stdout)
- if prompt:
- self._enqueue_hook(watch, prompt=prompt)
- if not self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(
- watch.id,
- exit_code=0,
- error=None,
- event_detected=True,
- disable=watch.mode == "once",
- ),
+ # Building the prompt is pure; the stamp and the hook it authorises are
+ # committed together (HFR-269).
+ if not self._commit_cycle_result(
+ watch,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=watch.mode == "once",
+ prompt=_build_prompt(watch.message or watch.prefix, result.stdout),
):
return
if watch.mode != "forever":
@@ -1175,52 +1405,44 @@ class ManagedWatchService:
if result.timed_out or result.exit_code == 124:
error_text = "timed out"
if watch.mode == "forever" and 124 in set(watch.retry_exit_codes):
- if not self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(watch.id, exit_code=124, error=error_text, disable=False),
+ # A retry authorises no hook: the watch keeps running, and there is
+ # nothing to tell the user yet.
+ if not self._commit_cycle_result(
+ watch, exit_code=124, error=error_text, disable=False
):
return
await asyncio.sleep(watch.retry_delay_seconds)
continue
- self._enqueue_failure_hook(
+ self._commit_cycle_result(
watch,
exit_code=124,
- error_text=f"Watch timed out after {int(cycle_timeout)} second(s).",
- )
- self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(watch.id, exit_code=124, error=error_text, disable=True),
+ error=error_text,
+ disable=True,
+ prefix=watch.message or watch.prefix,
+ body=_failure_hook_body(
+ watch,
+ exit_code=124,
+ error_text=f"Watch timed out after {int(cycle_timeout)} second(s).",
+ ),
)
return
error_text = _squash_error(result.stderr) or f"watch command exited with status {result.exit_code}"
if watch.mode == "forever" and result.exit_code in set(watch.retry_exit_codes):
- if not self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(
- watch.id,
- exit_code=result.exit_code,
- error=error_text,
- disable=False,
- ),
+ if not self._commit_cycle_result(
+ watch, exit_code=result.exit_code, error=error_text, disable=False
):
return
await asyncio.sleep(watch.retry_delay_seconds)
continue
- self._enqueue_failure_hook(watch, exit_code=result.exit_code, error_text=error_text)
- self._watch_store_call(
- watch.id,
- "mark_cycle_result",
- lambda: self.store.mark_cycle_result(
- watch.id,
- exit_code=result.exit_code,
- error=error_text,
- disable=True,
- ),
+ self._commit_cycle_result(
+ watch,
+ exit_code=result.exit_code,
+ error=error_text,
+ disable=True,
+ prefix=watch.message or watch.prefix,
+ body=_failure_hook_body(watch, exit_code=result.exit_code, error_text=error_text),
)
return
@@ -1298,18 +1520,24 @@ class ManagedWatchService:
timed_out=timed_out,
)
- def _enqueue_hook(
+ def _hook_request(
self,
watch: ManagedWatch,
*,
prompt: Optional[str] = None,
prefix: Optional[str] = None,
body: Optional[str] = None,
- ) -> None:
+ ) -> Optional[TaskExecutionRequest]:
+ """The cycle's completion hook, BUILT and not yet durable.
+
+ ``None`` when there is no prompt to deliver. Composing the request is pure;
+ ``_commit_cycle_result`` decides where it becomes durable.
+ """
+
final_prompt = prompt or _build_prompt(prefix, body)
if not final_prompt:
- return
- self.request_store.enqueue_hook_send(
+ return None
+ return self.request_store.build_hook_send(
session_key=watch.session_key,
session_id=watch.session_id,
post_to=watch.post_to,
@@ -1323,41 +1551,98 @@ class ManagedWatchService:
metadata=watch.metadata,
)
- def _enqueue_failure_hook(self, watch: ManagedWatch, *, exit_code: int, error_text: str) -> None:
- watch_label = watch.name or watch.id
- if exit_code == 124:
- body = (
- f"Watch '{watch_label}' stopped because the waiter timed out.\n"
- f"Check whether the timeout is too short or the waiter is blocked, then recreate the watch if monitoring should continue.\n"
- f"Details: {error_text}"
- )
- else:
- body = (
- f"Watch '{watch_label}' stopped because the waiter exited with code {exit_code}.\n"
- f"Review the error below, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.\n"
- f"Error: {error_text}"
- )
- self._enqueue_hook(watch, prefix=watch.message or watch.prefix, body=body)
-
- def _stop_watch_for_missing_cwd(self, watch: ManagedWatch, *, error_text: str) -> None:
+ def _commit_cycle_result(
+ self,
+ watch: ManagedWatch,
+ *,
+ exit_code: Optional[int],
+ error: Optional[str],
+ event_detected: bool = False,
+ disable: bool = False,
+ prompt: Optional[str] = None,
+ prefix: Optional[str] = None,
+ body: Optional[str] = None,
+ ) -> bool:
+ """Record a cycle's outcome and queue the hook it authorises, as ONE decision.
+
+ ``False`` means the guarded stamp was refused, nothing was written and no hook
+ exists; the caller must stop the watch.
+
+ HFR-267 made the guarded stamp run BEFORE the hook, which was necessary and not
+ sufficient: TWO COMMITS ARE NOT ONE DECISION.
+
+ self.store.mark_cycle_result(...) # transaction 1, COMMITS
+ self.request_store.enqueue_hook_send(...) # transaction 2, COMMITS
+
+ A ``/new`` reclaim or an archive from another connection can commit in the gap
+ between those commits. The stamp is accepted -- it won its compare-and-set
+ fairly, against the state that existed when it ran -- and the hook is queued
+ afterwards anyway, into a session the teardown has deleted and under a
+ definition it has paused or soft-deleted. Nothing is refused, because by the
+ time the teardown lands there is nothing left to refuse. Reordering moved the
+ window; it could not close it.
+
+ And the ordering introduced the inverse: a failure between the two commits left
+ a ``once``/terminal watch durably DISABLED with its completion hook lost, so the
+ user is never told the watch finished.
+
+ Both disappear when the stamp and the outbox row share a transaction (HFR-269).
+ When the two stores do not share a database -- file-backed test and legacy
+ configurations -- they cannot, and the fallback keeps HFR-267's order; the
+ file-backed watch store has no compare-and-set for a teardown to outrun.
+ """
+
+ request = self._hook_request(watch, prompt=prompt, prefix=prefix, body=body)
+ atomic = request is not None and _shared_run_ledger_backend(self.store, self.request_store) is not None
+ queued_run = self.request_store.queued_run_payload(request) if atomic and request else None
if not self._watch_store_call(
watch.id,
"mark_cycle_result",
lambda: self.store.mark_cycle_result(
watch.id,
- exit_code=1,
- error=error_text,
- disable=True,
+ exit_code=exit_code,
+ error=error,
+ event_detected=event_detected,
+ disable=disable,
+ queued_run=queued_run,
),
+ guarded=True,
):
- return
+ return False
+ if request is not None and queued_run is None:
+ self.request_store.enqueue(request)
+ return True
+
+ def _stop_watch_for_missing_cwd(self, watch: ManagedWatch, *, error_text: str) -> None:
watch_label = watch.name or watch.id
- body = (
- f"Watch '{watch_label}' stopped because its working directory is no longer available.\n"
- f"Working directory: {watch.cwd}\n"
- "Update or recreate the watch with a valid cwd before monitoring continues."
+ self._commit_cycle_result(
+ watch,
+ exit_code=1,
+ error=error_text,
+ disable=True,
+ body=(
+ f"Watch '{watch_label}' stopped because its working directory is no longer available.\n"
+ f"Working directory: {watch.cwd}\n"
+ "Update or recreate the watch with a valid cwd before monitoring continues."
+ ),
+ )
+
+
+def _failure_hook_body(watch: ManagedWatch, *, exit_code: int, error_text: str) -> str:
+ """The body of the hook that tells the user why a watch stopped failing."""
+
+ watch_label = watch.name or watch.id
+ if exit_code == 124:
+ return (
+ f"Watch '{watch_label}' stopped because the waiter timed out.\n"
+ f"Check whether the timeout is too short or the waiter is blocked, then recreate the watch if monitoring should continue.\n"
+ f"Details: {error_text}"
)
- self._enqueue_hook(watch, body=body)
+ return (
+ f"Watch '{watch_label}' stopped because the waiter exited with code {exit_code}.\n"
+ f"Review the error below, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.\n"
+ f"Error: {error_text}"
+ )
def _build_prompt(prefix: Optional[str], body: Optional[str]) -> str:
diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.py
index 3fe2808ed..03ba9aad1 100644
--- a/storage/agent_session_rows.py
+++ b/storage/agent_session_rows.py
@@ -1,14 +1,19 @@
from __future__ import annotations
import json
+import logging
import os
import secrets
from datetime import datetime, timezone
from typing import Any
-from sqlalchemy import Connection, select
+from sqlalchemy import Connection, func, select, update
from storage.models import agent_sessions, scope_settings
+from storage.session_reclaim import (
+ OVERRIDABLE_SETTING_COLUMNS,
+ reconcile_explicit_overrides,
+)
SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
JSON_VALUE_PREFIX = "__json__:"
@@ -16,6 +21,8 @@ SESSION_VISIBILITIES = frozenset({"foreground", "background"})
PRIVATE_AGENT_RUN_SCOPE_TYPE = "private_agent_run"
+logger = logging.getLogger(__name__)
+
def session_openable_in_chat(*, session_id: Any, scope_native_type: Any = None) -> bool:
"""Whether ``/chat/<session_id>`` will actually open this session.
@@ -66,6 +73,15 @@ def decode_session_value(value: Any) -> Any:
return value
+def _metadata_object(value: Any) -> dict[str, Any]:
+ """Parse a stored ``metadata_json`` blob; never raise on legacy junk."""
+ try:
+ parsed = json.loads(value) if value else {}
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
def snapshot_scope_workdir(conn: Connection, scope_id: str | None) -> str | None:
if not scope_id:
return None
@@ -82,6 +98,73 @@ def normalize_workdir(value: Any) -> str | None:
return os.path.abspath(os.path.expanduser(text))
+#: A write that changes nothing, used ONLY to reserve SQLite's writer slot inside a
+#: transaction that is already open, where ``BEGIN IMMEDIATE`` is illegal. SQLite takes
+#: the write lock at the START of an UPDATE program -- before its WHERE loop -- so a
+#: never-matching UPDATE becomes the writer without touching a row. That is the one
+#: property it exists for, so a test pins it rather than trusting it.
+_WRITE_LOCK_RESERVATION_SQL = "UPDATE agent_sessions SET id = id WHERE 1 = 0"
+
+
+def reserve_write_lock(conn: Connection) -> None:
+ """Hold SQLite's write lock for the rest of this transaction, from BEFORE the reads.
+
+ THE RACE THIS REMOVES INSTEAD OF DETECTING. SQLite takes the write lock at a
+ transaction's first WRITE, never at its reads, and in WAL mode a transaction that
+ already holds a READ snapshot can no longer BECOME a writer once another connection
+ has committed: SQLite answers ``SQLITE_BUSY_SNAPSHOT`` and ``busy_timeout`` never
+ retries it, because waiting cannot make a snapshot newer. So every "read, decide,
+ write" sequence here carries a window, and the widest one was the first-turn INSERT:
+ a ``SAVEPOINT`` opened the transaction and ``new_session_id``'s scan pinned its
+ snapshot inside it, so a competing turn committing in between left the loser unable
+ to write at all -- and every caller of a shared get-or-create saw "database is
+ locked" out of an ordinary first turn.
+
+ Calling this BEFORE those reads means the failure cannot happen rather than being
+ recovered from afterwards: the lock is held for the remainder of the transaction, so
+ nothing the decision rests on can change before the write lands, and there is no
+ error left to classify. That is also why it holds on every supported interpreter.
+ RECOGNISING ``SQLITE_BUSY_SNAPSHOT`` requires ``sqlite3.Error.sqlite_errorcode``
+ (Python 3.11+), because its primary code and its message are the ones every
+ unrelated ``SQLITE_BUSY`` carries and neither discriminates -- while this project
+ supports Python 3.10 (``requires-python >= 3.10``), where that attribute does not
+ exist. NOT PRODUCING the error requires nothing from the interpreter at all.
+
+ ``_claim_anchor_row``'s supersede branch has always depended on exactly this: its
+ anchor-move UPDATE takes the lock, which is the whole reason the INSERT after it
+ needs no re-read of its own. This makes the same guarantee available to the paths
+ that have no write to lead with.
+
+ TWO SPELLINGS, ONE GUARANTEE, because SQLite has no ``LOCK TABLE``:
+
+ * In autocommit -- which is every production entry point into the create path, since
+ pysqlite opens no transaction for a bare SELECT -- ``BEGIN IMMEDIATE`` takes the
+ write lock AND the read snapshot in ONE statement, so there is no instant between
+ them for a competing commit to land in. SQLAlchemy's pysqlite dialect emits no
+ ``BEGIN`` of its own, so this is the transaction the enclosing ``engine.begin()``
+ goes on to commit or roll back.
+ * Inside a transaction that is already open, ``BEGIN IMMEDIATE`` is illegal, so
+ ``_WRITE_LOCK_RESERVATION_SQL`` reserves the writer slot instead. If that
+ transaction is already a writer the statement is a no-op; if it has only read, this
+ is where a stale snapshot surfaces -- before this module's own reads and with
+ nothing of ours yet written, which is the earliest and cheapest place for it.
+
+ WHAT IT COSTS is contention, not correctness: concurrent FIRST turns on the same
+ database now queue behind each other for the length of the caller's transaction
+ rather than racing and having one lose. ``busy_timeout`` (5s, ``storage/db.py``)
+ bounds that wait, the create path runs once per thread, and the previous behaviour on
+ this very interleaving was an exception rather than a faster answer. It is
+ deliberately NOT applied to the read-mostly fast path where a session row already
+ exists: those writes re-assert their read inside the statement instead
+ (``unchanged_text``), which costs no serialisation.
+ """
+
+ if conn.connection.dbapi_connection.in_transaction:
+ conn.exec_driver_sql(_WRITE_LOCK_RESERVATION_SQL)
+ return
+ conn.exec_driver_sql("BEGIN IMMEDIATE")
+
+
def new_session_id(conn: Connection) -> str:
used = {str(value) for value in conn.execute(select(agent_sessions.c.id)).scalars()}
while True:
@@ -157,3 +240,367 @@ def create_agent_session_row(
)
)
return row_id
+
+
+def get_or_create_agent_session_row(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ session_anchor: str,
+ agent_backend: str,
+ **create_kwargs: Any,
+) -> tuple[str | None, bool]:
+ """Resolve the one session row for ``(scope_id, session_anchor)``, creating it once.
+
+ Returns ``(session_id, created)``, where ``session_id`` is ``None`` when there is
+ NO usable session: a claim race was lost (relabel or supersede, see
+ ``_claim_anchor_row``) to a writer that ARCHIVED or removed the row. An archive is
+ terminal, so the winner's id is not an answer, and every caller must degrade
+ instead of using it.
+
+ Three things make a plain find-then-create unsafe here, and all three are the
+ same defect seen from a different angle:
+
+ 1. **Lookup key narrower than the constraint key.** Callers look up by
+ ``(scope, anchor, backend)`` while the UNIQUE index is ``(scope, anchor)``
+ alone, so a row owned by another backend is invisible to the finder and
+ fatal to the INSERT. Resolved by looking up on the CONSTRAINT key.
+ 2. **The find-then-create race.** SQLite takes no write lock at a SELECT, so two
+ callers can both miss and both try to INSERT the first row. Resolved by
+ ``reserve_write_lock``: the create path takes the write lock BEFORE the reads the
+ INSERT rests on and re-decides under it, so there is no window for a competing
+ creator to commit in — neither the ``IntegrityError`` from the UNIQUE index nor
+ the ``SQLITE_BUSY_SNAPSHOT`` that a stale read snapshot used to produce.
+ 3. **Two backends, one thread.** A thread is ONE session per (scope, anchor);
+ the incoming backend wins the anchor. An unbound row is relabelled in place
+ (nothing to lose). A row that already carries a native session id is
+ *superseded* instead: its anchor is moved aside so the slot frees, which
+ keeps the old transcript, Show Page and any bound definitions attached to a
+ row that still resolves by id. The resume path
+ (``core/handlers/session_handler.py``) deletes that row outright; this is
+ the same policy without the collateral damage, and it is the reason nothing
+ needs reclaiming here.
+ """
+
+ anchor = str(session_anchor) if session_anchor is not None else None
+ backend = str(agent_backend or "")
+
+ existing = _row_for_scope_anchor(conn, scope_id=scope_id, session_anchor=anchor)
+ if existing is None:
+ # NOTHING holds the anchor, so this call intends to INSERT. Reserve the writer
+ # slot BEFORE the reads that INSERT rests on -- the id scan in
+ # ``new_session_id`` and the workdir snapshot -- and then take the decision
+ # AGAIN underneath it. With the lock held no other connection can commit, so
+ # the second read is final and the INSERT cannot collide with a competing
+ # creator; it is the same reason the supersede branch's INSERT needs no re-read.
+ #
+ # The first read stays unlocked deliberately: it is the hot path every message
+ # takes and a session row almost always exists by then. That is exactly why it
+ # cannot be trusted here -- a winner may commit between it and the reservation --
+ # so the reserved re-read is what the create decides from.
+ reserve_write_lock(conn)
+ existing = _row_for_scope_anchor(conn, scope_id=scope_id, session_anchor=anchor)
+ if existing is not None:
+ return _claim_anchor_row(
+ conn,
+ existing,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ backend=backend,
+ create_kwargs=create_kwargs,
+ )
+
+ return (
+ create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ agent_backend=backend,
+ **create_kwargs,
+ ),
+ True,
+ )
+
+
+def _row_for_scope_anchor(
+ conn: Connection,
+ *,
+ scope_id: str | None,
+ session_anchor: str | None,
+) -> dict[str, Any] | None:
+ if session_anchor is None:
+ return None
+ row = (
+ conn.execute(
+ select(
+ agent_sessions.c.id,
+ agent_sessions.c.agent_backend,
+ agent_sessions.c.agent_variant,
+ agent_sessions.c.native_session_id,
+ )
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(agent_sessions.c.session_anchor == session_anchor)
+ # Never resolve onto an archived row: archive vacates the anchor, so a
+ # match here would be a stale one. Matches the bind/resolve read paths.
+ .where(agent_sessions.c.status != "archived")
+ .order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc())
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ return dict(row) if row is not None else None
+
+
+# A superseded row keeps its original anchor with this marker appended, so
+# ``thread_id_from_session_anchor`` still recovers the thread for definitions
+# pinned to it. Anything that matches anchors by PREFIX must exclude the marker
+# explicitly -- ``delete_agent_sessions`` does, because superseding promises the
+# row is kept and a prefix clear would otherwise hard-delete it.
+SUPERSEDED_ANCHOR_MARKER = "superseded"
+SUPERSEDED_ANCHOR_INFIX = f":{SUPERSEDED_ANCHOR_MARKER}:"
+
+
+def unchanged_text(column: Any, value: Any) -> Any:
+ """Predicate re-asserting that a TEXT column still holds what a read observed.
+
+ THE ONE IDIOM in this module: a decision made from a SELECT is re-asserted inside
+ the statement that acts on it, because the SELECT reserves nothing -- pysqlite
+ emits no ``BEGIN`` for a bare SELECT, so SQLite takes the write lock at the first
+ DML and another connection can commit in between. Factored because every such
+ re-assertion needs the same NULL handling: these columns are nullable text and a
+ bare ``col == value`` over a NULL evaluates to NULL, not false, so without
+ ``COALESCE`` the guard silently stops guarding exactly the legacy rows (blank
+ backend, NULL anchor) most likely to be raced on.
+ """
+
+ return func.coalesce(column, "") == str(value or "")
+
+
+def live_session_or_none(conn: Connection, row_id: str) -> str | None:
+ """Re-read a lost race's winner: its id if still usable, ``None`` if not.
+
+ The ANSWER half of the idiom, shared by the lost-race paths here: refusing the
+ write is only half of it, since what the function RETURNS is part of the same
+ invariant. A winner that ARCHIVED the row is terminal and vacates the anchor --
+ every read path filters ``status != 'archived'``, and
+ ``BaseAgent.ensure_agent_session_id`` pins any non-empty answer straight into the
+ turn context without re-resolving -- so the archived id is no answer at all, and
+ neither is a missing row (a concurrent hard delete). Same answer the sibling
+ writers ``bind_agent_session`` / ``bind_agent_session_by_id`` give for the same
+ interleaving (HFR-251/252/253/254).
+ """
+
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == str(row_id))
+ ).scalar_one_or_none()
+ if status is None or str(status) == "archived":
+ return None
+ return str(row_id)
+
+
+def _claim_anchor_row(
+ conn: Connection,
+ row: dict[str, Any],
+ *,
+ scope_id: str | None,
+ session_anchor: str | None,
+ backend: str,
+ create_kwargs: dict[str, Any],
+) -> tuple[str | None, bool]:
+ row_id = str(row["id"])
+ current_backend = str(row["agent_backend"] or "")
+ if not backend or current_backend == backend:
+ return row_id, False
+
+ now = utc_now_iso()
+ if not decode_session_value(row["native_session_id"]):
+ # Unbound row: relabel it to the incoming backend. This is the ordinary
+ # ``ensure_agent_session_id`` case — the row exists only to reserve the
+ # thread's identity, so adopting it costs nothing and avoids a collision.
+ #
+ # The WHOLE route is replaced, not merged. The guard above restricts this
+ # branch to a genuine backend CHANGE on a row with NO committed native
+ # conversation: it never produced a turn under its old backend, so its
+ # agent / model / reasoning_effort are provisional reservations, not a
+ # user's choice. Merging them ("keep what the incoming route leaves
+ # ``None``") is what let a row become Claude-owned while still carrying a
+ # Codex model and Codex Agent name — the legacy
+ # ``ensure_agent_session_id`` / ``bind_agent_session`` callers have no
+ # model / effort parameters and pass ``None`` unconditionally, so for them
+ # the merge was guaranteed to keep the old backend's settings. The "None
+ # means I have no opinion" reading that legitimately applies to
+ # same-backend binds never reaches here, because a same-backend claim
+ # returns above.
+ values: dict[str, Any] = {
+ "agent_backend": backend,
+ "agent_variant": str(create_kwargs.get("agent_variant") or backend),
+ "updated_at": now,
+ }
+ for column in ("agent_id", "agent_name", "model", "reasoning_effort"):
+ values[column] = create_kwargs.get(column)
+ # Resetting the columns must also drop their explicit-override marker:
+ # left behind, it keeps telling dispatch that this session pins the (now
+ # cleared) model on purpose, so the adopted row would still route the old
+ # backend's settings.
+ stored_metadata = conn.execute(
+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == row_id)
+ ).scalar_one_or_none()
+ values["metadata_json"] = json.dumps(
+ reconcile_explicit_overrides(
+ _metadata_object(stored_metadata), cleared=OVERRIDABLE_SETTING_COLUMNS
+ ),
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
+ # The three predicates below RE-ASSERT the state this branch was decided
+ # from, because none of the reads above hold it. ``_row_for_scope_anchor``
+ # and the metadata SELECT reserve nothing: pysqlite emits no ``BEGIN`` for a
+ # bare SELECT, so the write lock is taken at the first DML and a
+ # still-finishing turn on the OLD backend can commit its native id -- or an
+ # archive can land -- between the decision and this statement. A bare ``id``
+ # match then relabels a row that is no longer relabellable: the row ends up
+ # ``agent_backend='claude'`` while still holding the Codex native id the
+ # winner just bound, with the whole route wiped and the override marker
+ # cleared. The sibling writer ``bind_agent_session_by_id`` carries exactly
+ # these three for the same reason (HFR-251); this one, added by the same PR,
+ # carried none.
+ relabelled = conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == row_id)
+ # Still live. An archive is terminal and vacates the anchor, so a
+ # relabel here would rewrite a row nothing should resolve to.
+ .where(agent_sessions.c.status != "archived")
+ # Still unbound: WRITE-ONCE enforced BY THE STATEMENT. A committed native
+ # id is backend-specific, so a bound row must be SUPERSEDED (below) and
+ # never relabelled. A rule enforced by a preceding SELECT is not
+ # write-once.
+ .where(func.coalesce(agent_sessions.c.native_session_id, "") == "")
+ # Still on the backend this branch decided AGAINST, so a concurrent
+ # claim that already moved the row cannot be overwritten by this
+ # caller's stale route.
+ .where(func.coalesce(agent_sessions.c.agent_backend, "") == current_backend)
+ .values(**values)
+ )
+ if relabelled.rowcount:
+ return row_id, False
+ # LOST the race. Return the winner UNTOUCHED -- its backend identity, its
+ # write-once native id, its model / reasoning_effort and its override marker
+ # all stand. Falling through to the supersede branch below would be a second
+ # write decided from the same stale snapshot, which is the defect this guard
+ # exists to prevent.
+ #
+ # WHICH WINNER, THOUGH. Two different writes can take this branch's row, and
+ # only one of them leaves a usable session:
+ #
+ # * a concurrent BIND (the row is live and now carries a native id) -- a real
+ # session, on the winner's backend, which this caller's turn may go on to
+ # use; answer with its id.
+ # * a concurrent ARCHIVE -- terminal. The archive VACATES the anchor, and
+ # every read path here filters ``status != 'archived'`` (this function's own
+ # ``_row_for_scope_anchor`` included), so the archived id resolves to nothing
+ # anywhere else. There is no later re-resolve to correct it either:
+ # ``BaseAgent.ensure_agent_session_id`` pins whatever non-empty id it is
+ # handed straight into ``context.platform_specific['agent_session_id']`` and
+ # the turn runs against that row. So the answer is ``None``, exactly as the
+ # two sibling writers ``bind_agent_session`` and
+ # ``bind_agent_session_by_id`` already answer for the same interleaving
+ # (HFR-251/252/254). Not a re-resolve and not a fresh row: either would be a
+ # second decision from the snapshot this branch was just refused for.
+ winner = live_session_or_none(conn, row_id)
+ logger.warning(
+ "Lost the anchor-relabel race for session %s; keeping the winner's route "
+ "(requested backend=%s, decided from=%s, winner=%s)",
+ row_id,
+ backend,
+ current_backend or "''",
+ "live" if winner else "archived or gone",
+ )
+ return winner, False
+
+ # Bound to another backend: its native id is write-once and backend-specific,
+ # so it cannot be relabelled. Move its anchor aside and let the caller create a
+ # fresh row on the freed slot. Nothing is deleted.
+ #
+ # The marker is a SUFFIX on the original anchor, not a replacement for it.
+ # Definitions pinned to this row survive the supersede, and
+ # ``resolve_session_id_target`` derives their thread solely from
+ # ``session_anchor`` via ``thread_id_from_session_anchor``, which reads
+ # ``anchor.split(":", 1)[0]``. A bare ``superseded:<id>`` leaves that base as
+ # the literal "superseded", matching no platform prefix, so every pinned
+ # ``--post-to thread`` definition would silently fall back to the channel
+ # root -- and because the row still exists, the unresolvable-binding recovery
+ # never fires to catch it. Suffixing keeps the base parseable while still
+ # freeing the slot, since anchor lookups match the full string exactly.
+ # Colon-suffixed anchors are already the convention here (see the
+ # "pre-scoped session anchors" branch in ``thread_id_from_session_anchor``).
+ # The row was located by this exact anchor, so the parameter is its current
+ # value; the row mapping here does not carry the column.
+ current_anchor = str(session_anchor or "")
+ if not current_anchor or SUPERSEDED_ANCHOR_INFIX in current_anchor:
+ superseded_anchor = f"{SUPERSEDED_ANCHOR_MARKER}:{row_id}"
+ else:
+ superseded_anchor = f"{current_anchor}{SUPERSEDED_ANCHOR_INFIX}{row_id}"
+ # The three predicates RE-ASSERT the state this branch was decided from, for the
+ # reason the relabel branch above spells out: the reads reserve nothing, so a second
+ # backend claim observing the SAME bound ``(scope_id, session_anchor)`` row can move
+ # the anchor and create its replacement inside this window. With a bare ``id`` match
+ # the loser reported a successful anchor move -- it re-superseded a row whose anchor
+ # had already moved -- and then ran straight into ``create_agent_session_row``, where
+ # its INSERT collided with the winner's replacement on the UNIQUE
+ # ``(scope_id, session_anchor)`` index. The caller got an ``IntegrityError`` out of a
+ # function whose entire contract is "resolve the one session row for this anchor,
+ # creating it once", instead of the winning session.
+ moved = conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == row_id)
+ # Still live. An archive is terminal and vacates the anchor to its own
+ # sentinel, so there is no slot here to free and nothing to supersede.
+ .where(agent_sessions.c.status != "archived")
+ # Still holding the anchor this call resolved it by: once another claim has
+ # moved it aside, the slot is not ours to free and may already be filled by
+ # the winner's replacement row.
+ .where(unchanged_text(agent_sessions.c.session_anchor, current_anchor))
+ # Still on the backend this branch decided against, so a concurrent claim that
+ # already adopted the row cannot be superseded out from under it.
+ .where(unchanged_text(agent_sessions.c.agent_backend, current_backend))
+ .values(session_anchor=superseded_anchor, updated_at=now)
+ )
+ if not moved.rowcount:
+ # LOST the race. Answer with the row that HOLDS the anchor now, re-read; do NOT
+ # insert. A second decision from the refused snapshot is exactly the defect, and
+ # the INSERT is the statement that would raise. ``_row_for_scope_anchor`` already
+ # excludes archived rows, so a winner that archived (or a hard delete) yields
+ # ``None`` -- no usable session -- which every caller of
+ # ``get_or_create_agent_session_row`` already handles.
+ #
+ # The winner may be on a DIFFERENT backend than this caller asked for. That is
+ # the same degradation the relabel branch accepts: a thread is ONE session per
+ # (scope, anchor), the race decided whose, and re-superseding from the stale
+ # snapshot would leave two writers taking turns evicting each other.
+ winner = _row_for_scope_anchor(conn, scope_id=scope_id, session_anchor=session_anchor)
+ winner_id = str(winner["id"]) if winner is not None else None
+ logger.warning(
+ "Lost the anchor-supersede race for session %s; returning the current "
+ "anchor holder (requested backend=%s, decided from=%s, winner=%s)",
+ row_id,
+ backend,
+ current_backend or "''",
+ winner_id or "archived or gone",
+ )
+ return winner_id, False
+ # The anchor move above took the write lock, and it is held for the rest of this
+ # transaction, so no other connection can fill the slot between freeing it and this
+ # INSERT. That -- not a preceding read -- is why the create needs no re-read of its
+ # own here, and it is the guarantee ``reserve_write_lock`` now gives the first-turn
+ # create, which has no write to lead with.
+ return (
+ create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=session_anchor,
+ agent_backend=backend,
+ **create_kwargs,
+ ),
+ True,
+ )
diff --git a/storage/background.py b/storage/background.py
index 05f5257f3..373862ea2 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -14,7 +14,7 @@ from apscheduler.triggers.date import DateTrigger
from sqlalchemy import and_, case, func, insert, or_, select, update
from config import paths
-from storage.agent_session_rows import session_openable_in_chat
+from storage.agent_session_rows import session_openable_in_chat, unchanged_text
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import (
background_tables_ready,
@@ -23,6 +23,7 @@ from storage.migrations import (
)
from storage.models import agent_runs, agent_sessions, run_definitions, scopes
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
+from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
logger = logging.getLogger(__name__)
@@ -184,6 +185,143 @@ def _id_batches(values: Iterable[_BatchValue], *, params_per_value: int = 1) ->
return [ids[start : start + size] for start in range(0, len(ids), size)]
+class DefinitionWriteConflict(RuntimeError):
+ """A full-row definition write lost to a concurrent lifecycle/binding change.
+
+ Raised by the callers that OWN a user action (``vibe task update``,
+ ``vibe watch update``, pause/resume), never swallowed: the write did not
+ happen, so reporting the mutated in-memory task back to the user would claim
+ an edit the database refused.
+ """
+
+ def __init__(self, definition_id: str, *, definition_type: str = "definition") -> None:
+ super().__init__(
+ f"{definition_type} {definition_id} changed underneath this update "
+ "(its Session binding, enabled state, deletion or reclaim snapshot moved); "
+ "nothing was written"
+ )
+ self.definition_id = str(definition_id)
+ self.definition_type = str(definition_type)
+
+
+@dataclass(frozen=True)
+class DefinitionWriteExpectation:
+ """The definition state a FULL-ROW payload was derived from.
+
+ ``upsert_scheduled_task`` / ``upsert_watch`` write EVERY column of
+ ``run_definitions``, from a payload a caller built out of a read that happened
+ somewhere else entirely -- ``vibe task update`` reads the definition, resolves
+ Agents and Sessions, prompts for nothing, and only then writes the whole row
+ back. Between that read and this write, ``reclaim_bound_definitions`` (``/new``
+ or the archive dialog) can pause or soft-delete the very same row and stamp its
+ ``session_settings_snapshot`` on it. A write keyed on ``id`` alone then RESTORES
+ the pre-teardown ``session_id`` / ``enabled`` / ``deleted_at`` / metadata: the
+ reclaim's compare-and-set succeeded, the counters and the teardown ledger told
+ the user "1 task paused", and the row is enabled again and pointing at a session
+ that no longer exists.
+
+ So the write must re-assert the state it was decided from -- the same idiom the
+ session writers use (``storage.agent_session_rows.unchanged_text``), applied to
+ a payload whose read is one layer up instead of one statement up.
+
+ THE PREDICATE SET IS THE STATE TEARDOWN OWNS, and nothing else:
+
+ * ``session_id`` -- the binding the payload's fields were resolved against.
+ * ``enabled`` -- the pause half of a ``pause``-mode reclaim.
+ * ``deleted_at`` -- the soft-delete half of a ``delete``-mode reclaim, and the
+ one that lets a full-row write RESURRECT a removed task, since no in-memory
+ definition even carries the column (it is always written back as ``NULL``).
+ * the reclaim snapshot's ``captured_at`` -- the third reclaim shape: for an
+ ALREADY-paused definition the reclaim changes neither ``enabled`` nor
+ ``deleted_at``, it only refreshes ``session_settings_snapshot``. That
+ snapshot is what a later ``create_once`` rebind reads to carry the old
+ workdir / agent / model forward, so restoring the pre-teardown metadata sends
+ the task back on the wrong route (D3) with every other guard satisfied.
+
+ DELIBERATELY NOT ``updated_at``, and not the whole row. A row-version guard
+ would refuse every benign concurrent write -- a run result landing while the
+ user renames a task -- and turn a working edit into an error. What is guarded is
+ the lifecycle and binding state a teardown decides, which is exactly what a
+ stale full-row payload must not be allowed to undo.
+ """
+
+ session_id: Optional[str] = None
+ enabled: bool = True
+ deleted_at: Optional[str] = None
+ #: ``session_settings_snapshot.captured_at`` as read, ``None``/"" when the
+ #: definition carried no reclaim snapshot.
+ snapshot_captured_at: Optional[str] = None
+
+ @classmethod
+ def from_read(
+ cls,
+ *,
+ session_id: Any = None,
+ enabled: Any = True,
+ deleted_at: Any = None,
+ metadata: Any = None,
+ ) -> "DefinitionWriteExpectation":
+ """Build the expectation from the definition row/dataclass just read."""
+
+ return cls(
+ session_id=str(session_id) if session_id else None,
+ enabled=bool(enabled),
+ deleted_at=str(deleted_at) if deleted_at else None,
+ snapshot_captured_at=reclaim_snapshot_marker(metadata),
+ )
+
+
+def reclaim_snapshot_marker(metadata: Any) -> Optional[str]:
+ """``session_settings_snapshot.captured_at`` from definition metadata, if any.
+
+ Never raises: the marker is JSON on rows that predate it, so anything
+ unparseable reads as "this definition carries no snapshot", which is what the
+ SQL side of the guard also computes for a malformed blob.
+ """
+
+ if not isinstance(metadata, dict):
+ return None
+ snapshot = metadata.get(SESSION_SETTINGS_SNAPSHOT_KEY)
+ if not isinstance(snapshot, dict):
+ return None
+ captured_at = snapshot.get("captured_at")
+ return str(captured_at) if captured_at else None
+
+
+#: ``captured_at`` of the reclaim snapshot, read in SQL. Guarded by ``json_valid``
+#: because ``metadata_json`` is user-visible text on legacy rows: a bare
+#: ``json_extract`` over a malformed blob raises, which would turn "this row has no
+#: snapshot" into a failed write.
+_RECLAIM_SNAPSHOT_MARKER_SQL = case(
+ (
+ func.json_valid(run_definitions.c.metadata_json) == 1,
+ func.json_extract(
+ run_definitions.c.metadata_json,
+ f"$.{SESSION_SETTINGS_SNAPSHOT_KEY}.captured_at",
+ ),
+ ),
+ else_=None,
+)
+
+
+def definition_state_unchanged(expect: DefinitionWriteExpectation) -> list[Any]:
+ """Predicates re-asserting the state a full-row payload was derived from.
+
+ Shares ``unchanged_text`` with the session writers rather than restating its
+ NULL handling: these are nullable TEXT columns and a bare ``col == value`` over
+ a NULL evaluates to NULL, not false, so without ``COALESCE`` the guard stops
+ guarding exactly the rows most likely to be raced on (an unbound definition, a
+ row with no snapshot). ``enabled`` is ``NOT NULL INTEGER`` and needs none.
+ """
+
+ return [
+ unchanged_text(run_definitions.c.session_id, expect.session_id),
+ run_definitions.c.enabled == (1 if expect.enabled else 0),
+ unchanged_text(run_definitions.c.deleted_at, expect.deleted_at),
+ unchanged_text(_RECLAIM_SNAPSHOT_MARKER_SQL, expect.snapshot_captured_at),
+ ]
+
+
def definition_lifecycle_expression(definition_type: str):
"""The single declaration of a task/watch lifecycle state, as SQL.
@@ -940,6 +1078,68 @@ def reset_workbench_claimed_runs_in_connection(conn: Any, run_ids: list[str]) ->
_defer_run_ids_updated_from_connection(conn, changed_ids)
+def upsert_definition_in_connection(
+ conn: Any,
+ values: dict[str, Any],
+ *,
+ expect: DefinitionWriteExpectation | None,
+ definition_type: str,
+) -> bool:
+ """The one full-row ``run_definitions`` write, guarded, in a CALLER'S transaction.
+
+ Separated from ``_upsert_definition`` so a guarded stamp and the durable effect it
+ authorises can be committed together (HFR-269). ``False`` means the write was
+ refused and the caller's transaction must not persist anything that depended on
+ it.
+ """
+
+ existing = conn.execute(
+ select(run_definitions.c.id).where(run_definitions.c.id == values["id"]).limit(1)
+ ).scalar_one_or_none()
+ if not existing:
+ conn.execute(insert(run_definitions).values(**values))
+ return True
+ stmt = update(run_definitions).where(run_definitions.c.id == values["id"])
+ if expect is not None:
+ # RE-ASSERT what the payload was decided from. The read that produced it
+ # reserves nothing -- it happened in the caller, one layer and possibly many
+ # statements ago, and even the ``existing`` SELECT above takes no write lock
+ # (pysqlite emits no ``BEGIN`` for a bare SELECT), so the lock is first taken
+ # here.
+ stmt = stmt.where(*definition_state_unchanged(expect))
+ result = conn.execute(stmt.values(**values))
+ if result.rowcount:
+ return True
+ # LOST. Nothing was written, so nothing may be reported as written: the counters
+ # and the ledger a reclaim credited stay true, and the caller decides what to tell
+ # the user (``DefinitionWriteConflict`` for a user action, a ``False`` return for a
+ # best-effort runtime stamp).
+ logger.warning(
+ "Refused a stale full-row write for %s %s: its Session binding, enabled "
+ "state, deletion or reclaim snapshot changed after the payload was read",
+ definition_type,
+ values["id"],
+ )
+ return False
+
+
+def enqueue_run_in_connection(conn: Any, values: dict[str, Any]) -> None:
+ """Write one ``agent_runs`` outbox row in a CALLER'S transaction.
+
+ The event snapshot is deferred to the transaction, so subscribers are told about
+ a run only once the row they would read is committed.
+ """
+
+ existing = conn.execute(
+ select(agent_runs.c.id).where(agent_runs.c.id == values["id"]).limit(1)
+ ).scalar_one_or_none()
+ if existing:
+ conn.execute(update(agent_runs).where(agent_runs.c.id == values["id"]).values(**values))
+ else:
+ conn.execute(insert(agent_runs).values(**values))
+ _defer_run_ids_updated_from_connection(conn, [values["id"]])
+
+
class SQLiteBackgroundTaskStore:
def __init__(self, db_path: Optional[Path] = None):
self.db_path = db_path or paths.get_sqlite_state_path()
@@ -1024,16 +1224,20 @@ class SQLiteBackgroundTaskStore:
[self._scheduled_task_from_row(row)], conn, definition_type="scheduled"
)[0]
- def upsert_scheduled_task(self, payload: dict[str, Any]) -> None:
- values = self._scheduled_task_values(payload)
- with self.engine.begin() as conn:
- existing = conn.execute(
- select(run_definitions.c.id).where(run_definitions.c.id == values["id"]).limit(1)
- ).scalar_one_or_none()
- if existing:
- conn.execute(update(run_definitions).where(run_definitions.c.id == values["id"]).values(**values))
- else:
- conn.execute(insert(run_definitions).values(**values))
+ def upsert_scheduled_task(
+ self, payload: dict[str, Any], *, expect: DefinitionWriteExpectation | None = None
+ ) -> bool:
+ """Write a whole scheduled-task row. ``False`` means the write was REFUSED.
+
+ ``expect`` is the state the payload was derived from (see
+ ``DefinitionWriteExpectation``); pass it from every caller that read the
+ definition before building the payload, so a teardown committed in between
+ cannot be silently reverted.
+ """
+
+ return self._upsert_definition(
+ self._scheduled_task_values(payload), expect=expect, definition_type="scheduled task"
+ )
def remove_task(self, definition_id: str, *, deleted_at: Optional[str] = None) -> bool:
with self.engine.begin() as conn:
@@ -1152,32 +1356,81 @@ class SQLiteBackgroundTaskStore:
return None
return self._enrich_definitions([self._watch_from_row(row)], conn, definition_type="watch")[0]
- def upsert_watch(self, payload: dict[str, Any]) -> None:
- values = self._watch_values(payload)
+ def upsert_watch(
+ self, payload: dict[str, Any], *, expect: DefinitionWriteExpectation | None = None
+ ) -> bool:
+ """Write a whole watch row. ``False`` means the write was REFUSED.
+
+ The twin of ``upsert_scheduled_task``: same table, same full-row shape, same
+ guard. Watches are reclaimed by the same ``reclaim_bound_definitions`` call,
+ so guarding only the task side would leave the identical hole open.
+ """
+
+ return self._upsert_definition(
+ self._watch_values(payload), expect=expect, definition_type="watch"
+ )
+
+ def _upsert_definition(
+ self,
+ values: dict[str, Any],
+ *,
+ expect: DefinitionWriteExpectation | None,
+ definition_type: str,
+ ) -> bool:
+ """The one full-row ``run_definitions`` write, guarded once for both types."""
+
with self.engine.begin() as conn:
- existing = conn.execute(
- select(run_definitions.c.id).where(run_definitions.c.id == values["id"]).limit(1)
- ).scalar_one_or_none()
- if existing:
- conn.execute(update(run_definitions).where(run_definitions.c.id == values["id"]).values(**values))
- else:
- conn.execute(insert(run_definitions).values(**values))
+ return upsert_definition_in_connection(
+ conn, values, expect=expect, definition_type=definition_type
+ )
+
+ def upsert_watch_with_queued_run(
+ self,
+ payload: dict[str, Any],
+ *,
+ expect: DefinitionWriteExpectation | None,
+ run_payload: dict[str, Any],
+ ) -> bool:
+ """A guarded watch stamp and the outbox row it authorises, ONE transaction.
+
+ HFR-269 -- the bug this method exists to remove. HFR-267 put the guarded stamp
+ BEFORE the enqueue, which is necessary and was not sufficient, because two
+ commits are not one decision:
+
+ self.store.mark_cycle_result(...) # transaction 1, COMMITS
+ self.request_store.enqueue_hook_send(...) # transaction 2, COMMITS
+
+ A ``/new`` reclaim or an archive from another connection can commit in the gap
+ between those two commits. The stamp is then accepted -- it won its
+ compare-and-set fairly, before the teardown -- and the hook is queued
+ afterwards anyway, against a definition the database has since paused or
+ soft-deleted. The guard refuses nothing because there is nothing left to
+ refuse: the ordering change moved the race window, it did not close it.
+
+ The inverse was the other half: an exception between the two commits left a
+ ``once``/terminal watch durably disabled with its completion hook LOST, so the
+ user is never told the watch finished and the definition cannot say why.
+
+ Both are the same defect -- the stamp and the effect it authorises were
+ separate transactions. Here they are one: the outbox row is written on the same
+ connection, after the guard, and a refusal or an exception rolls BOTH back.
+ ``False`` means nothing was written; the watch is untouched and no hook exists.
+ """
+
+ values = self._watch_values(payload)
+ run_values = self._run_values(run_payload)
+ with run_update_event_transaction(self.engine) as conn:
+ if not upsert_definition_in_connection(
+ conn, values, expect=expect, definition_type="watch"
+ ):
+ return False
+ enqueue_run_in_connection(conn, run_values)
+ return True
def enqueue_run(self, payload: dict[str, Any]) -> None:
values = self._run_values(payload)
- row_to_publish = None
- with self.engine.begin() as conn:
- existing = conn.execute(
- select(agent_runs.c.id).where(agent_runs.c.id == values["id"]).limit(1)
- ).scalar_one_or_none()
- if existing:
- conn.execute(update(agent_runs).where(agent_runs.c.id == values["id"]).values(**values))
- else:
- conn.execute(insert(agent_runs).values(**values))
- row_to_publish = dict(
- conn.execute(select(agent_runs).where(agent_runs.c.id == values["id"]).limit(1)).mappings().one()
- )
- _publish_run_rows_updated([row_to_publish])
+ with run_update_event_transaction(self.engine) as conn:
+ enqueue_run_in_connection(conn, values)
def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
stmt = self._runs_query(status=status).order_by(agent_runs.c.created_at, agent_runs.c.id)
diff --git a/storage/models.py b/storage/models.py
index 690fc4f4f..2cf9290fc 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -133,6 +133,12 @@ agent_sessions = Table(
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
Column("last_active_at", String, nullable=True),
+ # A thread is ONE session per (scope, anchor). The invariant shipped in the
+ # Alembic revision only (20260601_0011), while ``SQLiteSessionsService.__init__``
+ # calls ``metadata.create_all`` — so any DB born from models-only, including
+ # tests, silently lacked it and could not reproduce the production collision.
+ # Index name matches the revision's so the two agree on one object.
+ Index("uq_agent_sessions_scope_anchor", "scope_id", "session_anchor", unique=True),
Index("ix_agent_sessions_scope_anchor_workdir", "scope_id", "session_anchor", "workdir"),
Index("ix_agent_sessions_backend_variant", "agent_backend", "agent_variant"),
Index("ix_agent_sessions_status_activity", "status", "last_active_at"),
diff --git a/storage/session_reclaim.py b/storage/session_reclaim.py
new file mode 100644
index 000000000..82f4b3e02
--- /dev/null
+++ b/storage/session_reclaim.py
@@ -0,0 +1,395 @@
+"""Reclaim the definitions bound to a Session that is going away.
+
+Two teardown paths, one contract. ``archive_session`` already reclaimed —
+it vacates the anchor and soft-deletes bound ``run_definitions`` — while the IM
+``/new`` path hard-deleted the session rows and reclaimed nothing, so a
+``create_once`` task pinned to that session fired and failed forever with nobody
+told. This module owns the shared half so a new teardown path cannot forget it.
+
+The two callers need OPPOSITE outcomes, so ``mode`` is required and has no
+default:
+
+- ``delete`` — archive is terminal. A paused definition could be re-enabled later
+ and would then target a dead session, so it is soft-deleted.
+- ``pause`` — ``/new`` is an everyday command (D2). ``enabled=0`` keeps the
+ definition recoverable; soft-deleting a user's tasks on ``/new`` is the
+ regression this split exists to prevent.
+
+Reclaim is also the only code path that still sees BOTH rows, so it snapshots the
+session settings that live nowhere else. ``run_definitions`` stores ``agent_name``
+and ``cwd`` but no ``model``/``reasoning_effort``; without the snapshot a later
+``create_once`` rebind re-resolves the current Agent and silently changes the
+task's model (D3). Anywhere later is too late.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from contextlib import contextmanager
+from contextvars import ContextVar
+from datetime import datetime, timezone
+from typing import Any, Iterable, Iterator, Literal
+
+from sqlalchemy import select, update
+from sqlalchemy.engine import Connection
+
+from storage.models import agent_sessions, run_definitions
+
+logger = logging.getLogger(__name__)
+
+RECLAIM_DELETE = "delete"
+RECLAIM_PAUSE = "pause"
+ReclaimMode = Literal["delete", "pause"]
+
+#: Durable definition-metadata key holding the settings of the session that was
+#: reclaimed. Read by the ``create_once`` rebind so it can carry the previous
+#: workdir / agent / model forward instead of resetting to scope defaults.
+SESSION_SETTINGS_SNAPSHOT_KEY = "session_settings_snapshot"
+
+#: Durable SESSION-metadata key listing the settings this session pins
+#: EXPLICITLY, so a stored NULL can be told apart from an absent value.
+#:
+#: ``agent_sessions.model IS NULL`` already means "inherit whatever the Agent
+#: resolves to at dispatch time" for every session ever created, and dispatch
+#: implements that with ``or vibe_agent.model``. A preserved ``create_once``
+#: rebind needs the opposite: the session it replaces pinned NOTHING, and D3
+#: says keep it that way even if the Agent has since gained a default. Those two
+#: cannot be the same NULL, and REINTERPRETING the global NULL would silently
+#: change the routing of every existing session -- so the distinction is carried
+#: as an explicit presence marker on the sessions that need it, and every row
+#: without the marker keeps today's inherit semantics untouched.
+#:
+#: Value is the list of column names that are explicit, e.g.
+#: ``["model", "reasoning_effort"]``.
+SESSION_SETTINGS_OVERRIDE_KEY = "explicit_setting_overrides"
+
+#: The only columns the override marker can name. Kept next to the key so a
+#: writer that adds a third pinnable column has one place to look.
+OVERRIDABLE_SETTING_COLUMNS = ("model", "reasoning_effort")
+
+_SNAPSHOT_COLUMNS = (
+ "scope_id",
+ "agent_backend",
+ "agent_variant",
+ "agent_id",
+ "agent_name",
+ "model",
+ "reasoning_effort",
+ "workdir",
+ "session_anchor",
+ "visibility",
+)
+
+_DEFAULT_PAUSE_REASON = "the bound agent session was cleared"
+
+# Ambient teardown context. The ``/new`` path reaches ``delete_agent_sessions``
+# through every registered backend's ``clear_sessions``, so threading a reason and
+# a result count through four backend adapters would push transport-level detail
+# into the storage signature. The context is set once by the command handler and
+# read here; an explicit ``reason=`` argument always wins over it.
+_teardown_reason: ContextVar[str | None] = ContextVar("_avibe_teardown_reason", default=None)
+_teardown_ledger: ContextVar[list[dict[str, Any]] | None] = ContextVar(
+ "_avibe_teardown_ledger", default=None
+)
+
+
+@contextmanager
+def session_teardown_context(*, reason: str | None = None) -> Iterator[list[dict[str, Any]]]:
+ """Name the cause of a session teardown and collect what it reclaimed.
+
+ Yields the ledger, one entry per definition whose state actually changed, so a
+ caller can report "N tasks paused" without every layer in between growing a
+ return value.
+ """
+
+ entries: list[dict[str, Any]] = []
+ reason_token = _teardown_reason.set(reason)
+ ledger_token = _teardown_ledger.set(entries)
+ try:
+ yield entries
+ finally:
+ _teardown_ledger.reset(ledger_token)
+ _teardown_reason.reset(reason_token)
+
+
+def current_reclaim_ledger() -> list[dict[str, Any]] | None:
+ """The active teardown ledger, or ``None`` when nothing is collecting."""
+
+ return _teardown_ledger.get()
+
+
+@contextmanager
+def reclaim_ledger_transaction() -> Iterator[None]:
+ """Scope ledger entries to a transaction; discard them if it does not commit.
+
+ HFR-273. The ledger is the LIVE half of a teardown -- it is what ``/new`` counts to
+ tell the user "N tasks paused" -- and it was append-only regardless of what the
+ database ended up doing. A transaction that reclaims a definition and then aborts
+ (a locked database on a later statement, or on the COMMIT itself) rolls the pause
+ back and leaves the entry: the definition is still enabled, still bound to the
+ session, and the user has been told it was paused. ``handle_new`` logs the failure
+ at debug and reports the ledger anyway, so nothing else corrects it.
+
+ Wrap the transaction, OUTSIDE ``engine.begin()``, so the truncation runs after the
+ rollback. Entries appended before this scope are left alone: an earlier transaction
+ in the same teardown may well have committed.
+
+ Not the same thing as a reclaim whose own DELETE was refused -- that reclaim really
+ did commit, and ``_delete_agent_session_rows`` documents why it is deliberately kept.
+ """
+
+ ledger = current_reclaim_ledger()
+ mark = len(ledger) if ledger is not None else 0
+ try:
+ yield
+ except BaseException:
+ if ledger is not None and len(ledger) > mark:
+ logger.warning(
+ "Discarding %d reclaim ledger entr(ies) whose transaction did not commit",
+ len(ledger) - mark,
+ )
+ del ledger[mark:]
+ raise
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _json_object(value: Any) -> dict[str, Any]:
+ try:
+ parsed = json.loads(value) if value else {}
+ except (TypeError, ValueError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+def _dump_json(payload: dict[str, Any]) -> str:
+ return json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
+
+
+def explicit_override_names(metadata: Any) -> set[str]:
+ """The setting names a session pins EXPLICITLY, per its metadata marker.
+
+ One parser for every reader, and it never raises: the marker is user-visible
+ JSON on a row that predates it, so a malformed or absent value must read as
+ "this session pins nothing" rather than break the turn that consulted it.
+ """
+
+ if not isinstance(metadata, dict):
+ return set()
+ marked = metadata.get(SESSION_SETTINGS_OVERRIDE_KEY)
+ if isinstance(marked, str):
+ # Tolerate a hand-edited scalar; treat it as a one-element list.
+ return {marked} if marked.strip() else set()
+ if isinstance(marked, (list, tuple, set)):
+ return {str(name) for name in marked if str(name).strip()}
+ return set()
+
+
+def reconcile_explicit_overrides(
+ metadata: Any,
+ *,
+ cleared: Iterable[str] = (),
+ explicit: Iterable[str] = (),
+) -> dict[str, Any]:
+ """Return a metadata dict whose override marker matches the columns just written.
+
+ THE INVARIANT: the marker is a claim about what the ROW currently pins, so
+ every writer of ``agent_sessions.model`` / ``.reasoning_effort`` must
+ reconcile it in the same statement. A writer that resets or replaces one of
+ those columns and leaves the marker behind keeps forcing dispatch to honour
+ a value the writer just changed -- the Workbench "Default" action clears the
+ model, the stale marker still says "this session pins NULL on purpose", and
+ dispatch keeps sending NULL instead of the Agent's default. The control
+ inverts: the user's edit is stored and displayed but never routed.
+
+ ``cleared`` names the settings this write reset or replaced (their marker
+ entries are dropped); ``explicit`` names the settings the writer is pinning
+ on purpose (their entries are added). Returns a NEW dict -- callers compose
+ it with their own metadata edits -- and removes the key entirely when no
+ names are left, so a row that pins nothing looks exactly like every row
+ created before the marker existed. ``metadata=None`` and a malformed marker
+ value are both tolerated (see ``explicit_override_names``).
+ """
+
+ result: dict[str, Any] = dict(metadata) if isinstance(metadata, dict) else {}
+ cleared_names = {str(name) for name in cleared}
+ names = [name for name in sorted(explicit_override_names(result)) if name not in cleared_names]
+ for name in explicit:
+ text = str(name)
+ if text and text not in names:
+ names.append(text)
+ if names:
+ result[SESSION_SETTINGS_OVERRIDE_KEY] = names
+ else:
+ result.pop(SESSION_SETTINGS_OVERRIDE_KEY, None)
+ return result
+
+
+def session_settings_snapshot(
+ conn: Connection,
+ session_id: str,
+ *,
+ reason: str | None = None,
+) -> dict[str, Any] | None:
+ """Copy the settings that live only on the session row.
+
+ Returns ``None`` when the row is already gone — the caller must run this
+ BEFORE the delete, in the same transaction.
+ """
+
+ row = (
+ conn.execute(
+ select(
+ agent_sessions.c.id,
+ *(agent_sessions.c[name] for name in _SNAPSHOT_COLUMNS),
+ ).where(agent_sessions.c.id == str(session_id))
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ return None
+ snapshot: dict[str, Any] = {"session_id": row["id"], "captured_at": _utc_now_iso()}
+ for name in _SNAPSHOT_COLUMNS:
+ snapshot[name] = row[name]
+ if reason:
+ snapshot["reason"] = reason
+ return snapshot
+
+
+def reclaim_bound_definitions(
+ conn: Connection,
+ session_id: str,
+ *,
+ mode: ReclaimMode,
+ reason: str | None = None,
+) -> dict[str, int]:
+ """Detach scheduled tasks / watches from a session that is going away.
+
+ ``mode`` is required: ``delete`` soft-deletes (terminal teardown), ``pause``
+ sets ``enabled=0`` and records ``last_error`` (recoverable teardown). Runs in
+ the caller's transaction, before the session row is removed.
+
+ Each definition is reclaimed by a COMPARE-AND-SET on the binding this call was
+ decided from, and the returned counters plus the teardown ledger count only the
+ writes that actually LANDED — a definition repointed to another session inside
+ the window is left alone and reported to nobody.
+ """
+
+ if mode not in (RECLAIM_DELETE, RECLAIM_PAUSE):
+ raise ValueError(f"invalid reclaim mode: {mode!r}")
+
+ summary = {"paused": 0, "deleted": 0, "snapshotted": 0}
+ sid = str(session_id or "").strip()
+ if not sid:
+ return summary
+
+ rows = (
+ conn.execute(
+ select(
+ run_definitions.c.id,
+ run_definitions.c.definition_type,
+ run_definitions.c.enabled,
+ run_definitions.c.metadata_json,
+ )
+ .where(run_definitions.c.session_id == sid)
+ .where(run_definitions.c.deleted_at.is_(None))
+ )
+ .mappings()
+ .all()
+ )
+ if not rows:
+ return summary
+
+ effective_reason = reason or _teardown_reason.get() or _DEFAULT_PAUSE_REASON
+ snapshot = session_settings_snapshot(conn, sid, reason=effective_reason)
+ ledger = _teardown_ledger.get()
+ now = _utc_now_iso()
+
+ for row in rows:
+ values: dict[str, Any] = {"updated_at": now}
+ counters: list[str] = []
+ if snapshot is not None:
+ metadata = _json_object(row["metadata_json"])
+ metadata[SESSION_SETTINGS_SNAPSHOT_KEY] = snapshot
+ values["metadata_json"] = _dump_json(metadata)
+ counters.append("snapshotted")
+ changed = False
+ if mode == RECLAIM_DELETE:
+ values["deleted_at"] = now
+ counters.append("deleted")
+ changed = True
+ elif row["enabled"]:
+ # Already-paused definitions keep the fresh snapshot but must not have
+ # an unrelated pause reason restamped over their own.
+ values["enabled"] = 0
+ values["last_error"] = effective_reason
+ counters.append("paused")
+ changed = True
+ # The TWO predicates below RE-ASSERT what the SELECT above decided, because
+ # that read reserves nothing. pysqlite emits no ``BEGIN`` for a bare SELECT, so
+ # the write lock is taken at the first DML: on the hard-delete path
+ # (``_delete_agent_session_rows``) the reclaim helper is reached after only
+ # reads -- a resolved two-part scope key never upserts -- so a second
+ # connection can commit between the read and this statement.
+ # ``archive_session`` writes first and is serialised, but the shared helper
+ # cannot depend on which caller it is under.
+ #
+ # WHAT A BARE ``id`` MATCH LOSES: the user repoints this task / watch to
+ # another Session (``upsert_scheduled_task``, a full-row UPDATE) or deletes it
+ # inside the window. This statement then pauses or soft-deletes a definition
+ # that is now bound to a DIFFERENT, live session, and overwrites its
+ # ``session_settings_snapshot`` with the settings of the session it no longer
+ # belongs to -- so a later ``create_once`` rebind carries the wrong model
+ # forward. Both re-asserted: the binding this reclaim was decided for, and the
+ # live ``deleted_at`` state.
+ reclaimed = conn.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == row["id"])
+ # Still bound to the session that is going away.
+ .where(run_definitions.c.session_id == sid)
+ # Still live: a definition deleted inside the window stays deleted, and its
+ # ``deleted_at`` must not be restamped with this teardown's clock.
+ .where(run_definitions.c.deleted_at.is_(None))
+ .values(**values)
+ )
+ if not reclaimed.rowcount:
+ # LOST the race, so this reclaim did NOT happen and must not be reported as
+ # though it had. The accounting is part of the guard: ``summary`` is what
+ # the archive confirm dialog reports, and the ledger is what ``/new`` counts
+ # in its reply ("N tasks paused"). Crediting a write that never landed tells
+ # the user a task was paused while it keeps firing on its new session -- the
+ # same class of silent lie as the write itself.
+ logger.warning(
+ "Skipped reclaiming definition %s for session %s mode=%s: it was "
+ "repointed or deleted concurrently",
+ row["id"],
+ sid,
+ mode,
+ )
+ continue
+ for name in counters:
+ summary[name] += 1
+ if changed and ledger is not None:
+ ledger.append(
+ {
+ "definition_id": row["id"],
+ "definition_type": row["definition_type"],
+ "mode": mode,
+ "session_id": sid,
+ "reason": effective_reason,
+ }
+ )
+
+ if summary["paused"] or summary["deleted"]:
+ logger.info(
+ "Reclaimed definitions bound to session %s mode=%s paused=%d deleted=%d",
+ sid,
+ mode,
+ summary["paused"],
+ summary["deleted"],
+ )
+ return summary
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 4973a1c29..9d5f28aea 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -8,7 +8,7 @@ from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import Any
-from sqlalchemy import Connection, case, func, select
+from sqlalchemy import Connection, case, func, or_, select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.exc import IntegrityError
@@ -18,14 +18,33 @@ from config.v2_sessions import ActivePollInfo, SessionState
from config.v2_settings import _split_scoped_key
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.agent_session_rows import (
+ SUPERSEDED_ANCHOR_INFIX,
create_agent_session_row,
decode_session_value,
encode_session_value,
+ get_or_create_agent_session_row,
new_session_id,
normalize_workdir,
+ reserve_write_lock,
snapshot_scope_workdir,
)
-from storage.models import agent_sessions, metadata, runtime_records, scopes, state_meta
+from storage.models import (
+ agent_sessions,
+ metadata,
+ run_definitions,
+ runtime_records,
+ scopes,
+ state_meta,
+)
+from storage.session_reclaim import (
+ OVERRIDABLE_SETTING_COLUMNS,
+ RECLAIM_PAUSE,
+ ReclaimMode,
+ explicit_override_names,
+ reclaim_bound_definitions,
+ reclaim_ledger_transaction,
+ reconcile_explicit_overrides,
+)
from storage.settings_service import make_scope_id, upsert_scope
SESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"
@@ -106,6 +125,23 @@ def read_session_display_meta(
return meta
+#: ``classify_reserved_agent_session`` verdicts (HFR-279). Plain strings rather than an
+#: Enum because the retry bookkeeping in ``core.scheduled_tasks`` logs them verbatim and
+#: an operator reading those lines should see the fact, not a repr.
+RESERVATION_ABSENT = "absent"
+RESERVATION_ADOPTED = "adopted"
+RESERVATION_RESERVED = "reserved"
+
+#: Session-metadata key naming the harness definition whose recovery reserved the row
+#: (HFR-276). Written INSIDE the reservation's own transaction, so the durable handle
+#: exists exactly when the reservation does: a fault that later refuses both the release
+#: and the ``orphaned_reservations`` record cannot leave a row this key does not name.
+#: The key is scoped to the create_once recovery path on purpose -- a create_per_run
+#: reservation is legitimately unbound and unreferenced between its reserve and its
+#: dispatch, so a sweep keyed on this stamp must never be able to see one.
+RESERVED_BY_DEFINITION_METADATA_KEY = "reserved_by_harness_definition"
+
+
class SQLiteSessionsService:
def __init__(self, db_path: Path):
self.db_path = db_path
@@ -224,6 +260,201 @@ class SQLiteSessionsService:
now=now,
)
+ def release_reserved_agent_session(self, session_id: str, *, reason: str) -> bool:
+ """Give back a session this process reserved and then could not use.
+
+ The inverse of the two ``reserve_*`` entry points above, and deliberately the
+ NARROWEST thing that undoes them: it names exactly ONE row, by the id the
+ reservation returned, and it removes a workspace only when that workspace is the
+ Show Page directory the standalone reservation mkdir'd for that same id. A
+ scoped reservation inherits the Scope's workdir, which is shared with every other
+ session in that Scope and is never this call's to delete.
+
+ A reservation is committed BEFORE the caller can know whether it will be able to
+ use it (the guarded write that adopts it is a different transaction, in a
+ different store), so "reserve, lose the race, give it back" is a real sequence
+ and not an error path. Returns ``True`` only when this call removed the row.
+
+ TWO PREDICATES, and they are re-asserted BY the delete (``_delete_agent_session_rows``
+ re-runs the id query with the write lock held), so they hold at the instant of the
+ delete rather than at the instant they were read:
+
+ * ``native_session_id`` is still empty -- nothing was ever dispatched into it. A
+ bound row has a transcript and is not a reservation any more.
+ * no ``run_definitions`` row points at it -- if a definition adopted it after all,
+ it is somebody's live binding and deleting it would recreate the dangling
+ pointer the whole reclaim machinery exists to prevent.
+
+ Neither predicate is what keeps a CONCURRENT WINNER safe; the id does that. They
+ are there so that a caller which is WRONG about having lost the race destroys
+ nothing.
+
+ AND THE DECISION IS TAKEN UNDER THE WRITE LOCK (HFR-278). Re-asserting the
+ predicates in the DELETE was enough to keep the winner's ROW, and not enough to
+ keep the winner: ``_delete_agent_session_rows`` runs the id query first and calls
+ ``reclaim_bound_definitions`` second, and the id read reserves nothing (pysqlite
+ opens no transaction for a bare SELECT). An adoption committing between the two
+ left the reclaim looking at the WINNER's definition -- so it paused it, stamped
+ its ``last_error`` and overwrote its settings snapshot -- and only then did the
+ DELETE re-evaluate ``NOT EXISTS`` and correctly preserve the session. The row
+ survived; the definition that had just adopted it did not, and its reclaim is
+ deliberately never rolled back. ``reserve_write_lock`` removes the window instead
+ of detecting it: taken here, at the top of the transaction and BEFORE the read
+ the decision rests on, so no adoption can land between the read and the reclaim.
+ Nothing has been read yet on this connection, so this is the cheap
+ ``BEGIN IMMEDIATE`` spelling, which takes the write lock and the read snapshot in
+ one statement.
+ """
+
+ row = self.get_agent_session_by_id(str(session_id))
+ if row is None:
+ return False
+ with reclaim_ledger_transaction(), self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ deleted = _delete_agent_session_rows(
+ conn,
+ select(agent_sessions.c.id)
+ .where(agent_sessions.c.id == str(session_id))
+ .where(
+ or_(
+ agent_sessions.c.native_session_id.is_(None),
+ agent_sessions.c.native_session_id == "",
+ )
+ )
+ .where(
+ ~select(run_definitions.c.id)
+ .where(run_definitions.c.session_id == str(session_id))
+ .exists()
+ ),
+ # Nothing may be bound to a row that satisfies the predicates above, so
+ # the reclaim is a no-op by construction. ``RECLAIM_PAUSE`` is the
+ # conservative answer if that ever stops being true: pause a definition,
+ # never silently unbind one.
+ reclaim_mode=RECLAIM_PAUSE,
+ reclaim_reason=reason,
+ )
+ if not deleted:
+ logger.warning(
+ "Not releasing reserved agent session %s (%s): it was bound or adopted "
+ "after it was reserved",
+ session_id,
+ reason,
+ )
+ return False
+ self._remove_reserved_workspace(str(session_id), row.get("workdir"))
+ return True
+
+ def classify_reserved_agent_session(self, session_id: str) -> str:
+ """Which of the three reservation facts holds for ``session_id`` (HFR-279).
+
+ ``release_reserved_agent_session`` answers ``False`` for three different facts
+ -- the row is gone, the row was adopted, the release faulted -- and the retry
+ bookkeeping needs them apart: an absent or adopted row must be taken OFF the
+ retry record, a genuine orphan must stay on it. The verdicts:
+
+ * ``RESERVATION_ABSENT`` -- no row. Released by an earlier attempt or deleted
+ by its owner; nothing left to retry.
+ * ``RESERVATION_ADOPTED`` -- the row is somebody's live binding: a native
+ session was dispatched into it, or a ``run_definitions`` row points at it.
+ The same two predicates the guarded release re-asserts under the write lock,
+ read here WITHOUT that lock -- this probe exists precisely so an adopted
+ winner is never made to pay the release's ``BEGIN IMMEDIATE`` again on every
+ fire of the loser.
+ * ``RESERVATION_RESERVED`` -- the row exists, has no native binding and no
+ definition references it: still a reservation, still this caller's to
+ release.
+
+ ONE statement on purpose: both facts come from the same read snapshot, so the
+ answer is a state the row actually was in, never half of one state and half of
+ another. A read fault propagates -- the caller must keep the entry rather than
+ guess.
+ """
+
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(
+ agent_sessions.c.native_session_id,
+ select(run_definitions.c.id)
+ .where(run_definitions.c.session_id == str(session_id))
+ .exists()
+ .label("definition_referenced"),
+ )
+ .where(agent_sessions.c.id == str(session_id))
+ .limit(1)
+ ).first()
+ if row is None:
+ return RESERVATION_ABSENT
+ if str(row[0] or "") or bool(row[1]):
+ return RESERVATION_ADOPTED
+ return RESERVATION_RESERVED
+
+ def list_reserved_agent_sessions_for_definition(self, definition_id: str) -> list[str]:
+ """The still-unadopted reservations stamped with ``definition_id`` (HFR-276).
+
+ The durable side of the orphan retry: ``metadata.orphaned_reservations`` on the
+ definition is written AFTER a release fails, through the same database, so the
+ fault that refused the release can refuse the record too and the id -- random,
+ known to nothing else -- was lost. The stamp is different: it is written inside
+ the reservation's own INSERT transaction, so if the reservation committed, the
+ handle committed with it, and a later fire recovers the id from the row itself.
+
+ The filters are the classification facts, in the same single statement: only
+ rows that are still empty-native AND unreferenced are returned, so an adopted
+ winner is invisible here by construction. The guarded release re-asserts both
+ under the write lock anyway; this listing only decides who is WORTH a release
+ attempt.
+ """
+
+ stamped = func.json_extract(
+ agent_sessions.c.metadata_json,
+ f'$."{RESERVED_BY_DEFINITION_METADATA_KEY}"',
+ )
+ with self.engine.connect() as conn:
+ rows = conn.execute(
+ select(agent_sessions.c.id)
+ .where(stamped == str(definition_id))
+ .where(
+ or_(
+ agent_sessions.c.native_session_id.is_(None),
+ agent_sessions.c.native_session_id == "",
+ )
+ )
+ .where(
+ ~select(run_definitions.c.id)
+ .where(run_definitions.c.session_id == agent_sessions.c.id)
+ .exists()
+ )
+ .order_by(agent_sessions.c.id)
+ ).all()
+ return [str(row[0]) for row in rows]
+
+ @staticmethod
+ def _remove_reserved_workspace(session_id: str, workdir: Any) -> None:
+ """Remove the Show Page workspace a standalone reservation created, if any.
+
+ Ownership is decided by identity, not by emptiness: only ``show/<session_id>``
+ belongs to this session, and only this session can have created it. A workdir
+ that is anything else -- a Scope's shared directory, a user-supplied path -- is
+ left alone. ``rmdir`` rather than ``rmtree`` for the same reason: a released
+ reservation never ran, so its workspace is empty, and a non-empty one means
+ something happened in there that this call is not entitled to destroy.
+ """
+
+ if not workdir or str(workdir) != str(paths.get_show_page_dir(session_id)):
+ return
+ path = Path(str(workdir))
+ try:
+ path.rmdir()
+ except FileNotFoundError:
+ return
+ except OSError as exc:
+ logger.warning(
+ "Left the workspace %s of released session %s in place: %s",
+ path,
+ session_id,
+ exc,
+ )
+
def ensure_agent_session_id(
self,
*,
@@ -248,7 +479,16 @@ class SQLiteSessionsService:
)
if row_id:
return row_id
- return create_agent_session_row(
+ # Route the create through the CONSTRAINT key: the finder above filters
+ # on backend, the unique index does not, so a same-anchor row owned by
+ # another backend is invisible here and fatal to a bare INSERT.
+ #
+ # ``session_id`` is ``None`` when that resolve found NO usable session --
+ # the anchor-relabel race lost to a writer that archived the row -- and
+ # ``None`` is exactly what this function must then return: an archive is
+ # terminal, and ``BaseAgent.ensure_agent_session_id`` pins any non-empty
+ # answer into the turn's context without ever re-resolving it.
+ session_id, _created = get_or_create_agent_session_row(
conn,
scope_id=scope_id,
agent_backend=_agent_backend(str(agent_name)),
@@ -264,6 +504,7 @@ class SQLiteSessionsService:
now=now,
require_workdir=False,
)
+ return session_id
def bind_agent_session(
self,
@@ -291,7 +532,11 @@ class SQLiteSessionsService:
encoded_session_id = encode_session_value(native_session_id)
requested_workdir = str(workdir) if workdir is not None else None
if not row_id:
- return create_agent_session_row(
+ # Same reason as ``ensure_agent_session_id``: the finder's key is
+ # narrower than the unique index, and the SELECT above took no write
+ # lock. When this resolves to an existing row it falls through to the
+ # write-once update below rather than stealing the native id.
+ row_id, created = get_or_create_agent_session_row(
conn,
scope_id=scope_id,
agent_backend=_agent_backend(str(agent_name)),
@@ -307,6 +552,19 @@ class SQLiteSessionsService:
now=now,
require_workdir=False,
)
+ if not row_id:
+ # NO usable session: the resolve lost the anchor-relabel race to a
+ # writer that archived the row, and an archive is terminal. ``None``
+ # is the same answer the two lost-race paths further down already
+ # give for an archived winner, and it is also what fell out of the
+ # old code by accident -- every statement below is keyed on
+ # ``row_id``, so they all became ``id IS NULL``, matched nothing and
+ # left the final ``rowcount``-0 return. Accidentally right is not
+ # right: those statements also emit a spurious WRITE-ONCE race
+ # warning naming session ``None``. Decide it here instead.
+ return None
+ if created:
+ return row_id
values = {
"status": "active",
"updated_at": now,
@@ -323,18 +581,67 @@ class SQLiteSessionsService:
current_workdir,
requested_workdir,
)
- # WRITE-ONCE: a row's native_session_id is bound exactly once and never
- # changed. Set it only when the row has none yet; never let a recapture,
- # fork, subagent, or any fallback overwrite an existing native (product
- # invariant — one agent session ↔ one fixed native).
- if _set_native_once(conn, row_id, encoded_session_id):
- values["native_session_id"] = encoded_session_id
if vibe_agent_id is not None:
values["agent_id"] = vibe_agent_id
if vibe_agent_name is not None:
values["agent_name"] = vibe_agent_name
- conn.execute(agent_sessions.update().where(agent_sessions.c.id == row_id).values(**values))
- return row_id
+ # WRITE-ONCE: a row's native_session_id is bound exactly once and never
+ # changed. Never let a recapture, fork, subagent, or any fallback
+ # overwrite an existing native (product invariant — one agent session ↔
+ # one fixed native).
+ #
+ # The invariant is carried by the PREDICATE, not by the
+ # ``_set_native_once`` read: pysqlite emits no ``BEGIN`` for a bare
+ # SELECT, so the write lock is only taken at this UPDATE and another
+ # connection can commit a bind — or an archive — in between. A rule
+ # enforced by a preceding SELECT is not write-once. ``_set_native_once``
+ # still decides INTENT (and logs a differing native); the statement
+ # decides whether the write may land. Same shape as the twin
+ # ``bind_agent_session_by_id`` (HFR-251/252), which this path was missing.
+ if _set_native_once(conn, row_id, encoded_session_id):
+ first_bind = conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == row_id)
+ .where(agent_sessions.c.status != "archived")
+ .where(func.coalesce(agent_sessions.c.native_session_id, "") == "")
+ .values(**values, native_session_id=encoded_session_id)
+ )
+ if first_bind.rowcount:
+ return row_id
+ # Return the winner immediately. Falling through to the UPDATE below
+ # would preserve the winner's native id and then overwrite everything
+ # else it owns -- ``values`` carries ``status='active'``, both
+ # timestamps, and this caller's ``agent_id`` / ``agent_name`` -- so
+ # the row would attribute the winner's conversation to the Agent that
+ # LOST the race. The native id was never the only thing the winner
+ # owns, and this is the same correction the twin
+ # ``bind_agent_session_by_id`` needed: all THREE lost-race paths in
+ # this module now answer the same way instead of two of them
+ # continuing.
+ logger.warning(
+ "WRITE-ONCE: session %s was bound concurrently; keeping the winner's "
+ "native id and Agent identity",
+ row_id,
+ )
+ winner_status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == row_id)
+ ).scalar_one_or_none()
+ if winner_status is None or winner_status == "archived":
+ return None
+ return row_id
+ result = conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == row_id)
+ # ``values`` carries ``status='active'``, so without this predicate the
+ # bind RESURRECTS a row archived after the lookup above — the lookup
+ # (``_find_agent_session_row_id``) filters archived rows but reserves
+ # nothing, and the cancel that accompanies an archive is
+ # best-effort/background, so a still-finishing turn lands its bind
+ # here. Make the write itself the no-op instead.
+ .where(agent_sessions.c.status != "archived")
+ .values(**values)
+ )
+ return row_id if result.rowcount else None
def materialize_agent_session_route(
self,
@@ -351,18 +658,34 @@ class SQLiteSessionsService:
dispatch time (turn START), so a user's later explicit header pick —
including an explicit clear back to NULL — happens after this write and
is never undone by it. COALESCE keeps the fill-if-empty atomic against
- a concurrent pick. Returns True when a row was updated."""
- values: dict[str, Any] = {}
- if model:
- values["model"] = func.coalesce(func.nullif(agent_sessions.c.model, ""), model)
- if reasoning_effort:
- values["reasoning_effort"] = func.coalesce(
- func.nullif(agent_sessions.c.reasoning_effort, ""), reasoning_effort
- )
- if not values:
- return False
- values["updated_at"] = _utc_now_iso()
+ a concurrent pick. Returns True when a row was updated.
+
+ A setting the row pins EXPLICITLY is never filled, even when its column
+ is empty: that is the whole point of the explicit-override marker (a
+ preserved ``create_once`` rebind pins "no model" on purpose, D3). Filling
+ it here would turn the first turn into the thing the rebind was preventing
+ -- the Agent's current default becoming the session's pinned model."""
with self.engine.begin() as conn:
+ pinned = explicit_override_names(
+ _json_loads(
+ conn.execute(
+ select(agent_sessions.c.metadata_json).where(
+ agent_sessions.c.id == str(session_id)
+ )
+ ).scalar_one_or_none(),
+ {},
+ )
+ )
+ values: dict[str, Any] = {}
+ if model and "model" not in pinned:
+ values["model"] = func.coalesce(func.nullif(agent_sessions.c.model, ""), model)
+ if reasoning_effort and "reasoning_effort" not in pinned:
+ values["reasoning_effort"] = func.coalesce(
+ func.nullif(agent_sessions.c.reasoning_effort, ""), reasoning_effort
+ )
+ if not values:
+ return False
+ values["updated_at"] = _utc_now_iso()
result = conn.execute(
agent_sessions.update()
.where(agent_sessions.c.id == str(session_id))
@@ -393,21 +716,41 @@ class SQLiteSessionsService:
values["agent_id"] = vibe_agent_id
if vibe_agent_name is not None:
values["agent_name"] = vibe_agent_name
- if vibe_agent_backend is not None:
- values["agent_backend"] = vibe_agent_backend or ""
- values["agent_variant"] = vibe_agent_backend or "default"
+ requested_backend = (
+ str(vibe_agent_backend or "") if vibe_agent_backend is not None else None
+ )
with self.engine.begin() as conn:
# Never resurrect an archived (terminal) session. ``bind_agent_session_by_id``
# targets an explicit row, bypassing the ``status != 'archived'`` lookup
# guards — and a turn that was still finishing when the session was
# archived (the cancel is now best-effort/background) can land a late
# native-id bind here. Refuse it so the terminal archive sticks.
+ #
+ # THIS READ IS A FAST PATH, NOT THE GUARD. It reserves nothing either
+ # -- SQLite takes the write lock at the UPDATE -- so an archive can
+ # commit after it and before any write below. That interleaving is
+ # harmless because every UPDATE in this function re-asserts the
+ # predicate itself: the cross-backend adopt, the same-backend first
+ # bind, and the final statement all carry ``status != 'archived'``, so
+ # a late archive makes the write a no-op, and each rowcount-0 path
+ # re-reads the status and returns ``None``. Nothing here is left to
+ # make atomic; the read only spares an already-lost caller the rest of
+ # the work. Proven by HFR-252.
current_status = conn.execute(
select(agent_sessions.c.status).where(agent_sessions.c.id == str(session_id))
).scalar_one_or_none()
if current_status == "archived":
return None
if workdir is not None:
+ # LOG-ONLY, so the stale-snapshot hazard does not reach state: this
+ # read is never written back. ``workdir`` is not among the columns
+ # this function assigns -- neither ``values`` nor ``adopt_values``
+ # ever carries it, because the row's workdir is authoritative and
+ # only the create path sets it -- so the caller's requested workdir
+ # is DISCARDED whether it matches or not. A workdir another
+ # connection commits inside this window can therefore at worst make
+ # the warning below wrong or missing, which costs operator
+ # visibility and not correctness. Nothing to make atomic.
requested_workdir = str(workdir) or None
current = conn.execute(
select(agent_sessions.c.workdir, agent_sessions.c.session_anchor)
@@ -421,11 +764,140 @@ class SQLiteSessionsService:
current_workdir,
requested_workdir,
)
- # WRITE-ONCE: bind the native only if the row has none yet; never let a
- # recapture / fork / subagent overwrite an existing native (see
- # ``_set_native_once`` + bind_agent_session).
- if _set_native_once(conn, str(session_id), encoded_session_id):
- values["native_session_id"] = encoded_session_id
+ # This is the SECOND backend-adoption entry point. ``_claim_anchor_row``
+ # is not involved -- that one resolves a row by (scope, anchor), while
+ # this binds an explicitly targeted reserved row -- so the
+ # complete-route replacement it performs does not protect this path.
+ # Left merged, the row took the incoming backend and variant while
+ # keeping the PREVIOUS backend's model, reasoning_effort and
+ # explicit-setting marker: a Codex-owned session still routing an
+ # OpenCode model.
+ route_row = conn.execute(
+ select(
+ agent_sessions.c.agent_backend,
+ agent_sessions.c.native_session_id,
+ agent_sessions.c.metadata_json,
+ ).where(agent_sessions.c.id == str(session_id))
+ ).mappings().first()
+ current_backend = str((route_row or {}).get("agent_backend") or "")
+ already_bound = bool(decode_session_value((route_row or {}).get("native_session_id")))
+ backend_changes = bool(requested_backend) and requested_backend != current_backend
+ if backend_changes and not already_bound:
+ # The three cases below are decided from a SNAPSHOT, and these reads
+ # reserve nothing: SQLite takes the write lock at the UPDATE, so a
+ # second connection can bind this row after the read and before the
+ # write. A stale caller would then still take this branch and
+ # relabel a row that is now bound, clear the winner's route, and
+ # overwrite its write-once native id.
+ #
+ # So the adoption is ONE statement whose predicate re-asserts the
+ # snapshot it was decided from -- the same shape
+ # ``update_session`` uses for its backend lock. Route replacement
+ # and the native write therefore succeed or lose TOGETHER; there is
+ # no interleaving that applies one without the other.
+ adopt_values = dict(values)
+ adopt_values["agent_backend"] = requested_backend
+ adopt_values["agent_variant"] = requested_backend or "default"
+ adopt_values["model"] = None
+ adopt_values["reasoning_effort"] = None
+ adopt_values["metadata_json"] = json.dumps(
+ reconcile_explicit_overrides(
+ _json_loads((route_row or {}).get("metadata_json"), {}),
+ cleared=OVERRIDABLE_SETTING_COLUMNS,
+ ),
+ separators=(",", ":"),
+ ensure_ascii=False,
+ )
+ adopt_values["native_session_id"] = encoded_session_id
+ adopted = conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == str(session_id))
+ .where(agent_sessions.c.status != "archived")
+ # Still unbound: write-once enforced BY THE STATEMENT. A rule
+ # enforced by a preceding SELECT is not write-once.
+ .where(func.coalesce(agent_sessions.c.native_session_id, "") == "")
+ # Still on the backend we decided against.
+ .where(func.coalesce(agent_sessions.c.agent_backend, "") == current_backend)
+ .values(**adopt_values)
+ )
+ if adopted.rowcount:
+ return str(session_id)
+ # LOST the race. Return the winner untouched -- its backend
+ # identity, native id, model / effort and marker all stand. Falling
+ # through to the unconditional update below would apply this
+ # caller's stale identity on top of the winner, which is the defect
+ # this branch exists to prevent.
+ winner_status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == str(session_id))
+ ).scalar_one_or_none()
+ if winner_status is None or winner_status == "archived":
+ return None
+ logger.warning(
+ "Lost the native-bind race for session %s; keeping the winner's route "
+ "(requested backend=%s)",
+ session_id,
+ requested_backend,
+ )
+ return str(session_id)
+ if requested_backend is not None and not (backend_changes and already_bound):
+ values["agent_backend"] = requested_backend
+ values["agent_variant"] = requested_backend or "default"
+ if backend_changes and already_bound:
+ # WRITE-ONCE extends to the backend, not just the native id: the row
+ # already holds a conversation that a specific backend produced, and
+ # re-labelling it would leave that transcript attributed to a backend
+ # that never generated it. Drop the identity half of this bind rather
+ # than the whole call -- the native-id write below is separately
+ # guarded and a same-native re-bind stays idempotent.
+ values.pop("agent_id", None)
+ values.pop("agent_name", None)
+ logger.warning(
+ "Ignoring native bind backend switch on an already-bound session; "
+ "session_id=%s current=%s requested=%s",
+ session_id,
+ current_backend,
+ requested_backend,
+ )
+ # Same-backend (or backend-less) bind. WRITE-ONCE for the native id is
+ # carried by the PREDICATE, not by the ``_set_native_once`` read above
+ # it: between that read and this write another connection can commit a
+ # bind, and a rule enforced by a preceding SELECT is not write-once.
+ # ``_set_native_once`` still decides INTENT (and logs a differing
+ # native); the statement decides whether the write may land.
+ wants_native = _set_native_once(conn, str(session_id), encoded_session_id)
+ if wants_native:
+ first_bind = conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == str(session_id))
+ .where(agent_sessions.c.status != "archived")
+ .where(func.coalesce(agent_sessions.c.native_session_id, "") == "")
+ .values(**values, native_session_id=encoded_session_id)
+ )
+ if first_bind.rowcount:
+ return str(session_id)
+ # LOST the first bind. Return the winner immediately, exactly as the
+ # cross-backend branch above does -- the two lost-race paths now
+ # answer the same way instead of one of them continuing.
+ #
+ # The earlier version only dropped the identity columns when the
+ # winner's backend DIFFERED, which left two ways through: a winner
+ # on the SAME backend, and a caller that supplied no backend at all
+ # (the comparison cannot fire, so the conditional silently passed).
+ # Either way the final UPDATE below still ran with this caller's
+ # stale snapshot and overwrote the winner's selected Agent id/name,
+ # status and timestamps while dutifully preserving its native id.
+ # The native id was never the only thing the winner owns.
+ logger.warning(
+ "WRITE-ONCE: session %s was bound concurrently; keeping the winner's "
+ "native id and Agent identity",
+ session_id,
+ )
+ winner_status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == str(session_id))
+ ).scalar_one_or_none()
+ if winner_status is None or winner_status == "archived":
+ return None
+ return str(session_id)
result = conn.execute(
agent_sessions.update()
.where(agent_sessions.c.id == str(session_id))
@@ -478,19 +950,27 @@ class SQLiteSessionsService:
scope_key: str,
agent_name: str,
session_anchor: str,
+ reclaim_mode: ReclaimMode = RECLAIM_PAUSE,
+ reclaim_reason: str | None = None,
) -> bool:
now = _utc_now_iso()
- with self.engine.begin() as conn:
+ # ``reclaim_ledger_transaction`` OUTSIDE ``begin()``: every transaction that can
+ # reclaim a definition must discard its ledger entries if it does not commit
+ # (HFR-273), and the truncation has to run after the rollback.
+ with reclaim_ledger_transaction(), self.engine.begin() as conn:
scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
if scope_id is None:
return False
- result = conn.execute(
- agent_sessions.delete()
+ deleted = _delete_agent_session_rows(
+ conn,
+ select(agent_sessions.c.id)
.where(agent_sessions.c.scope_id == scope_id)
.where(_agent_session_name_predicate(str(agent_name) or "default"))
- .where(agent_sessions.c.session_anchor == str(session_anchor))
+ .where(agent_sessions.c.session_anchor == str(session_anchor)),
+ reclaim_mode=reclaim_mode,
+ reclaim_reason=reclaim_reason,
)
- return bool(result.rowcount)
+ return bool(deleted)
def delete_agent_sessions(
self,
@@ -498,13 +978,16 @@ class SQLiteSessionsService:
scope_key: str,
agent_name: str | None = None,
session_anchor_prefix: str | None = None,
+ reclaim_mode: ReclaimMode = RECLAIM_PAUSE,
+ reclaim_reason: str | None = None,
+ include_superseded: bool = False,
) -> int:
now = _utc_now_iso()
- with self.engine.begin() as conn:
+ with reclaim_ledger_transaction(), self.engine.begin() as conn:
scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
if scope_id is None:
return 0
- stmt = agent_sessions.delete().where(agent_sessions.c.scope_id == scope_id)
+ stmt = select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id)
if agent_name is not None:
stmt = stmt.where(_agent_session_name_predicate(str(agent_name) or "default"))
if session_anchor_prefix is not None:
@@ -514,8 +997,44 @@ class SQLiteSessionsService:
(agent_sessions.c.session_anchor == prefix)
| (agent_sessions.c.session_anchor.like(prefix_pattern, escape="\\"))
)
- result = conn.execute(stmt)
- return int(result.rowcount or 0)
+ if not include_superseded:
+ # A superseded row carries ``<original_anchor>:superseded:<id>``.
+ # This is a HARD delete and superseding deliberately keeps the row
+ # -- its native id is write-once and its history is not
+ # recoverable -- so exclude it from EVERY deletion path here, not
+ # just the prefix clear.
+ #
+ # The prefix branch alone is not enough, and the reason is the
+ # call order in ``handle_new``: it runs
+ # ``agent_service.clear_sessions()`` first, whose backend adapters
+ # reach this method with an ``agent_name`` and NO
+ # ``session_anchor_prefix``. A guard nested in the branch above is
+ # skipped there, so the row is already gone before the guarded
+ # clear runs. Callers that genuinely mean "remove everything",
+ # such as tearing down a scope that no longer exists, pass
+ # ``include_superseded=True`` rather than relying on which branch
+ # they happen to take.
+ #
+ # NULL-safe by construction: ``NOT LIKE`` over a NULL anchor
+ # evaluates to NULL, not true, so a bare negation silently
+ # PRESERVES every row whose ``session_anchor`` is NULL -- the
+ # exact inverse of this guard's purpose, and invisible because
+ # the rows simply fail to be deleted. Only a real marker may
+ # survive.
+ stmt = stmt.where(
+ or_(
+ agent_sessions.c.session_anchor.is_(None),
+ ~agent_sessions.c.session_anchor.like(
+ f"%{_escape_sql_like(SUPERSEDED_ANCHOR_INFIX)}%", escape="\\"
+ ),
+ )
+ )
+ return _delete_agent_session_rows(
+ conn,
+ stmt,
+ reclaim_mode=reclaim_mode,
+ reclaim_reason=reclaim_reason,
+ )
def load_state(self) -> SessionState:
with self.engine.connect() as conn:
@@ -1117,6 +1636,73 @@ def _agent_session_name_predicate(agent_name: str) -> Any:
return agent_sessions.c.agent_variant == requested
+def _delete_agent_session_rows(
+ conn: Connection,
+ id_query: Any,
+ *,
+ reclaim_mode: ReclaimMode,
+ reclaim_reason: str | None,
+) -> int:
+ """Hard-delete session rows, reclaiming what was bound to them first.
+
+ Every hard delete of a session row runs through here so no teardown path can
+ leave a ``run_definitions.session_id`` pointing at a row that no longer exists
+ — the root cause of a pinned task that fires and fails forever. The reclaim
+ must run BEFORE the delete: it is the last moment both rows are visible, and
+ the settings snapshot it takes is what lets a later rebind preserve the
+ session's model / agent instead of silently resetting to scope defaults.
+
+ ``id_query`` is re-asserted BY THE DELETE, so a row that stopped matching after
+ the id read is kept, and the returned count names only the rows actually removed.
+ """
+
+ session_ids = [str(row) for row in conn.execute(id_query).scalars().all()]
+ if not session_ids:
+ return 0
+ deleted = 0
+ for session_id in session_ids:
+ # The id read above reserves nothing -- pysqlite emits no ``BEGIN`` for a bare
+ # SELECT and ``resolve_scope_from_legacy_key`` does not write for a resolved
+ # 2-part scope key -- so every predicate ``id_query`` carries was evaluated
+ # before the write lock existed. The one that matters most is the
+ # ``include_superseded=False`` guard in ``delete_agent_sessions``: superseding
+ # PROMISES the row is kept (its native id is write-once and its transcript is not
+ # recoverable), and a supersede committed inside the window left this a hard
+ # delete of exactly the row that guard exists to protect, because the id was read
+ # while the anchor was still bare. Re-running ``id_query`` inside the DELETE
+ # re-evaluates every one of those predicates with the lock held, whichever caller
+ # built them.
+ #
+ # THE RECLAIM IS NOT ROLLED BACK when the delete is refused, and that is a
+ # deliberate choice rather than an oversight. It has to run first (it needs both
+ # rows visible for the settings snapshot), so undoing it would mean wrapping both
+ # statements in a SAVEPOINT -- and under WAL that makes things WORSE, not better:
+ # the SAVEPOINT opens the SQLite transaction before the reclaim's own SELECT, so
+ # the read pins a snapshot, and the reclaim's UPDATE then fails outright with
+ # ``SQLITE_BUSY_SNAPSHOT`` ("database is locked") on exactly the interleaving this
+ # whole guard exists to survive. Measured, not assumed. Leaving the reclaim in
+ # place is also the recoverable half: the definitions were bound to the session
+ # the user asked to clear, ``pause`` keeps them re-enablable, and the kept row is
+ # a superseded one the thread has already moved off.
+ reclaim_bound_definitions(conn, session_id, mode=reclaim_mode, reason=reclaim_reason)
+ removed = bool(
+ conn.execute(
+ agent_sessions.delete()
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.id.in_(id_query))
+ ).rowcount
+ )
+ if not removed:
+ logger.warning(
+ "Skipped hard-deleting session %s: it stopped matching the teardown "
+ "query concurrently (superseded, re-anchored or already gone)",
+ session_id,
+ )
+ continue
+ deleted += 1
+ return deleted
+
+
def _new_session_id(used: set[str]) -> str:
while True:
value = "ses" + "".join(secrets.choice(SESSION_ID_ALPHABET) for _ in range(10))
@@ -1165,12 +1751,53 @@ def _find_agent_session_row_id(
.limit(1)
).scalar_one_or_none()
if legacy_row_id:
- conn.execute(
+ # The predicates RE-ASSERT what the SELECT above decided, because that read
+ # reserves nothing: pysqlite emits no ``BEGIN`` for a bare SELECT, so the
+ # write lock is taken here, at the first DML. Both callers reach this
+ # function through ``resolve_scope_from_legacy_key``, which for the 2-part
+ # key form (``slack::C1``) that ``build_context_session_key`` emits for
+ # ordinary channel / thread turns returns after a pure SELECT -- so the
+ # window is open, exactly as in the sibling writers (HFR-251..254).
+ #
+ # A bare ``id`` match had the HFR-253 shape twice over. It relabelled a row
+ # whose placeholder backend a concurrent claim had already filled with a
+ # CONCRETE backend -- so the row came out labelled with this caller's
+ # backend while holding the winner's native id -- and it then RETURNED that
+ # id: ``ensure_agent_session_id`` hands its answer back unchanged, and
+ # ``BaseAgent.ensure_agent_session_id`` pins any non-empty id into
+ # ``context.platform_specific['agent_session_id']`` without ever
+ # re-resolving, so an archive committed inside the window (terminal, and
+ # filtered out by every read here, ``base_query`` included) was handed to the
+ # turn as its session.
+ relabelled = conn.execute(
agent_sessions.update()
.where(agent_sessions.c.id == legacy_row_id)
+ # Still live: an archive vacates the anchor and is terminal.
+ .where(agent_sessions.c.status != "archived")
+ # Still a placeholder. That is the whole justification for relabelling
+ # in place (a blank / "default" label names no previous backend, so
+ # nothing on the row can belong to a different one); once another claim
+ # has filled it, the justification is gone.
+ .where(agent_sessions.c.agent_backend.in_(["", "default"]))
+ .where(agent_sessions.c.agent_variant.in_(["", "default"]))
.values(agent_backend=backend, agent_variant=backend)
)
- return legacy_row_id
+ if relabelled.rowcount:
+ return legacy_row_id
+ # LOST the race: answer "no row for this (scope, anchor, backend)", which is
+ # what this function returns when the read finds nothing at all. The two
+ # callers then resolve the anchor through
+ # ``get_or_create_agent_session_row``, whose reads exclude archived rows and
+ # whose writes are individually guarded -- so the outcome converges with the
+ # serial order (winner first, then this caller) instead of this caller
+ # deciding a second time from the snapshot it was just refused for.
+ logger.warning(
+ "Lost the placeholder-relabel race for session %s; re-resolving the "
+ "anchor instead (requested backend=%s)",
+ legacy_row_id,
+ backend,
+ )
+ return None
return None
return conn.execute(
base_query.where(agent_sessions.c.agent_variant == requested).limit(1)
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 383b0b071..75a96db92 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -30,6 +30,11 @@ from storage.agent_session_rows import (
new_session_id,
)
from storage.db import escape_sql_like
+from storage.session_reclaim import (
+ RECLAIM_DELETE,
+ reclaim_bound_definitions,
+ reconcile_explicit_overrides,
+)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.models import (
agent_runs,
@@ -528,6 +533,24 @@ def update_session(
else f"{target_scope.platform}_{target_scope.native_id}:session_{session_id}"
)
+ # A PRESENT ``model`` / ``reasoning_effort`` -- any value, including ``None``
+ # -- replaces whatever this session pinned, so its explicit-override marker
+ # must go with it. The Chat header's "Default" item sends present nulls for
+ # the whole route; a marker left behind keeps telling dispatch that this
+ # session pins NULL on purpose, and "Default" then persists and displays a
+ # cleared model while the turn still runs without the Agent's default. Written
+ # LAST and composed onto the same ``existing_metadata`` the title / scope-move
+ # branches above already edited, so one UPDATE carries every metadata change
+ # and an unrelated edit leaves untouched marker entries alone.
+ replaced_settings = [
+ name
+ for name, value in (("model", model), ("reasoning_effort", reasoning_effort))
+ if value is not _UNSET
+ ]
+ if replaced_settings:
+ existing_metadata = reconcile_explicit_overrides(existing_metadata, cleared=replaced_settings)
+ values["metadata_json"] = _dumps_metadata(existing_metadata)
+
stmt = update(agent_sessions).where(agent_sessions.c.id == session_id)
if backend_changes:
# Re-assert the lock INSIDE the UPDATE: the guard above is read-then-
@@ -948,11 +971,14 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
# 2) Soft-delete bound scheduled tasks + watches (same table, distinguished by
# ``definition_type``). Deleting — not pausing — is deliberate: a paused
# definition could be re-enabled later and would then target a dead session.
- conn.execute(
- update(run_definitions)
- .where(run_definitions.c.session_id == session_id)
- .where(run_definitions.c.deleted_at.is_(None))
- .values(deleted_at=now, updated_at=now)
+ # Shared with the hard-delete teardown path, which passes ``pause`` instead
+ # (``/new`` is an everyday command, archive is terminal); the mode is
+ # required so a new caller cannot inherit this branch by omission.
+ reclaim_bound_definitions(
+ conn,
+ session_id,
+ mode=RECLAIM_DELETE,
+ reason=f"archive_session:{session_id}",
)
# 3) Cancel not-yet-terminal runs for this session. Flag every active run as
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 01d0d149b..75e378926 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -33,6 +33,11 @@ capabilities:
- tests/test_cli_pagination.py
- tests/test_codex_transport.py
- tests/test_internal_server.py
+ - tests/test_session_archive.py
+ - tests/test_sqlite_sessions_store.py
+ - tests/test_agent_run_target.py
+ - tests/test_watches.py
+ - tests/test_cli_watch_command.py
- id: auth_setup
name: IM-driven backend auth recovery
status: active
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 5c0b58f33..5cc7d178b 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -350,6 +350,1080 @@ scenarios:
layer: contract
backend: shared
test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_backfill_refuses_success_text_on_a_failed_run
+ - id: HFR-049
+ name: clearing a session pauses bound definitions instead of orphaning them
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_session_archive.py::test_delete_agent_sessions_reclaims_bound_definitions
+ - id: HFR-050
+ name: shared reclaim keeps archive terminal while /new stays recoverable
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_session_archive.py::test_archive_still_soft_deletes_bound_definitions
+ - id: HFR-051
+ name: models declare the (scope, anchor) session invariant
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_models_declare_scope_anchor_unique_index
+ - id: HFR-052
+ name: a same-anchor row owned by another backend is adopted, not collided with
+ status: covered
+ kind: failure_recovery
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_adopts_row_owned_by_other_backend
+ - id: HFR-053
+ name: find-then-create loses the session-row race gracefully
+ status: covered
+ kind: idempotency
+ layer: contract
+ backend: shared
+ test: tests/test_agent_run_target.py::test_resolve_agent_run_target_tolerates_concurrent_row_insert
+ - id: HFR-054
+ name: an unresolvable pinned session pauses its definition and notifies once
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_execute_task_pauses_and_notifies_when_pinned_session_is_missing
+ - id: HFR-055
+ name: a create_once definition rebinds instead of failing forever
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_create_once_rebinds_when_session_deleted
+ - id: HFR-056
+ name: a rebind preserves the deleted session's agent and model
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_rebind_preserves_model_of_the_deleted_session
+ - id: HFR-057
+ name: superseding a bound session preserves its thread routing
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_superseding_a_bound_row_keeps_its_thread_routing
+ - id: HFR-058
+ name: a paused watch is given watch commands, not task commands
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_command_handler_user_names.py::CommandHandlerUserNameTests::test_new_command_gives_watches_their_own_recovery_commands
+ - id: HFR-059
+ name: a prefix clear does not hard-delete a superseded row
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_prefix_clear_does_not_delete_a_superseded_row
+ - id: HFR-240
+ name: the backend-wide clear does not delete a superseded row
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_backend_wide_clear_does_not_delete_a_superseded_row
+ - id: HFR-241
+ name: the superseded exclusion still deletes a row carrying no marker
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_backend_wide_clear_still_deletes_a_rows_with_an_empty_anchor
+ - id: HFR-242
+ name: /new end to end keeps a superseded session and its bound definitions
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_command_handler_user_names.py::NewCommandStorageIntegrationTests::test_new_keeps_a_superseded_session_and_its_definitions_but_clears_the_live_one
+ - id: HFR-243
+ name: a rebind whose snapshot Agent is gone falls back to scope defaults
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_rebind_falls_back_to_scope_defaults_when_the_snapshot_agent_is_gone
+ - id: HFR-244
+ name: a snapshot's null model survives the rebind instead of adopting the Agent's
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_scheduled_tasks.py::test_rebind_keeps_a_snapshot_null_model_instead_of_adopting_the_agents
+ - id: HFR-245
+ name: an unrelated task update keeps the rebound session's Agent authority
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ # The schema carries one path, so this stays the primary test. A second test
+ # covers the same id in the report's literal order (unrelated edit BEFORE the
+ # default moves), where the persisted-state assertion is the load-bearing one:
+ # tests/test_scheduled_tasks.py::test_unrelated_task_update_keeps_the_follow_state_before_the_default_moves
+ test: tests/test_scheduled_tasks.py::test_unrelated_task_update_keeps_the_rebound_sessions_agent_authority
+ - id: HFR-246
+ name: adopting an unbound row replaces the old backend's whole route
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_legacy_adoption_replaces_the_whole_route_of_an_unbound_row
+ - id: HFR-247
+ name: the workbench Default action drops the explicit-override marker
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_core_services_sessions.py::test_workbench_default_action_drops_the_explicit_override_marker
+ - id: HFR-248
+ name: forking an explicit-null session copies its pins, not just its nulls
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ test: tests/test_session_fork.py::test_forking_an_inherited_null_session_keeps_its_explicit_pins
+ - id: HFR-249
+ name: turn-start materialization never fills an explicitly pinned setting
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_sqlite_sessions_store.py::test_materialize_agent_session_route_never_fills_an_explicitly_pinned_field
+ - id: HFR-250
+ name: a native bind by id replaces the whole route of an unbound row
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ # HFR-246 covers the (scope, anchor) adoption door (``_claim_anchor_row``); this
+ # is the second one, ``bind_agent_session_by_id``, which binds an explicitly
+ # targeted reserved row. Two companion tests hold the edges: an already-bound
+ # row keeps its backend identity (write-once), and an ordinary same-backend bind
+ # keeps the row's model / reasoning_effort and their marker.
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_keeps_the_backend_of_an_already_bound_row
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_keeps_the_pins_of_a_same_backend_bind
+ test: tests/test_sqlite_sessions_store.py::test_native_bind_by_id_replaces_the_whole_route_of_an_unbound_row
+ - id: HFR-251
+ name: a native bind by id that loses the race leaves the winner's row intact
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # kind=safety, not idempotency: two DIFFERENT callers with different natives and
+ # different Agent identities are not repeats of one another, so there is no
+ # "same call twice" to be idempotent about. What must hold is that losing the
+ # race destroys NOTHING the winner owns -- not merely "the write-once native id
+ # survives". The winner's native, backend, Agent id / name / variant,
+ # model / reasoning_effort, explicit-override marker, status and
+ # updated_at / last_active_at all stand. HFR-250 fixed WHAT the adoption branch
+ # writes; this covers WHEN it is allowed to, since its snapshot reads reserve
+ # nothing and SQLite only locks at the UPDATE.
+ # Three halves, one window. The two same-backend first-bind halves cover the
+ # branch where _set_native_once's SELECT was the only thing enforcing
+ # write-once, and specifically the two routes through the fall-through that
+ # dropped the identity columns only when requested_backend != winner_backend --
+ # the loser naming the winner's own backend (comparison equal), and the loser
+ # naming no backend at all (comparison cannot fire). Both were red asserting
+ # the winner's Agent identity and timestamps while its native id stood:
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_loses_a_concurrent_first_bind_without_a_requested_backend
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_loses_a_concurrent_same_backend_first_bind
+ test: tests/test_sqlite_sessions_store.py::test_native_bind_by_id_loses_a_concurrent_cross_backend_adoption
+ - id: HFR-252
+ name: a session archived mid-bind stays archived, whichever branch the bind takes
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The third read in bind_agent_session_by_id -- the status SELECT that refuses
+ # archived rows -- has the same read-then-write shape HFR-251 closed twice, but
+ # it decides no write: all three UPDATEs re-assert status != 'archived'
+ # themselves, so a late archive makes the write a no-op and the call returns
+ # None. So this entry is a PROOF, green before it was written, not a red-green
+ # regression. It exists because nothing failed if a future edit dropped one of
+ # those predicates and left the SELECT to "guard" the write; each case was
+ # confirmed to fail with its own predicate removed, one statement each.
+ # The other two statements: the cross-backend adopt, and the idempotent re-bind
+ # that is the only shape reaching the final UPDATE (write-once declines, so it
+ # is a bare id match carrying status='active'):
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_cannot_adopt_a_session_archived_inside_its_window
+ # tests/test_sqlite_sessions_store.py::test_native_bind_by_id_idempotent_rebind_cannot_resurrect_an_archived_session
+ test: tests/test_sqlite_sessions_store.py::test_native_bind_by_id_cannot_resurrect_a_session_archived_inside_its_window
+ - id: HFR-253
+ name: >-
+ an anchor relabel that loses the race leaves the winner's row intact and
+ returns no id for an archived winner
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The THIRD writer with the HFR-251 shape, and the one that re-asserted nothing
+ # at all: _claim_anchor_row's unbound branch decided "relabel this row to the
+ # incoming backend and replace its whole route" and then issued
+ # UPDATE ... WHERE id = ?, with no write-once, no backend and no archive
+ # predicate -- while its sibling bind_agent_session_by_id, added by the same PR,
+ # got all three. Production path: the channel Agent switches to Claude while the
+ # previous Codex turn is still finishing, so the Codex native id commits inside
+ # the window and the row comes out agent_backend='claude' holding a Codex native.
+ # The scope key is part of the mechanism: a 3-part key (slack::channel::C1)
+ # upserts the scope first, so the transaction already holds the write lock and the
+ # window does not exist; only the 2-part form build_context_session_key emits for
+ # ordinary channel/thread turns is exposed.
+ # The paired half covers the same window with a terminal archive as the competing
+ # write:
+ # tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_cannot_relabel_a_row_archived_inside_its_window
+ # THE INVARIANT IS WIDER THAN THE ROW: what the function RETURNS is part of it.
+ # Guarding the UPDATE stopped the relabel, but the lost-race path still handed
+ # back the winner's id even when the winner ARCHIVED the row -- and an archive is
+ # terminal, vacates the anchor, and is filtered out by every read path here. There
+ # is no later re-resolve to correct it: BaseAgent.ensure_agent_session_id pins any
+ # non-empty answer into context.platform_specific['agent_session_id'] and the turn
+ # runs against that row. So a lost relabel whose winner archived yields NO usable
+ # session: None, propagated through get_or_create_agent_session_row ->
+ # SQLiteSessionsService.ensure_agent_session_id, which is what the two sibling
+ # bind paths already answer for the same interleaving -- and NOT a fresh row,
+ # which would be a second write decided from the snapshot the relabel was just
+ # refused for. A LIVE bound winner is a real session, so the primary test pins the
+ # other answer just as explicitly: its id is still returned. Asserted at the
+ # storage boundary by both halves and end to end (the id is never pinned into the
+ # turn context) by:
+ # tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_archive_race_never_pins_an_agent_session_id
+ test: tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_cannot_relabel_a_row_bound_inside_its_window
+ - id: HFR-254
+ name: the legacy-scope native bind destroys nothing a concurrent winner owns
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # bind_agent_session is the legacy-scope twin of bind_agent_session_by_id and was
+ # missed by HFR-251/252: _set_native_once is a preceding SELECT, and the UPDATE
+ # acting on its answer carried neither coalesce(native_session_id,'') = '' nor
+ # status != 'archived' while unconditionally setting status='active'. One
+ # competing commit inside that window therefore lost its write-once native AND
+ # had its terminal archive undone, with the losing caller reporting success.
+ # The invariant is the same as HFR-251's and is NOT just write-once + archive:
+ # losing the race must destroy NOTHING the winner owns -- its native id, its
+ # Agent id / name / variant, model / reasoning_effort and the explicit-override
+ # marker, its status, and its updated_at / last_active_at all stand.
+ # Two halves, one window. The archive half asserts the write-once native, the
+ # surviving archive and the None return. The identity half is the one the first
+ # fix reintroduced and had to close a second time: with a LIVE winner the
+ # rowcount-0 first bind FELL THROUGH to the final UPDATE, whose shared values
+ # dict carries status='active', both timestamps and the caller's agent_id /
+ # agent_name, so the loser stamped its own Agent identity and clock over the
+ # winner while the native id stood. An archived winner hides it -- that write is
+ # refused wholesale by status != 'archived'. Same correction as the twin's:
+ # tests/test_sqlite_sessions_store.py::test_bind_agent_session_loses_a_concurrent_same_backend_first_bind
+ # The 2-part scope key (slack::C4) is part of the mechanism: a 3-part key upserts
+ # the scope, taking the write lock before the window opens.
+ test: tests/test_sqlite_sessions_store.py::test_bind_agent_session_keeps_the_native_of_a_row_bound_inside_its_window
+ - id: HFR-255
+ name: vibe task update rejects --agent together with --clear-agent
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ # The follow-the-session marker (HFR-245) was defeatable in ONE command. The pair
+ # honoured neither flag: --clear-agent won for agent_name (-> None) while the mere
+ # presence of --agent set explicit_agent_requested, which POPS the marker, so the
+ # definition looked like "unpinned and not following its Session" and the resolve
+ # wrote today's scope/default Agent back as a hard pin. Fixed by rejecting the
+ # contradictory pair, the convention --name / --clear-name already uses; the test
+ # asserts both pairs so they cannot drift apart.
+ # The sibling hole in vibe watch update is closed by HFR-256.
+ test: tests/test_cli_task_command.py::test_task_update_rejects_agent_together_with_clear_agent
+ - id: HFR-256
+ name: vibe watch update keeps the bound Session's Agent authority
+ status: covered
+ kind: safety
+ layer: scenario
+ backend: shared
+ # cmd_watch_update is the sibling definition command over the same run_definitions
+ # rows and had NO follow-the-session logic at all: --clear-agent / --agent were a
+ # silent if/elif with no contradictory-pair rejection, and the command then ran the
+ # same "agent_name is None and session_policy != 'existing'" re-resolution as the
+ # task side, writing today's scope/default Agent back as a HARD PIN. So
+ # --clear-agent was silently undone, and any unrelated edit (--name) re-pinned a
+ # watch whose Agent authority belonged to its Session. Parity fix: reuse
+ # BINDING_FOLLOWS_SESSION_METADATA_KEY, keep all three durable states
+ # (clear/follow, preserve on unrelated edits, exit on explicit --agent), and reject
+ # --agent together with --clear-agent (HFR-255's shape).
+ # The proof is NOT the CLI payload: after the unrelated edit the scope default is
+ # moved and the watch is FIRED through its production path -- the real
+ # ManagedWatchService._run_watch reads the STORED definition, _enqueue_hook queues a
+ # "watch" request carrying agent_name, and the real ScheduledTaskService
+ # claim/execute path hands it to the real MessageHandler. The assertions are on the
+ # AgentRequest that handler built (Agent identity, backend, system prompt). Only the
+ # waiter subprocess is stubbed.
+ # NOTE: _recover_pinned_session_binding (the reset-rebind writer of the marker) is
+ # reached only from _execute_task and takes a ScheduledTask, so it never runs for a
+ # watch definition; a watch enters the state through --clear-agent. Extending reset
+ # rebinding to watches is a separate change.
+ # The contradictory-pair half:
+ # tests/test_cli_watch_command.py::test_watch_update_rejects_agent_together_with_clear_agent
+ test: tests/test_scheduled_tasks.py::test_unrelated_watch_update_keeps_the_follow_session_agent_authority
+ # HFR-257..260 are the rest of the SET. HFR-251..254 each closed one instance of the
+ # same defect -- decide from a SELECT, then write with a predicate that re-asserts
+ # nothing -- one per review round, in the BIND writers. These four come from
+ # enumerating every UPDATE / INSERT / DELETE in storage/session_reclaim.py,
+ # storage/agent_session_rows.py and on their teardown call path and asking the same
+ # question of each, so the class is closed rather than sampled again.
+ - id: HFR-257
+ name: a reclaim that loses to a repoint changes nothing and is reported to nobody
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # reclaim_bound_definitions read every live definition bound to the dying session
+ # and then wrote WHERE run_definitions.id = ? alone. The hard-delete path
+ # (_delete_agent_session_rows) reaches it after nothing but reads -- a resolved
+ # 2-part scope key never upserts -- so a user repointing that task/watch to another
+ # Session (upsert_scheduled_task, a full-row UPDATE) inside the window had the
+ # definition paused on its NEW live binding, with its session_settings_snapshot
+ # overwritten by the DEAD session's settings; that snapshot is what a later
+ # create_once rebind reads, so the task would return on the wrong model / agent.
+ # Guarded by re-asserting both halves of what the read decided: session_id = <the
+ # binding this reclaim is for> AND deleted_at IS NULL.
+ # THE ACCOUNTING IS THE OTHER HALF, and it is a user-visible invariant, not
+ # bookkeeping: the returned summary is what the archive confirm dialog reports and
+ # the ledger is what /new counts in its reply, so both are credited only on
+ # rowcount. Measured at b366384b: summary {'paused': 1, 'snapshotted': 1} and a
+ # ledger entry for a definition that was never the teardown's to touch.
+ # The /new half drives the production path (delete_agent_sessions ->
+ # _delete_agent_session_rows -> reclaim, inside the command handler's
+ # session_teardown_context) with two definitions, so the ledger has to name exactly
+ # the one that did NOT move:
+ # tests/test_sqlite_sessions_store.py::test_new_teardown_path_reports_only_the_definitions_it_reclaimed
+ test: tests/test_sqlite_sessions_store.py::test_reclaim_leaves_a_definition_repointed_inside_its_window_alone
+ - id: HFR-258
+ name: a lost anchor supersede returns the winning session instead of raising
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The SECOND branch of _claim_anchor_row, and the one HFR-253 left behind: it
+ # guarded the relabel and not the supersede. Two turns on one thread claim a bound
+ # row for a new backend; the winner moves the anchor aside and inserts its
+ # replacement, then the loser's UPDATE ... WHERE id = ? "succeeds" (it re-supersedes
+ # an already-moved anchor), reports the slot freed, and falls into
+ # create_agent_session_row -- whose INSERT collides with the winner's replacement on
+ # the UNIQUE (scope_id, session_anchor) index. Red at b366384b with
+ # IntegrityError: UNIQUE constraint failed: agent_sessions.scope_id,
+ # agent_sessions.session_anchor escaping ensure_agent_session_id.
+ # Guarded by re-asserting status != 'archived', the anchor the row was resolved by,
+ # and the backend the branch decided against; on rowcount 0 the current anchor
+ # HOLDER is re-read and returned (None when it archived or is gone, which is what
+ # every caller of get_or_create_agent_session_row already handles). What the
+ # function RETURNS is part of the invariant, exactly as in HFR-253.
+ test: tests/test_sqlite_sessions_store.py::test_anchor_supersede_returns_the_winner_of_a_concurrent_supersede
+ - id: HFR-259
+ name: the placeholder relabel never hands back a row it lost the race for
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # _find_agent_session_row_id runs BEFORE get_or_create_agent_session_row on both
+ # bind entry points, and its legacy branch is itself a read-then-write: select a row
+ # whose agent_backend / agent_variant are still the blank / "default" placeholder,
+ # then relabel it with UPDATE ... WHERE id = ? and RETURN that id. Two ways to lose,
+ # both asserted. An archive committed inside the window was relabelled and then
+ # handed back -- and ensure_agent_session_id returns its answer unchanged while
+ # BaseAgent.ensure_agent_session_id pins any non-empty id into
+ # context.platform_specific['agent_session_id'] without re-resolving, so the turn ran
+ # against a terminal row (HFR-253's invariant, in a different function). A concurrent
+ # concrete-backend claim was overwritten, leaving the row labelled with this caller's
+ # backend while holding the winner's write-once native id.
+ # The answer on loss is None -- what this finder already returns when it sees nothing
+ # usable -- so the caller re-resolves through the guarded (scope, anchor) path and
+ # converges with the serial order instead of deciding twice from one snapshot.
+ # The identity half:
+ # tests/test_sqlite_sessions_store.py::test_placeholder_relabel_cannot_overwrite_a_backend_claimed_inside_its_window
+ test: tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_never_returns_a_placeholder_archived_inside_its_window
+ - id: HFR-260
+ name: a /new clear keeps a session superseded inside its window
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # _delete_agent_session_rows evaluated the WHOLE teardown query -- scope, agent-name
+ # match and the include_superseded=False guard -- in the id READ, before any write
+ # lock existed, then hard-deleted by id list. Superseding PROMISES the row is kept
+ # (write-once native id, unrecoverable transcript), so a supersede committed inside
+ # that window made /new hard-delete exactly the row the guard protects, and count it.
+ # Fixed by re-running id_query inside the DELETE, which re-evaluates every predicate
+ # under the lock whichever caller built them, and returning only rows actually
+ # removed.
+ # DELIBERATELY NOT ROLLED BACK: the reclaim runs first (it needs both rows visible
+ # for the settings snapshot), and wrapping the pair in a SAVEPOINT makes it worse --
+ # under WAL the SAVEPOINT opens the transaction before the reclaim's own SELECT, so
+ # the read pins a snapshot and the reclaim UPDATE fails with SQLITE_BUSY_SNAPSHOT on
+ # this very interleaving (measured). The pause therefore stands and the ledger says
+ # so; pause is the recoverable mode and the kept row is one the thread has moved off.
+ test: tests/test_sqlite_sessions_store.py::test_new_teardown_keeps_a_session_superseded_inside_its_window
+ # HFR-261..262 continue the same class from the OTHER side. HFR-249..260 guarded the
+ # writers that decide from a read one statement earlier; these two are the writer whose
+ # read is a whole LAYER earlier (a CLI command's payload) and the one race a guarded
+ # statement cannot answer at all -- there the loser is refused the write lock outright,
+ # so the remedy is to hold the lock from before the read rather than re-assert it.
+ - id: HFR-261
+ name: a full-row definition write cannot undo the reclaim it lost to
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # upsert_scheduled_task and upsert_watch write EVERY column of run_definitions from a
+ # payload the caller built out of a read one layer up (vibe task/watch update reads
+ # the definition, then resolves Agents, Sessions and delivery targets before writing).
+ # A reclaim committed in that window -- /new or the archive dialog, whose own CAS was
+ # closed by HFR-257 -- was then silently REVERTED: the stale payload restored
+ # session_id, enabled, deleted_at (no in-memory definition even carries the column, so
+ # it was always written back as NULL, resurrecting a soft-deleted task) and the
+ # pre-teardown metadata_json, including the session_settings_snapshot a later
+ # create_once rebind reads for the dead session's workdir/agent/model (D3). The
+ # reclaim's counters and the /new ledger had already told the user "1 task paused".
+ # PREDICATE SET = the state teardown owns: session_id, enabled, deleted_at, and the
+ # snapshot's captured_at. The fourth is not redundant: for an ALREADY-paused
+ # definition the reclaim changes none of the first three, it only refreshes the
+ # snapshot. Deliberately NOT updated_at / the whole row -- a version guard would
+ # refuse a rename racing a run-result stamp and turn a working edit into an error.
+ # Both writers share one guarded statement (_upsert_definition) and the
+ # unchanged_text idiom of storage/agent_session_rows.py, so the pair cannot drift.
+ # CALLERS: vibe task update / vibe watch update and pause/resume raise
+ # DefinitionWriteConflict -> exit 1 with code definition_write_conflict (a lost write
+ # must not be reported as an applied edit); the runtime stamps (mark_task_result,
+ # mark_cycle_start/result, record_binding_recovery) return False and reload the
+ # mirror; the reset-rebind persist logs and keeps the rebind for that fire only.
+ # The watch half, same window, same command shape:
+ # tests/test_cli_watch_command.py::test_watch_update_refuses_to_undo_a_reclaim_committed_after_its_read
+ # The deleted_at half (archive + an in-flight run's result stamp):
+ # tests/test_scheduled_tasks.py::test_task_result_stamp_cannot_resurrect_a_definition_the_archive_deleted
+ # The snapshot-marker half (the reclaim shape the lifecycle guards cannot see):
+ # tests/test_scheduled_tasks.py::test_cycle_result_cannot_restore_the_metadata_a_snapshot_refresh_replaced
+ test: tests/test_cli_task_command.py::test_task_update_refuses_to_undo_a_reclaim_committed_after_its_read
+ - id: HFR-262
+ name: a first-turn insert holds the write lock across the reads it decides from
+ status: covered
+ kind: reliability
+ layer: contract
+ backend: shared
+ # get_or_create_agent_session_row's create branch READ and then wrote with no lock
+ # between: SAVEPOINT opened the transaction and new_session_id's scan pinned a WAL read
+ # snapshot inside it, so a competing first turn committing between that scan and the
+ # INSERT left the loser unable to become a writer at all. SQLite answers
+ # SQLITE_BUSY_SNAPSHOT (extended code 517) -- a PLAIN OperationalError whose primary
+ # code and "database is locked" message are the ones every unrelated busy error
+ # carries -- and busy_timeout never retries it, because waiting cannot make a snapshot
+ # newer. Measured at ed4ddd93: 517 escaping ensure_agent_session_id on an ordinary
+ # first turn, from the shared get-or-create every platform reaches.
+ # MECHANISM: reserve_write_lock, called BEFORE the reads the INSERT decides from, so
+ # the failure cannot occur instead of being recovered from afterwards. The create path
+ # becomes the writer, re-reads the anchor under the lock, and only then inserts -- with
+ # one writer allowed, nothing it decided from can change, so neither SQLITE_BUSY_SNAPSHOT
+ # nor the UNIQUE-index IntegrityError is reachable there. Exactly the guarantee
+ # _claim_anchor_row's supersede branch already relied on (its anchor-move UPDATE takes
+ # the lock, which is why its own INSERT needs no re-read), now available to the paths
+ # with no write to lead with.
+ # WHY NOT DETECTION. Identifying 517 needs sqlite3.Error.sqlite_errorcode, which is
+ # Python 3.11+, while requires-python is >= 3.10. Verified on 3.10.12: the attribute is
+ # absent, the round-14 detect-and-retry fix let OperationalError("database is locked")
+ # escape a first turn, and the same test passed on 3.13 -- a fix that only works on
+ # some supported interpreters. Not producing the error needs nothing from the
+ # interpreter, so the 517 catch, its bounded retry, the SAVEPOINT and the
+ # "gave up, no usable session" answer are all DELETED rather than left unreachable.
+ # TWO SPELLINGS, ONE GUARANTEE, because SQLite has no LOCK TABLE: BEGIN IMMEDIATE when
+ # the connection is in autocommit (which is every entry point that resolves its scope
+ # with a pure SELECT, since pysqlite opens no transaction for a bare SELECT), and a
+ # never-matching UPDATE when a transaction is already open and BEGIN IMMEDIATE would be
+ # illegal (a 3-part scope key upserts the scope first). SQLite takes the write lock at
+ # the START of an UPDATE program, before its WHERE loop, which is pinned by a test
+ # rather than trusted.
+ # SCOPE: the create branch only. The read-mostly fast path where a session row already
+ # exists stays unlocked and keeps re-asserting its read inside the statement
+ # (unchanged_text, HFR-249..260), so no inbound message serialises on this. The window
+ # that remains -- a winner committing between the unlocked first read and the
+ # reservation -- is why the create re-decides under the lock, and is covered.
+ # COST: concurrent FIRST turns on one database queue behind each other for the length
+ # of the caller's transaction, bounded by busy_timeout (5s); the previous behaviour on
+ # that interleaving was an exception, not a faster answer.
+ # PROVEN AS A FACT, NOT AN ARGUMENT: a competing writer given busy_timeout = 0 must be
+ # REFUSED at the last read before the INSERT, checked for every production entry point
+ # and paired with a statement-sequence assertion that a reservation precedes that read.
+ # Both observations are version-independent, and the whole set passes on 3.10.12 and
+ # 3.13.5 and fails against both the pre-round-14 and the round-14 module.
+ # Every production path into the contested INSERT:
+ # tests/test_sqlite_sessions_store.py::test_every_first_turn_entry_point_reserves_the_write_lock
+ # tests/test_agent_run_target.py::test_resolve_agent_run_target_reserves_the_write_lock_for_its_first_turn_insert
+ # The window kept open on purpose, and the reserved re-read that closes it:
+ # tests/test_sqlite_sessions_store.py::test_first_turn_insert_joins_a_winner_that_committed_before_the_reservation
+ # The never-matching UPDATE actually takes the lock and changes nothing:
+ # tests/test_sqlite_sessions_store.py::test_write_lock_reservation_takes_the_lock_without_touching_a_row
+ test: tests/test_sqlite_sessions_store.py::test_first_turn_insert_reserves_the_write_lock_before_the_reads_it_decides_from
+ # WHAT THE WHOLE-ROW-WRITER HUNT FOUND, and what the id HFR-263 actually holds now.
+ # The hunt for a THIRD whole-row writer that could clobber a guarded transition came
+ # back empty, and that negative still stands: the only one found is
+ # SQLiteSessionsService.save_state (config/v2_sessions.py::SessionsStore.save →
+ # on_conflict_do_update over agent_sessions, which overwrites status /
+ # native_session_id / agent_backend / metadata_json from a legacy in-memory map), and
+ # it is the one DEFERRED instance, tracked as issue #1076 and not fixed here.
+ # HFR-263 was briefly recorded as "hunted, does not exist" on the strength of that
+ # negative. That was the wrong conclusion to draw from it: the hunt asked who ELSE
+ # writes whole rows, and the open question was the opposite one -- who CONSUMES a
+ # guarded write's refusal. HFR-263..266 are that question's answers, and the id
+ # HFR-263 now belongs to the watch consuming end below.
+ # HFR-263..266 are the CONSUMING end of the guards HFR-249..262 added. A guarded write
+ # that correctly refuses is only half an invariant: the caller still has to stop, and
+ # four of them did not. Two discarded the refusal outright (the watch supervisor's
+ # wrapper, the scheduled-fire result stamp), one discarded it and notified anyway, and
+ # one inferred a settled catalog fact from a broad catch and so read an infrastructure
+ # fault as one. Same shape as the guards themselves, one layer out: nothing that did
+ # not happen may be reported as though it had.
+ - id: HFR-263
+ name: a refused cycle-start stamp stops the watch before it runs anything
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # /new pauses a bound watch (reclaim, HFR-257) and replies "1 watch paused". The
+ # supervisor loop is already past its own maybe_reload, so it holds the pre-teardown
+ # mirror; mark_cycle_start is the guarded full-row write (HFR-261) that refuses that
+ # stale payload and returns False.
+ # THE HOLE WAS THE WRAPPER. _watch_store_call was `callback(); return True` -- it
+ # discarded the callback's own return value and reported the refusal to the loop as a
+ # landed write. The cycle then spawned its waiter subprocess and enqueued a hook into
+ # the session the teardown had just deleted, after /new told the user the watch was
+ # paused. Both the command execution and the delivery happen AFTER the stamp, so both
+ # are reachable from one discarded bool.
+ # FIX: guarded=True makes the callback's False a refusal the wrapper propagates, for
+ # mark_cycle_start and every mark_cycle_result site. Opt-in, not the default, because
+ # a False return is not universally a refusal -- maybe_reload returns False for
+ # "nothing changed", which is the common case and must not stop the watch. A refusal
+ # does NOT fuse the store: the database is healthy, this write simply lost.
+ # Driven through the REAL _run_watch with the reclaim committed from a second
+ # connection inside the write window; _run_cycle is the only double and returns a
+ # SUCCESS result on purpose, because on the unfixed wrapper that is what produces the
+ # hook the test forbids.
+ test: tests/test_watches.py::test_run_watch_stops_when_its_start_stamp_loses_to_a_reclaim
+ - id: HFR-264
+ name: a refused result stamp cannot complete the run ok
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The task twin of HFR-263, and the one that reaches the run ledger. A one-shot task
+ # fires, the user archives the bound Session mid-run, reclaim(mode='delete')
+ # soft-deletes the definition, and mark_task_result refuses the stale terminal stamp
+ # (HFR-261) -- last_run_at, last_error and the one-shot disable are not stored.
+ # _execute_task discarded that False and returned a TaskExecutionResult with
+ # error=None, so _execute_claimed_request completed the run ok=True: the database
+ # refused the stamp and BOTH the caller and agent_runs reported success. The user sees
+ # a green run for a task whose stored state never moved, and an `at` task that was
+ # never disabled can fire again.
+ # CARRIED ON THE EXISTING ERROR CHANNEL, deliberately: a non-empty `error` is already
+ # what makes complete(ok=not error) record a failure and what the CLI and the Harness
+ # detail pane show. No new settlement machinery, no notification/replay work. A real
+ # failure keeps its own message; only a would-be success gains one.
+ test: tests/test_scheduled_tasks.py::test_a_refused_result_stamp_cannot_complete_the_run_ok
+ - id: HFR-265
+ name: the deleted-Agent fallback has a type, so a fault cannot spend the route
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # _rebind_create_once_session tries the reclaim snapshot's settings first and falls
+ # back to a reset attempt that degrades to scope defaults. The fallback exists for
+ # exactly two facts -- the snapshot's Agent was deleted, or disabled (HFR-243) -- and
+ # it decided that from a BROAD `except Exception`, which cannot tell a settled catalog
+ # fact from SQLite contention, a migration failure or a filesystem error. On any of
+ # those the reset attempt then SUCCEEDED: _persist_task_session_id wrote the reset
+ # route, agent_name was dropped, binding_follows_session was stamped, and the task
+ # PERMANENTLY lost the Agent and model the snapshot was holding for it -- under a
+ # notice claiming the settings "could not be recovered". A transient fault became
+ # data loss. Same shape as the forbidden broad OperationalError retry: a catch wide
+ # enough to convert an infrastructure fault into silence.
+ # FIX: a typed contract. VibeAgentStore.require / require_enabled raise
+ # AgentUnavailableError(reason='missing'|'disabled'), and _reserve_runtime_session
+ # raises it with reason='no_default' for the absent default Agent; the fallback
+ # catches THAT and nothing else. Operational failures propagate, with the
+ # definition's route, lifecycle and durable metadata untouched and NO fallback
+ # reservation -- the run fails through _execute_claimed_request's existing handler and
+ # the next fire re-resolves from the stored row. AgentUnavailableError subclasses
+ # ValueError and keeps the old messages, so every existing `except ValueError` caller
+ # (CLI, UI server, controller route resolution) is unchanged, and HFR-243's
+ # missing-Agent fallback half stays green.
+ # The typed contract itself:
+ # tests/test_scheduled_tasks.py::test_agent_resolution_types_the_deleted_or_disabled_condition
+ test: tests/test_scheduled_tasks.py::test_rebind_propagates_an_operational_fault_instead_of_resetting_the_route
+ - id: HFR-266
+ name: a refused recovery record must not notify a transition it cannot dedup
+ status: covered
+ kind: reliability
+ layer: contract
+ backend: shared
+ # Found by the sweep HFR-263/264 prompted: the same question asked of every guarded
+ # write this PR added. _emit_binding_change promises "once per binding transition,
+ # never once per fire", and the ONLY thing that makes it once is the durable
+ # metadata.binding_recovery marker it writes first. That write is guarded (HFR-261)
+ # and refuses when the definition was reclaimed, repointed or removed in the window --
+ # and its False was ignored, so the notice went out with nothing behind it: a daily
+ # cron re-notifies every day, about a recovery the stored definition no longer
+ # reflects. The notification is now conditional on the marker landing.
+ # THE SWEEP'S OTHER ANSWERS, checked and NOT defects:
+ # * archive_session's `reclaimed` tally is taken BEFORE its reclaim, so it looks like
+ # the same shape -- but archive_session runs entirely inside one engine.begin() and
+ # takes the write lock at its first UPDATE, before both the count and the reclaim's
+ # read. Its reclaim cannot refuse, so the tally cannot diverge. Left alone.
+ # * /new's ledger already counts only landed writes (HFR-257), which is what
+ # "N tasks paused" reports.
+ # * vibe task/watch update and pause/resume raise DefinitionWriteConflict -> exit 1
+ # (HFR-261); _pause_task swallows it deliberately and documentedly (the teardown
+ # already applied the state it was going to write).
+ # CORRECTED BY HFR-268: this round also credited _persist_task_session_id's swallow
+ # as deliberate, on the strength of its own comment ("the rebind stands for one
+ # fire"). That was checking the return-value handling, not the ORDERING -- the fire
+ # goes on to dispatch a real turn on the unpersisted rebind. See HFR-268.
+ # * modules/agents/base.py's `bound or reserved_id` substitution after a refused
+ # by-id bind is pre-existing and deliberate: the reserved row is the publish target
+ # for the open Chat, not a claim that the native id was recorded. Not this PR's.
+ test: tests/test_scheduled_tasks.py::test_a_refused_recovery_record_does_not_notify_a_transition_it_cannot_dedup
+ - id: HFR-267
+ name: a watch cycle hook must be enqueued after its guarded stamp, never before
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # THE QUESTION THIS ROUND CHANGED. HFR-263..266 asked "does the caller respect the
+ # guard's answer?" and closed every site where it did not. That is not sufficient.
+ # Here the caller DID respect it -- and the side effect had already escaped.
+ # All four hook-enqueueing branches of _run_watch (success, per-cycle timeout,
+ # terminal failure, lifetime expiry) ran:
+ # self._enqueue_hook(...) # durable, unrecallable
+ # if not self._watch_store_call(..., guarded=True):
+ # return # refusal, too late
+ # enqueue_hook_send writes a request row a SEPARATE drain loop claims and executes,
+ # so `return` after the refusal unqueues nothing. When /new, an archive or a
+ # concurrent edit reclaims the watch mid-cycle, the guard correctly refuses the
+ # result stamp and the prompt is still delivered into the session the teardown
+ # deleted, for a definition the database has torn down -- after /new told the user
+ # "1 watch paused". A guard only means something when it runs BEFORE the effect it
+ # authorises. _stop_watch_for_missing_cwd already had that order; the four branches
+ # now match it, and _enqueue_hook carries the invariant in its docstring.
+ # Driven through the real _run_watch, with the real reclaim committed from a second
+ # connection inside the RESULT stamp's write window (occurrence-selected, so the
+ # start stamp is accepted first and the cycle genuinely ran). Each branch also has a
+ # control case proving it DOES deliver its own hook when the stamp lands, so the
+ # refusal cases cannot pass by never reaching the branch.
+ test: tests/test_watches.py::test_run_watch_enqueues_no_hook_when_the_result_stamp_is_refused
+ - id: HFR-268
+ name: a refused rebind must not dispatch the turn it was reserved for
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The ordering sweep HFR-267 prompted, applied to the task twin. Same class, one
+ # step subtler: the guard IS called first here and its answer is dropped rather than
+ # never requested. _persist_task_session_id swallowed DefinitionWriteConflict and
+ # returned None, so _recover_pinned_session_binding still reported action="rebound"
+ # with a new_session_id, and _execute_task dispatched a REAL agent turn -- prompt run,
+ # reply posted to the user's channel -- against a session whose binding the store had
+ # just refused to record. HFR-266's own notice went out too, saying "rebound to a new
+ # agent session X ... preserved" for a rebind that was never stored, because
+ # record_binding_recovery recomputes its expectation from the post-teardown mirror and
+ # so lands. The refusal also covers the soft-delete shape (expect.deleted_at is None),
+ # which is why "the rebind stands for THIS fire only" was not a safe reading of it.
+ # The persist now reports, and a refusal returns action="reclaimed" with no
+ # new_session_id -- the field _execute_task reads to decide whether to fire -- so the
+ # turn cannot run and both the durable error and the notice say what happened.
+ # RESIDUE, stated rather than hidden: the replacement session row is reserved before
+ # the guarded write, because the write needs the id it produces. A refusal therefore
+ # leaves one unreferenced background session row, the same residue create_per_run
+ # leaves by design. No user-visible effect escapes; the row does.
+ test: tests/test_scheduled_tasks.py::test_execute_task_does_not_dispatch_when_the_rebind_persist_is_refused
+ - id: HFR-269
+ name: >-
+ a guarded stamp and the outbox row it authorises must be one transaction: no
+ teardown commits between them, and a failed outbox write retires nothing
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # THE QUESTION THIS ROUND CHANGED AGAIN. HFR-263..266 asked "does the caller respect
+ # the guard's answer?"; HFR-267 asked "does the guard run before the effect?". Both
+ # are true here and the guard still fails, because TWO COMMITS ARE NOT ONE DECISION:
+ # self.store.mark_cycle_result(...) # transaction 1, COMMITS
+ # self.request_store.enqueue_hook_send(...) # transaction 2, COMMITS
+ # A /new reclaim or an archive from another connection commits in the GAP between
+ # those commits. The stamp is accepted -- it won its compare-and-set fairly, against
+ # the state that existed when it ran -- and the hook is queued afterwards anyway:
+ # a durable request row the drain loop delivers into a session the teardown deleted,
+ # under a definition it paused or soft-deleted, after the user was told so. Nothing
+ # is refused, because by then there is nothing left to refuse. HFR-267 moved the race
+ # window; it could not close it.
+ # THE INVERSE HFR-267 INTRODUCED: a fault between the two commits (full disk, locked
+ # database) left a once/terminal watch durably DISABLED with its completion hook
+ # LOST -- the definition says "finished", the user was never told, nothing runs it
+ # again. One failure traded for another.
+ # STEP 1, THE FACT THAT DECIDED THE FIX: run_definitions (the definition) and
+ # agent_runs (the outbox) are two tables in ONE SQLite database. Both stores default
+ # to paths.get_sqlite_state_path() -- ManagedWatchStore._sqlite and
+ # TaskExecutionStore._sqlite are separate SQLiteBackgroundTaskStore instances over
+ # the same file -- so one transaction is available and is the honest fix, not
+ # claim-time validation. Both stores also have FILE backends (a JSON file of watches,
+ # a directory of run JSON files), used only by tests and legacy state; those cannot
+ # share a transaction, and they also have no compare-and-set at all
+ # (ManagedWatchStore._write_watch returns True unconditionally without SQLite), so
+ # there is no guard there for a teardown to outrun. _shared_run_ledger_backend states
+ # that choice per configuration instead of assuming it.
+ # FIX: upsert_watch_with_queued_run commits the guarded run_definitions UPDATE and
+ # the agent_runs INSERT on one connection, guard first, and _commit_cycle_result is
+ # the single idiom all five result-stamp sites in _run_watch use (success, per-cycle
+ # timeout, terminal failure, lifetime expiry, missing cwd). A refusal or an exception
+ # rolls back BOTH, which removes the inverse instead of reversing it.
+ # THE SEPARATE-TRANSACTIONS SWEEP, and why the rest are not this defect:
+ # * mark_cycle_start -> spawning the waiter subprocess, and _persist_task_session_id /
+ # record_binding_recovery -> dispatching a turn or sending a notice: the authorised
+ # effect is a process or a network send, so no transaction can contain it. Ordering
+ # (HFR-267/268) plus a guarded terminal stamp is the whole available guarantee.
+ # * mark_task_result -> the run-ledger settlement is REPORTING of an effect that
+ # already happened, not an effect the stamp authorises; HFR-264 made it report the
+ # refusal.
+ # * _run_task's enqueue and enqueue_session_callback are authorised by a READ, not by
+ # a guarded write, and both dedup on re-entry (pending-run scan, find_callback_run).
+ # * delete_agent_sessions/archive_session run the reclaim inside the caller's
+ # transaction already; reserve_forked_session is one begin() for reads and insert;
+ # settle_run_terminal/claim_pending_run publish their events after the commit.
+ # * _drain_callbacks writes the callback run and THEN marks it sent -- effect before
+ # marker -- but the marker is not a guard and the enqueue is idempotent through
+ # find_callback_run.
+ # Driven through the real _run_watch over the real agent_runs ledger, with the real
+ # archive reclaim attempted from a second connection at the instant the outbox INSERT
+ # is about to run and PRAGMA busy_timeout = 0, so "could a teardown commit in the
+ # gap?" is answered by the database rather than by a sleep.
+ # ONE ID, TWO FAILURE HALVES. The schema carries one path, so the teardown-in-the-gap
+ # half stays the primary test. The INVERSE half is the same defect and the same id,
+ # tested separately because it fails for the opposite reason -- no teardown, no race,
+ # just a fault on the second commit, which left the watch disabled and retired with
+ # the hook that reports it gone (a once watch is unrecoverable there). Sharing the
+ # transaction rolls both back together, so the watch stays enabled and its completion
+ # is still owed; the fault is injected at the INSERT itself, on whichever connection
+ # the code under test writes the row through:
+ # tests/test_watches.py::test_a_failed_outbox_write_does_not_retire_the_watch_with_its_hook_lost
+ # SUCCESSFUL CONTROL PER TERMINAL BRANCH, so the contract cannot pass by refusing
+ # everything: with no teardown and no injected fault, the transaction must COMMIT and
+ # carry both halves -- the branch's own result transition read back from the
+ # definition, and exactly one outbox row with that branch's own prompt text. All five
+ # hook-producing branches, and every parametrized test here shares the same
+ # _HOOK_BRANCHES table so a new branch cannot be added without its control:
+ # tests/test_watches.py::test_the_atomic_stamp_and_its_hook_both_land_when_nothing_races_them
+ test: tests/test_watches.py::test_no_teardown_can_commit_between_the_result_stamp_and_its_hook
+ - id: HFR-270
+ name: a refused rebind must reclaim the session and workspace it reserved
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # ONE STEP PAST HFR-268, and the reason a refusal is not finished when it stops the
+ # effect. _rebind_create_once_session COMMITS the replacement session before
+ # _persist_task_session_id is called at all -- a different store, a different
+ # transaction, and for a standalone placement a mkdir of a Show Page workspace too.
+ # HFR-268 correctly stopped the dispatch and left that row behind: nothing points at
+ # it (the definition still names the session the teardown cleared and the notice says
+ # "not rebound"), so it is a live, unreferenced background session that nothing will
+ # ever run, list or delete, plus its workspace, and one more of each for every fire
+ # that loses the same race.
+ # ATOMIC vs EXPLICIT RECLAIM, and why reclaim: the reservation and the write that
+ # adopts it go through two different services with two different engines, and the
+ # reservation's mkdir is a side effect no SQL transaction can roll back. One atomic
+ # operation would mean threading a single connection through both stores and STILL
+ # leaving the directory. Naming the one row this call created and giving it back is
+ # smaller, is exact about which row it may touch, and does not depend on the two
+ # stores continuing to live in one database.
+ # NARROW BY CONSTRUCTION: release_reserved_agent_session names the row by the id the
+ # reservation returned, requires native_session_id still empty and no run_definitions
+ # row pointing at it, and re-asserts both IN the delete (_delete_agent_session_rows
+ # re-runs the id query with the write lock held). The workspace is removed only when
+ # it IS show/<session_id> -- the directory that reservation created and nothing else
+ # can own -- so a scoped reservation's inherited Scope workdir is never touched.
+ # Both placements are driven through the real _execute_task with a concurrent winner
+ # reserved through the SAME branch, so "delete the unreferenced background sessions"
+ # would fail the test:
+ test: tests/test_scheduled_tasks.py::test_a_refused_rebind_reclaims_the_session_and_workspace_it_reserved
+ - id: HFR-271
+ name: a write that raises must roll the in-process mirror back with the transaction
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # THE RULE THE REST OF THIS ROUND CAME FROM: a rollback is not proven by re-reading
+ # the durable row. It is proven when the durable row AND the live in-process state
+ # agree. HFR-269's inverse test read the rolled-back watch through a freshly built
+ # ManagedWatchStore -- ordinarily good hygiene, and here exactly what hid the defect,
+ # because the half that stayed wrong was the service still running.
+ # ManagedWatchStore is a write-through cache: mark_cycle_result mutates the cached
+ # ManagedWatch (enabled=False, retired_at, last_finished_at, last_exit_code) and THEN
+ # calls _write_watch. _write_watch reloaded only when the compare-and-set RETURNED
+ # False, never when the write RAISED, and _watch_store_call swallows the exception
+ # into the store fuse, so nothing downstream corrected it. Reproduced on the real
+ # _run_watch: durable row enabled=True/retired=None, service.store enabled=False/
+ # retired_at=<ts>/exit_code=0.
+ # WHO READS THE STALE MIRROR: reconcile_watches picks which watches keep running out
+ # of that dict, vibe watch list renders it, and _read_state derives the NEXT
+ # compare-and-set's expectation from it, so one stale entry also mis-guards the next
+ # write. FIX: every way the write can fail to land reloads, at the one choke point,
+ # and if the reload itself fails the entry is dropped rather than kept (absent reads
+ # as "gone" and stops the watch; stale keeps it running on state that never existed).
+ # No broad retry. Parametrized over every guarded writer that goes through the choke
+ # point, with the fault injected at the run_definitions statement itself rather than
+ # at one caller's second write:
+ # tests/test_watches.py::test_a_definition_write_that_raises_leaves_no_live_mirror_ahead_of_the_database
+ # The HFR-269 inverse test now asserts both halves as well, which is what makes it
+ # able to see this class at all:
+ test: tests/test_watches.py::test_a_failed_outbox_write_does_not_retire_the_watch_with_its_hook_lost
+ - id: HFR-272
+ name: the task store's mirror must roll back with a raised write too
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # HFR-271 applied to the sibling store rather than waiting for a second report.
+ # ScheduledTaskStore is the same write-through cache with the same choke point:
+ # set_enabled / update_task / record_binding_recovery / mark_task_result each mutate
+ # the cached ScheduledTask and hand the whole row to _write_task, and _write_task
+ # reloaded only on the False return. reconcile_jobs schedules from that dict and
+ # _read_state derives the next guard's expectation from it, so a raised write left
+ # the scheduler acting on an edit the database rolled back. Same fix, same shape,
+ # same drop-on-failed-reload fallback:
+ test: tests/test_scheduled_tasks.py::test_a_definition_write_that_raises_leaves_no_live_task_mirror_ahead_of_the_database
+ - id: HFR-273
+ name: a teardown that rolls back must not report definitions as reclaimed
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The same rule applied to the one piece of teardown state that is NOT in the
+ # database. reclaim_bound_definitions appends to the teardown ledger as it pauses
+ # each definition, and the ledger is what /new counts for "N tasks paused". It was
+ # append-only: a transaction that reclaimed and then ABORTED -- a locked database on
+ # a later statement or on the COMMIT, the class of fault this whole PR is about --
+ # rolled the pause back and left the entry. handle_new wraps clear_session_base in
+ # except Exception: logger.debug(...) and reports the ledger anyway, so the user is
+ # told a task was paused while it is still enabled, still bound to the session they
+ # cleared, and still firing into it.
+ # FIX: reclaim_ledger_transaction wraps each transaction that can reclaim, OUTSIDE
+ # begin() so the truncation runs after the rollback, and discards only entries this
+ # transaction added. Deliberately NOT the same case as a reclaim whose own DELETE was
+ # refused -- that reclaim really did commit, and _delete_agent_session_rows documents
+ # why keeping it is the recoverable half:
+ test: tests/test_session_archive.py::test_a_teardown_that_rolls_back_reports_nothing_as_reclaimed
+ - id: HFR-274
+ name: the live session map must keep what the teardown SQL deliberately kept
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The consuming half of HFR-240/241, found the same way. clear_session_base
+ # hand-pruned state.session_mappings by the prefix rule the SQL used to use --
+ # key == base or key.startswith(base + ":") -- which stopped being the same rule when
+ # delete_agent_sessions grew its include_superseded=False guard. A superseded row is
+ # anchored <base>:superseded:<id>, so the database KEEPS it (its native id is
+ # write-once and its transcript is not recoverable) while the prefix scan deleted the
+ # only pointer this process had to it, and save_state made that permanent: the guard
+ # preserved a row nothing can reach.
+ # FIX: re-read the map from the service, exactly as clear_agent_sessions and
+ # remove_agent_session already do, so the local half cannot disagree with a delete
+ # whose rules it no longer reimplements. Asserted on the live SessionsStore inside
+ # the same /new run that reads the durable rows:
+ test: tests/test_command_handler_user_names.py::NewCommandStorageIntegrationTests::test_new_keeps_a_superseded_session_and_its_definitions_but_clears_the_live_one
+ - id: HFR-275
+ name: the create and delete entry points must roll their mirror back too
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The last two writers HFR-271/272 did not reach, found by sweeping BOTH definition
+ # stores for the mirror shape rather than for the guarded-write shape: an in-memory
+ # entry mutated BEFORE the persistence call, with no restore when it fails.
+ # upsert_watch / upsert_task are the create-and-adopt entry points and take no
+ # ``expect`` (their payload is not a re-read), so they never went through the guarded
+ # choke point. They are also the only writers that can add an id the database has
+ # NEVER seen, which is the worse direction: the caller is told the definition could
+ # not be created, while reconcile_watches / reconcile_jobs pick it out of exactly
+ # that dict and start running it -- spawning the waiter command, or firing the prompt
+ # into a channel -- with no durable row to stop it and nothing that will reload it
+ # away.
+ # remove_watch / remove_task are the same shape in the conservative direction: the
+ # entry is dropped before the soft delete, so a failure stops a definition the
+ # database still has. Silently, and NOT self-healing -- the row is unchanged, so
+ # maybe_reload sees no external write and it stays stopped until a restart.
+ # Both now reload through the same _reload_after_lost_write helper, which is correct
+ # for a create (the id is simply absent from the database) and for an adopt or a
+ # delete (the previous row comes back).
+ test: tests/test_watches.py::test_a_failed_create_leaves_no_phantom_watch_in_the_live_store
+ - id: HFR-276
+ name: a reclaim that fails must record the orphan, not report a completed reclaim
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # One layer INSIDE the HFR-270 fix, and the same class as HFR-263..266: the caller
+ # ignored the guard's answer. _release_reserved_session is deliberately never fatal
+ # (it runs on a path already reporting a failure to the user), so it catches every
+ # exception and returns False; _recover_pinned_session_binding dropped that boolean
+ # and emitted SessionBindingChange(action="reclaimed") regardless. A locked database
+ # or an I/O fault during the release therefore left exactly the orphan HFR-270
+ # promises cannot remain -- a live, unreferenced background session and its workspace
+ # -- told the user it had been given back, and lost the only handle on it: the
+ # reserved id is random and is never written to the definition, so the next fire that
+ # loses the same race reserved and leaked another one, untracked.
+ # FIX, both clauses. The boolean is consumed and the losing branch emits a distinct
+ # action="orphaned" whose detail names the session that is still live; and the id is
+ # recorded durably on the definition that reserved it
+ # (metadata.orphaned_reservations in run_definitions.metadata_json, the same row the
+ # binding-recovery record already uses), so a reservation may accumulate only in a
+ # TRACKED, retryable form. That record is itself written through the guarded full-row
+ # writer, so its own False is consumed too: the notice then says the id could not be
+ # recorded either. The next fire of the same definition retries the release from the
+ # record (_retry_orphaned_reservations) and drops the entries it resolves, keeping the
+ # ones whose release failed again. release_reserved_agent_session keeps its exact-id /
+ # empty-native / unreferenced predicates unchanged, so no retry can take a concurrent
+ # winner. Asserted on the live store mirror AND the durable row:
+ # tests/test_scheduled_tasks.py::test_a_release_that_fails_records_the_orphan_instead_of_reporting_a_reclaim
+ # THE SHARED-FAULT HALF, which the first regression could not see because it raised
+ # from a monkeypatched release while leaving SQLite healthy: the record is written
+ # through the SAME database whose fault just refused the release, so the stated
+ # production cases (locked database, I/O fault) refuse both writes for one reason --
+ # and _write_task RAISES on a faulted write (HFR-272), which the first fix's
+ # boolean-only handling let unwind past the notice branch entirely. FIX, two parts.
+ # The raise and the refusal are consumed as one "not recorded" branch in
+ # _track_orphaned_reservation and _retry_orphaned_reservations; and the durable
+ # handle no longer depends on the record at all: the recovery rebind stamps the
+ # reserving definition's id into the reservation row's own metadata
+ # (reserved_by_harness_definition), inside the reservation's INSERT transaction, so
+ # if the row committed the handle committed with it. The next fire sweeps rows
+ # stamped with this definition's id that are still empty-native and unreferenced
+ # (the HFR-279 classification facts, one consistent read) and releases them, so
+ # recovery survives a restart with nothing in memory. The stamp is written ONLY by
+ # the create_once recovery rebind, whose fires serialize on the pinned session's
+ # lock -- a create_per_run reservation is legitimately unbound and unreferenced
+ # between reserve and dispatch, and its fires can overlap, so it must never be
+ # inside the sweep's definition of an orphan. The regression takes a REAL
+ # BEGIN IMMEDIATE on the database file across the release and the record, asserts
+ # the record did NOT land, then recovers through freshly constructed stores (the
+ # restart shape) and finally proves a stamped-AND-adopted rebound session is never
+ # swept:
+ # tests/test_scheduled_tasks.py::test_a_locked_database_that_refuses_release_and_record_still_recovers_the_orphan
+ test: tests/test_scheduled_tasks.py::test_a_release_that_fails_records_the_orphan_instead_of_reporting_a_reclaim
+ - id: HFR-277
+ name: a mirror dropped by a failed write reloads without an unrelated commit
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The consuming end of HFR-271/272's OWN recovery path, and the same class as
+ # HFR-263..266 one layer further in: the fix trusted a mechanism that cannot see what
+ # it needs to see. _reload_after_lost_write drops the entry when the guarded write
+ # fails AND the immediate recovery load fails too -- correct, an absent definition is
+ # safer to act on than a mutated one the database never accepted -- and documented
+ # that maybe_reload restores it "once the database is reachable again". It did not.
+ # maybe_reload consulted only SqliteInvalidationProbe, i.e. PRAGMA data_version,
+ # which moves when another connection COMMITS; the failed write ROLLED BACK, so
+ # data_version was unchanged and every later tick answered "nothing changed". The
+ # definition stayed durably enabled in SQLite and invisible in-process until a
+ # restart or an unrelated commit happened to bump the counter -- and reconcile_jobs /
+ # reconcile_watches choose what to schedule and what keeps running out of exactly
+ # those dicts, so a cron task stopped firing and a watch stopped being reconciled
+ # while their rows still said enabled.
+ # FIX, both definition stores: an in-process _reload_required flag set where the
+ # entry is dropped, which makes the NEXT maybe_reload load unconditionally, and is
+ # cleared only by the load that repairs the mirror (so a reload that fails again is
+ # retried on the tick after). In-process rather than a database column on purpose: it
+ # describes THIS mirror, not the data; a restart reloads from SQLite anyway; and
+ # persisting it would mean writing to the database that was just proven unwritable.
+ # Both tests end the fault the way a transient fault ends -- by going away, writing
+ # nothing -- and a witness probe on its own connection asserts data_version is
+ # UNCHANGED at that instant, so recovering because some other writer committed cannot
+ # be mistaken for recovering because the store remembered. Asserted on the live
+ # mirror (get / list) AND the durable row:
+ # tests/test_watches.py::test_a_dropped_watch_mirror_recovers_with_no_unrelated_commit_to_wake_it
+ test: tests/test_scheduled_tasks.py::test_a_dropped_task_mirror_recovers_with_no_unrelated_commit_to_wake_it
+ - id: HFR-278
+ name: releasing a reservation cannot damage a definition that adopted it
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # One layer inside our own HFR-270 fix, and the same window HFR-257..260 closed
+ # statement by statement -- reached this time through the reservation cleanup HFR-270
+ # added. release_reserved_agent_session -> _delete_agent_session_rows runs its
+ # id_query first and reclaim_bound_definitions second, and the id read reserves
+ # nothing (pysqlite opens no transaction for a bare SELECT). An adoption committing
+ # between the two left the reclaim reading the WINNER's definition: it paused it,
+ # stamped its last_error with the release's reason, and overwrote its
+ # session_settings_snapshot -- which a later create_once rebind reads. The final
+ # DELETE then re-evaluated NOT EXISTS and correctly PRESERVED the session, which is
+ # why nothing surfaced: the release returned False, logged "not releasing", and the
+ # winner was disabled anyway. The reclaim is deliberately never rolled back
+ # (_delete_agent_session_rows documents why under WAL), so nothing corrected it.
+ # FIX: reserve_write_lock(conn) -- the HFR-262 precedent -- at the top of the
+ # release's transaction, BEFORE the read the decision rests on. Nothing has been read
+ # on that connection yet, so it is the cheap BEGIN IMMEDIATE spelling, which takes
+ # the write lock and the read snapshot in one statement. The adoption can then only
+ # land before the release looks (the exact-id / native-empty / unreferenced
+ # predicates see it and the release backs off, all three kept unchanged) or after the
+ # release has committed. Re-asserting the predicates in the DELETE protects the ROW;
+ # the damage was to a definition, which is why order and not detection is the fix.
+ # Asserted on the FULL row the winner owns (the HFR-251 lesson): its Session row, its
+ # Show workspace on disk, its route/anchor, its pins and explicit override markers,
+ # its definition's enabled state, pause reason, settings snapshot, every timestamp,
+ # and the teardown ledger that must credit nothing. The mechanism itself is pinned
+ # separately, the two ways the HFR-262 tests do it (reservation ahead of the read in
+ # the statement sequence, and a zero-patience competing writer REFUSED at it):
+ # tests/test_sqlite_sessions_store.py::test_releasing_a_reservation_holds_the_write_lock_at_its_decision_read
+ test: tests/test_sqlite_sessions_store.py::test_releasing_a_reservation_cannot_damage_a_definition_that_adopted_it
+ - id: HFR-279
+ name: an adopted reservation is dropped from the retry record without being touched
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # One layer inside HFR-276's own fix, found by the exact-head Codex review of that
+ # fix. release_reserved_agent_session answers False for three different facts --
+ # the row is gone, the row was adopted, the release faulted -- and the retry's
+ # absence-only probe (_reserved_session_is_gone) resolved only the first. A tracked
+ # reservation that was since adopted (a native session dispatched into it, or a
+ # run_definitions row pointing at it) is not absent and can never be released, so
+ # its entry stayed on metadata.orphaned_reservations forever and every later fire
+ # of the original definition re-took SQLite's write lock (the release's
+ # BEGIN IMMEDIATE) to retry a cleanup that cannot succeed -- the loser's
+ # bookkeeping taxing the winner's row on every fire, indefinitely.
+ # FIX: an explicit classification (classify_reserved_agent_session) that runs
+ # BEFORE any release attempt and reads both adoption facts -- native binding and
+ # definition reference -- in ONE SQL statement, so the verdict is a state the row
+ # actually was in. Four verdicts, four actions: absent -> resolved and dropped;
+ # adopted -> resolved and dropped WITHOUT being read under the write lock, let
+ # alone mutated; still empty-native and unreferenced -> a genuine orphan, released
+ # through the unchanged guarded release (whose predicates re-assert both facts
+ # under the write lock, so a classification that raced an adoption destroys
+ # nothing -- the entry stays and the next fire classifies it as adopted); a
+ # classification that cannot read -> the entry is KEPT, never guessed away. The
+ # regression adopts one tracked reservation each way, asserts the winners' FULL
+ # rows (route/anchor, workdir, pins and metadata markers, every timestamp) and the
+ # adopting definition's full row are byte-identical across the retry, that no
+ # release was attempted against either winner or the absent id, and that the
+ # record dropped the resolved entries durably and in the live mirror. The fault
+ # verdict is pinned separately:
+ # tests/test_scheduled_tasks.py::test_a_retry_classification_that_cannot_read_keeps_the_entry
+ test: tests/test_scheduled_tasks.py::test_an_adopted_reservation_is_dropped_from_the_retry_record_without_being_touched
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.py
index f87df5869..5363b3364 100644
--- a/tests/test_agent_run_target.py
+++ b/tests/test_agent_run_target.py
@@ -5,7 +5,8 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
-from sqlalchemy import select
+from sqlalchemy import event, select
+from sqlalchemy.exc import OperationalError
from core.services import sessions as sessions_service
from core.services.agent_run_target import resolve_agent_run_target
@@ -1088,3 +1089,242 @@ def test_native_bind_does_not_change_session_workdir(tmp_path):
with controller.sqlite_engine.connect() as conn:
session = sessions_service.get_session(conn, target.agent_session_id)
assert session["workdir"] == str(original_workdir)
+
+
+#: ``_row_for_scope_anchor``'s read. It runs TWICE on the create path: once unlocked on the
+#: hot path, and again after ``reserve_write_lock`` has taken the write lock. Landing a
+#: competing commit after the FIRST one is the whole window that remains (HFR-262), and the
+#: reserved re-read is what has to see it.
+_ANCHOR_DECISION_SELECT = (
+ "SELECT agent_sessions.id, agent_sessions.agent_backend, agent_sessions.agent_variant, "
+ "agent_sessions.native_session_id FROM agent_sessions WHERE agent_sessions.scope_id = ? "
+ "AND agent_sessions.session_anchor = ? AND agent_sessions.status != ? "
+ "ORDER BY agent_sessions.last_active_at DESC, agent_sessions.id DESC LIMIT ? OFFSET ?"
+)
+
+
+def test_resolve_agent_run_target_tolerates_concurrent_row_insert(tmp_path):
+ """HFR-053 — IM inbound find-then-create is a race, not a guarantee.
+
+ ``resolve_agent_run_target`` selected and then inserted with no ``IntegrityError``
+ catch; SQLite takes no write lock at a SELECT, so a competing writer can win the
+ ``(scope_id, session_anchor)`` slot in between. The loser must re-read the winner's row
+ instead of surfacing a 500.
+
+ WHERE THE COMPETITOR COMMITS, and why it moved. This used to wrap
+ ``create_agent_session_row`` and commit the winner from inside the create call. That
+ interleaving no longer exists: HFR-262 made the create path take the write lock BEFORE
+ the reads its INSERT decides from, so a competing connection reaching that point is
+ refused the lock rather than allowed to commit — and a test that stages an impossible
+ interleaving is proving nothing about production. The window that DOES remain is
+ earlier and deliberate: ``get_or_create_agent_session_row`` keeps its first anchor read
+ unlocked (it is the hot path every message takes), so a winner can still commit between
+ that read and the reservation. The competitor is landed exactly there, from a real
+ second connection, which is the production race this scenario is about.
+
+ So the loser still has to answer with the winner's row — now by re-deciding under the
+ write lock rather than by catching the UNIQUE violation. A create that trusted its
+ unlocked read would insert a second row for a thread that already has one, and this
+ test fails on it.
+ """
+ controller = _controller(tmp_path)
+ db_path = Path(controller.sqlite_engine.url.database)
+ with controller.sqlite_engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C777",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, scope_id, workdir=str(tmp_path / "wd"))
+
+ competitor: dict[str, str] = {}
+
+ @event.listens_for(controller.sqlite_engine, "after_cursor_execute")
+ def _win_the_anchor(conn, cursor, statement, parameters, context, executemany):
+ if competitor or " ".join(statement.split()) != _ANCHOR_DECISION_SELECT:
+ return
+ other = create_sqlite_engine(db_path)
+ try:
+ with other.begin() as other_conn:
+ competitor["id"] = create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_anchor="slack_171717.777",
+ agent_backend="codex",
+ workdir=str(tmp_path / "wd"),
+ )
+ finally:
+ other.dispose()
+
+ ctx = MessageContext(user_id="U1", channel_id="C777", platform="slack", thread_id="171717.777")
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="slack_171717.777")
+
+ assert competitor, (
+ "the competing insert never landed between the unlocked read and the reservation, "
+ "so this test proved nothing — the keyed read is no longer the SQL the code emits"
+ )
+ assert target.agent_session_id == competitor["id"]
+ with controller.sqlite_engine.connect() as conn:
+ ids = list(conn.execute(select(agent_sessions.c.id)).scalars().all())
+ assert ids == [competitor["id"]], (
+ f"agent_sessions holds {ids!r}; the loser must join the winner's row, never insert "
+ "a second one for the same thread"
+ )
+
+
+def test_resolve_agent_run_target_tolerates_no_usable_session(tmp_path, monkeypatch):
+ """HFR-253, third caller — "no usable session" must not be a 500 on inbound.
+
+ ``get_or_create_agent_session_row`` answers ``(None, created)`` when it resolved
+ onto an existing row for this anchor, tried to claim it for this turn's backend,
+ and lost that race to a writer that ARCHIVED the row: an archive is terminal, so
+ there is no id to hand back. The interleaving that produces it is proven against
+ the storage boundary by
+ ``tests/test_sqlite_sessions_store.py::test_ensure_agent_session_id_cannot_relabel_a_row_archived_inside_its_window``;
+ what is pinned HERE is how this third caller consumes that answer.
+
+ It used to consume it by crashing. The row read after the get-or-create is a
+ ``.one()`` keyed on the returned id, so ``id IS NULL`` matched nothing and
+ ``NoResultFound`` propagated out of inbound message handling — a user-visible
+ failure on an ordinary channel turn, caused by another session being archived.
+ The turn must instead run on the UNPERSISTED target, which is the answer this
+ function already gives whenever there is no scope to persist against: a resolved
+ workdir and Agent route, and no ``agent_session_id``.
+ """
+ import core.services.agent_run_target as art
+
+ controller = _controller(tmp_path)
+ with controller.sqlite_engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C778",
+ now="2026-07-28T05:00:00Z",
+ )
+ _seed_scope_settings(conn, scope_id, workdir=str(tmp_path / "wd"))
+
+ monkeypatch.setattr(art, "get_or_create_agent_session_row", lambda conn, **kwargs: (None, False))
+
+ ctx = MessageContext(user_id="U1", channel_id="C778", platform="slack", thread_id="171717.778")
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="slack_171717.778")
+
+ assert target is not None
+ assert target.agent_session_id is None, (
+ f"the turn was pointed at {target.agent_session_id!r} after the keyed "
+ "get-or-create reported no usable session"
+ )
+ # The rest of the turn still has everything it needs.
+ assert target.workdir == str(tmp_path / "wd")
+ assert target.session_anchor == "slack_171717.778"
+ assert target.agent_backend == "codex"
+ with controller.sqlite_engine.connect() as conn:
+ assert (
+ conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id)
+ ).first()
+ is None
+ ), "the degrade minted a row for the anchor the archive just vacated"
+
+
+#: The last read the first-turn INSERT in ``get_or_create_agent_session_row`` decides
+#: from: ``new_session_id``'s scan of every existing session id.
+_SESSION_ID_SCAN_SELECT = "SELECT agent_sessions.id FROM agent_sessions"
+
+#: The two spellings ``reserve_write_lock`` uses to become the writer before that read.
+_WRITE_LOCK_RESERVATIONS = ("BEGIN IMMEDIATE", "UPDATE agent_sessions SET id = id WHERE 1 = 0")
+
+
+def test_resolve_agent_run_target_reserves_the_write_lock_for_its_first_turn_insert(tmp_path):
+ """HFR-262 — the third production path into the contested first-turn INSERT.
+
+ ``resolve_agent_run_target`` reaches the same shared get-or-create as
+ ``SQLiteSessionsService.ensure_agent_session_id`` / ``bind_agent_session`` (pinned in
+ ``tests/test_sqlite_sessions_store.py``), and it gets there after nothing but SELECTs
+ -- so before the fix its INSERT decided from a WAL read snapshot no write lock stood
+ behind, and a turn arriving on the same brand-new thread could make that snapshot
+ stale. SQLite answers that with ``SQLITE_BUSY_SNAPSHOT``, which ``busy_timeout`` never
+ retries and which cannot even be IDENTIFIED on Python 3.10 (``sqlite_errorcode`` is
+ 3.11+), so the fix removes the window rather than detecting the failure.
+
+ One path holding the write lock is not the fix; the INSERT is shared, so this asserts
+ the guarantee here too, and asserts it as a fact rather than an argument: a competing
+ writer given ``busy_timeout = 0`` must be REFUSED at the last read before the INSERT.
+ That observation does not depend on the interpreter version.
+ """
+ workdir = tmp_path / "channel"
+ controller = _controller(tmp_path)
+ with controller.sqlite_engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="channel",
+ native_id="C123",
+ now="2026-06-04T05:00:00Z",
+ )
+ _seed_scope_settings(conn, scope_id, workdir=str(workdir))
+
+ statements: list[str] = []
+ race = {"fired": 0, "refused": [], "committed": 0}
+
+ @event.listens_for(controller.sqlite_engine, "after_cursor_execute")
+ def _observe(conn, cursor, statement, parameters, context, executemany):
+ normalised = " ".join(statement.split())
+ statements.append(normalised)
+ if race["fired"] or normalised != _SESSION_ID_SCAN_SELECT:
+ return
+ race["fired"] += 1
+ other = create_sqlite_engine()
+ try:
+ with other.connect() as other_conn:
+ # Zero patience instead of the engine's 5s pragma, so "the writer slot is
+ # taken" is an immediate refusal rather than a five-second wait.
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 0")
+ try:
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id="seswinner001",
+ session_anchor="slack_171717.123",
+ agent_backend="claude",
+ agent_variant="claude",
+ native_session_id="",
+ workdir=str(workdir),
+ now="2026-06-04T05:00:01Z",
+ )
+ other_conn.commit()
+ except OperationalError as exc:
+ race["refused"].append(str(exc))
+ else:
+ race["committed"] += 1
+ finally:
+ other.dispose()
+
+ ctx = MessageContext(user_id="U1", channel_id="C123", platform="slack", thread_id="171717.123")
+ target = resolve_agent_run_target(ctx, controller=controller, base_session_id="slack_171717.123")
+
+ assert target.agent_session_id, "the first turn produced no session at all"
+ assert _SESSION_ID_SCAN_SELECT in statements, (
+ "the id scan the INSERT decides from is no longer emitted, so neither check below "
+ "means anything"
+ )
+ scan_at = statements.index(_SESSION_ID_SCAN_SELECT)
+ reserved_at = [index for index, sql in enumerate(statements) if sql in _WRITE_LOCK_RESERVATIONS]
+ assert reserved_at and min(reserved_at) < scan_at, (
+ f"no write-lock reservation precedes the id scan: {statements!r}"
+ )
+ assert race["fired"] == 1, "the competing insert never ran inside the window"
+ assert race["committed"] == 0, (
+ f"a competing connection took the write lock while resolve_agent_run_target was "
+ f"reading the state its INSERT decides from: {race!r}"
+ )
+ assert len(race["refused"]) == 1, f"the competing writer was neither refused nor committed: {race!r}"
+
+ with controller.sqlite_engine.connect() as conn:
+ ids = list(conn.execute(select(agent_sessions.c.id)).scalars().all())
+ assert ids == [target.agent_session_id], (
+ f"agent_sessions holds {ids!r}; exactly ONE row may exist for a thread whose first "
+ "turn was contested"
+ )
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index fc1ad74f1..96f5930c1 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -1350,6 +1350,102 @@ def test_task_update_modifies_existing_task_without_changing_id(tmp_path: Path,
assert payload["definition"]["prompt"] == "updated"
+def test_task_update_rejects_agent_together_with_clear_agent(tmp_path: Path) -> None:
+ """HFR-255 — ``--agent X --clear-agent`` re-pinned today's default Agent.
+
+ THE DEFECT. The two flags mean opposite things, and unlike ``--name`` /
+ ``--clear-name`` the pair raised nothing. It also did not simply pick one:
+ ``--clear-agent`` won for ``agent_name`` (→ None), while the mere PRESENCE of
+ ``--agent`` set ``explicit_agent_requested``, which POPS the follow-the-session
+ marker. The definition therefore looked like "no Agent pinned, and not following
+ its Session", so the resolve below took the ``agent_name is None and
+ session_policy != 'existing'`` branch, resolved today's scope / default Agent, and
+ wrote it back as a HARD PIN — the exact regression the marker exists to prevent
+ (HFR-245), reachable in one command and with neither flag's meaning honoured.
+
+ THE FIX is the convention ``--name`` / ``--clear-name`` already sets: reject the
+ contradictory pair, because the user's intent is genuinely ambiguous (did they
+ mean to pin, or to unpin?). Asserted BOTH ways below, so the two pairs cannot
+ drift apart.
+
+ The stored definition must also be untouched: a rejected command may not have
+ written a pin on its way to failing.
+ """
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ try:
+ # The Agent the bound Session runs as, and a DIFFERENT current default. The
+ # gap between them is what makes the re-pin observable at all.
+ agent_store.create(name="rebound", backend="codex")
+ successor = agent_store.create(name="successor", backend="claude")
+ agent_store.set_default_agent_name(successor.name)
+ finally:
+ agent_store.close()
+
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ name="digest",
+ session_key="slack::channel::C123",
+ session_policy="create_per_run",
+ agent_name=None,
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={cli.BINDING_FOLLOWS_SESSION_METADATA_KEY: True},
+ )
+
+ def _update(*argv: str) -> tuple[int, str]:
+ """Run the REAL command. Returns ``(exit code, raw stderr)``.
+
+ Stderr is returned unparsed on purpose: the pre-fix command SUCCEEDS and
+ writes nothing there, so parsing it eagerly would turn the interesting red
+ into a ``JSONDecodeError`` and hide which field was corrupted.
+ """
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, *argv])
+ cli_agent_store = cli.VibeAgentStore(db_path)
+ stderr = io.StringIO()
+ try:
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli._agent_store", return_value=cli_agent_store),
+ redirect_stderr(stderr),
+ ):
+ return cli.cmd_task_update(args), stderr.getvalue()
+ finally:
+ cli_agent_store.close()
+
+ result, stderr_text = _update("--agent", "rebound", "--clear-agent")
+
+ # The persisted definition first: this is the damage, and asserting it before the
+ # exit code keeps the red pointed at the regression rather than at the reporting.
+ stored = store.get_task(task.id)
+ assert stored is not None
+ assert stored.agent_name is None, (
+ f"the contradictory pair pinned agent_name={stored.agent_name!r} — today's "
+ f"default Agent ({successor.name!r}), which is neither the Agent that was "
+ "passed nor the cleared state that was asked for; every future fire now runs "
+ "as the wrong Agent"
+ )
+ assert stored.metadata.get(cli.BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "the contradictory pair dropped the follow-the-session state, so the bound "
+ "Session no longer governs the definition's Agent"
+ )
+ assert result == 1, (
+ "vibe task update accepted --agent together with --clear-agent; it honours "
+ "neither flag and re-pins the definition to today's default Agent instead"
+ )
+ assert json.loads(stderr_text)["code"] == "conflicting_agent_update", stderr_text
+
+ # The convention this mirrors, asserted so the two pairs cannot drift apart.
+ name_result, name_stderr = _update("--name", "renamed", "--clear-name")
+ assert name_result == 1
+ assert json.loads(name_stderr)["code"] == "conflicting_name_update", name_stderr
+
+
def test_task_update_rejects_scope_without_session_creation(tmp_path: Path) -> None:
store_path = tmp_path / "scheduled_tasks.json"
store = cli.ScheduledTaskStore(store_path)
@@ -3061,3 +3157,149 @@ def test_task_hidden_aliases_still_parse() -> None:
assert list_args.task_command == "ls"
assert remove_args.task_command == "rm"
+
+
+def _reclaim_bound_definitions_now(session_id: str, *, mode: str, reason: str) -> dict[str, int]:
+ """Run the shared teardown reclaim against the isolated state database.
+
+ The production callers are ``/new`` (``delete_agent_sessions``) and the archive
+ dialog; both reach this same helper, and it is the write a stale full-row
+ definition payload undoes.
+ """
+ from config import paths
+ from storage.db import create_sqlite_engine
+ from storage.session_reclaim import reclaim_bound_definitions
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return reclaim_bound_definitions(conn, session_id, mode=mode, reason=reason)
+ finally:
+ engine.dispose()
+
+
+def _create_bare_agent_session(*, workdir: Path, anchor: str = "slack_C123") -> str:
+ """A Session row with settings worth snapshotting and no Agent to resolve.
+
+ ``agent_name`` is deliberately ``None``: ``vibe task update`` resolves the bound
+ Session's Agent through ``require_enabled``, and this test is about the write,
+ not about Agent resolution.
+ """
+ from config import paths
+ from storage.agent_session_rows import create_agent_session_row
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return create_agent_session_row(
+ conn,
+ scope_id=None,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ model="gpt-5.5-codex",
+ native_session_id="codex-native",
+ workdir=str(workdir),
+ require_workdir=False,
+ )
+ finally:
+ engine.dispose()
+
+
+def test_task_update_refuses_to_undo_a_reclaim_committed_after_its_read(tmp_path: Path) -> None:
+ """HFR-261 — ``vibe task update`` wrote the WHOLE row from a stale read.
+
+ THE PRODUCTION STORY. A task is pinned to Session S. The user renames it. While
+ the command is resolving Agents, Sessions and delivery targets, ``/new`` arrives
+ in that thread (or the archive dialog is confirmed) and
+ ``reclaim_bound_definitions`` pauses this very definition, stamps the pause
+ reason, and records the ``session_settings_snapshot`` a later ``create_once``
+ rebind needs.
+
+ THE DEFECT. ``upsert_scheduled_task`` writes EVERY column of
+ ``run_definitions``, keyed on ``id`` alone, from a payload built out of the
+ earlier read. So the rename restored ``enabled=1``, wiped ``last_error`` and
+ replaced the metadata with the pre-teardown copy: the reclaim's compare-and-set
+ had succeeded, its counters and the ``/new`` ledger had already told the user "1
+ task paused", and the definition was quietly running again against a session that
+ no longer exists.
+
+ A LOST WRITE MUST ALSO BE A VISIBLE FAILURE. The command previously printed the
+ renamed task and exited 0 — a claim about a row it did not write. It now exits 1
+ with ``definition_write_conflict``.
+ """
+ from storage.session_reclaim import RECLAIM_PAUSE, SESSION_SETTINGS_SNAPSHOT_KEY
+
+ store = cli.ScheduledTaskStore()
+ session_id = _create_bare_agent_session(workdir=tmp_path)
+ task = store.add_task(
+ name="Nightly summary",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ prompt="summarise the day",
+ schedule_type="cron",
+ cron="0 3 * * *",
+ timezone_name="UTC",
+ metadata={"origin": "cli"},
+ )
+
+ # The teardown, committed after the CLI's read of this definition and before its
+ # write. ``store`` is deliberately NOT reloaded: that stale mirror is exactly what
+ # production holds.
+ summary = _reclaim_bound_definitions_now(
+ session_id, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared"
+ )
+ assert summary == {"paused": 1, "deleted": 0, "snapshotted": 1}, (
+ f"the reclaim itself did not land ({summary!r}), so the rest of this test is "
+ "meaningless"
+ )
+
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--name", "Renamed by the user"])
+ stderr = io.StringIO()
+ with (
+ redirect_stderr(stderr),
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ result = cli.cmd_task_update(args)
+
+ assert result == 1, (
+ "the command reported success for a write the database refused; the user is "
+ "shown a renamed task while the stored definition is whatever the teardown left"
+ )
+ payload = json.loads(stderr.getvalue())
+ assert payload["code"] == "definition_write_conflict"
+ assert payload["details"]["task_id"] == task.id
+
+ stored = cli.ScheduledTaskStore().get_task(task.id)
+ assert stored is not None
+ assert stored.enabled is False, (
+ "the stale full-row write re-enabled a definition the teardown paused; it now "
+ "fires forever against a session that no longer exists"
+ )
+ assert stored.last_error == "the bound agent session was cleared", (
+ f"the pause reason was overwritten with {stored.last_error!r}, so the user "
+ "cannot see why the task stopped"
+ )
+ assert SESSION_SETTINGS_SNAPSHOT_KEY in stored.metadata, (
+ "the stale write replaced the reclaim's settings snapshot with the "
+ "pre-teardown metadata; that snapshot is what a later create_once rebind "
+ "reads, so the task would come back on the wrong workdir/agent/model"
+ )
+ assert stored.name == "Nightly summary", (
+ "the refused write partially landed — a lost compare-and-set must change "
+ "NOTHING, not just the guarded columns"
+ )
+ # HFR-271's rule: everything above reads a store this line built. The store the
+ # COMMAND used is still in scope and still holds the row it mutated before the
+ # refusal, so assert the two halves agree rather than only the durable one.
+ live = store.get_task(task.id)
+ assert live is not None and live.to_dict() == stored.to_dict(), (
+ "the write was refused and the live store kept the mutation: it still serves "
+ f"name={None if live is None else live.name!r} "
+ f"enabled={None if live is None else live.enabled!r} while the row says "
+ f"name={stored.name!r} enabled={stored.enabled!r}"
+ )
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 9379a13f5..2261aaa6d 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -1457,3 +1457,229 @@ def test_watch_add_rejects_deprecated_prompt_argument() -> None:
assert result == 1
assert payload["code"] == "deprecated_prompt_argument"
assert "--message" in payload["hint"]
+
+
+def test_watch_update_rejects_agent_together_with_clear_agent(tmp_path: Path) -> None:
+ """HFR-256 — ``--agent X --clear-agent`` re-pinned today's default Agent.
+
+ The sibling half of HFR-255, on ``vibe watch update``. The two flags mean
+ opposite things and -- unlike ``--name`` / ``--clear-name`` in the same command
+ -- the pair raised nothing. It also did not simply pick one: ``--clear-agent``
+ won for ``agent_name`` (-> None) while the mere PRESENCE of ``--agent`` POPS the
+ follow-the-session marker, so the definition looked like "no Agent pinned, and
+ not following its Session" and the re-resolution wrote today's scope / default
+ Agent back as a HARD PIN -- with neither flag's meaning honoured.
+
+ THE FIX is the convention ``--name`` / ``--clear-name`` already sets in this very
+ command: reject the contradictory pair, because the intent is genuinely ambiguous.
+ Asserted BOTH ways below so the two pairs cannot drift apart.
+
+ The stored definition must also be untouched: a rejected command may not have
+ written a pin on its way to failing.
+ """
+ from storage.importer import ensure_sqlite_state
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
+ agent_store = cli.VibeAgentStore(db_path)
+ try:
+ # The Agent the definition's Session runs as, and a DIFFERENT current
+ # default. The gap between them is what makes the re-pin observable at all.
+ agent_store.create(name="rebound", backend="codex")
+ successor = agent_store.create(name="successor", backend="claude")
+ agent_store.set_default_agent_name(successor.name)
+ finally:
+ agent_store.close()
+
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = store.add_watch(
+ name="ci watch",
+ session_key="slack::channel::C123",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix="CI finished.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key="slack::channel::C123",
+ agent_name=None,
+ metadata={cli.BINDING_FOLLOWS_SESSION_METADATA_KEY: True},
+ )
+
+ def _update(*argv: str) -> tuple[int, str]:
+ """Run the REAL command. Returns ``(exit code, raw stderr)``.
+
+ Stderr is returned unparsed on purpose: the pre-fix command SUCCEEDS and
+ writes nothing there, so parsing it eagerly would turn the interesting red
+ into a ``JSONDecodeError`` and hide which field was corrupted.
+ """
+ args = _parse_watch_update([watch.id, *argv])
+ cli_agent_store = cli.VibeAgentStore(db_path)
+ stderr = io.StringIO()
+ try:
+ with (
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=WatchRuntimeStateStore(tmp_path / "watch_runtime.json")),
+ patch("vibe.cli._agent_store", return_value=cli_agent_store),
+ redirect_stderr(stderr),
+ ):
+ return cli.cmd_watch_update(args), stderr.getvalue()
+ finally:
+ cli_agent_store.close()
+
+ result, stderr_text = _update("--agent", "rebound", "--clear-agent")
+
+ # The persisted definition first: this is the damage, and asserting it before the
+ # exit code keeps the red pointed at the regression rather than at the reporting.
+ stored = store.get_watch(watch.id)
+ assert stored is not None
+ assert stored.agent_name is None, (
+ f"the contradictory pair pinned agent_name={stored.agent_name!r} — today's "
+ f"default Agent ({successor.name!r}), which is neither the Agent that was "
+ "passed nor the cleared state that was asked for; every future watch hook now "
+ "runs as the wrong Agent"
+ )
+ assert stored.metadata.get(cli.BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "the contradictory pair dropped the follow-the-session state, so the bound "
+ "Session no longer governs the definition's Agent"
+ )
+ assert result == 1, (
+ "vibe watch update accepted --agent together with --clear-agent; it honours "
+ "neither flag and re-pins the definition to today's default Agent instead"
+ )
+ assert json.loads(stderr_text)["code"] == "conflicting_agent_update", stderr_text
+
+ # The convention this mirrors, asserted so the two pairs cannot drift apart.
+ name_result, name_stderr = _update("--name", "renamed", "--clear-name")
+ assert name_result == 1
+ assert json.loads(name_stderr)["code"] == "conflicting_name_update", name_stderr
+
+
+def _reclaim_bound_definitions_now(session_id: str, *, mode: str, reason: str) -> dict[str, int]:
+ """The shared teardown reclaim, run against the isolated state database."""
+ from config import paths
+ from storage.db import create_sqlite_engine
+ from storage.session_reclaim import reclaim_bound_definitions
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return reclaim_bound_definitions(conn, session_id, mode=mode, reason=reason)
+ finally:
+ engine.dispose()
+
+
+def _create_bare_agent_session(*, workdir: Path, anchor: str = "slack_C123") -> str:
+ """A Session row worth snapshotting, with no Agent for the CLI to resolve."""
+ from config import paths
+ from storage.agent_session_rows import create_agent_session_row
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return create_agent_session_row(
+ conn,
+ scope_id=None,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ model="gpt-5.5-codex",
+ native_session_id="codex-native",
+ workdir=str(workdir),
+ require_workdir=False,
+ )
+ finally:
+ engine.dispose()
+
+
+def test_watch_update_refuses_to_undo_a_reclaim_committed_after_its_read(tmp_path: Path) -> None:
+ """HFR-261, watch half — ``upsert_watch`` is the same full-row write.
+
+ Watches live in the same ``run_definitions`` table, are reclaimed by the same
+ ``reclaim_bound_definitions`` call, and were written back by the same whole-row
+ UPDATE keyed on ``id`` alone. Guarding only the task side would have left the
+ identical hole open for every ``vibe watch update``: the reclaim's pause, its
+ reason and its ``session_settings_snapshot`` restored to their pre-teardown
+ values, with the command reporting success.
+ """
+ from storage.session_reclaim import RECLAIM_PAUSE, SESSION_SETTINGS_SNAPSHOT_KEY
+
+ store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ session_id = _create_bare_agent_session(workdir=tmp_path)
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ metadata={"origin": "cli"},
+ )
+
+ summary = _reclaim_bound_definitions_now(
+ session_id, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared"
+ )
+ assert summary == {"paused": 1, "deleted": 0, "snapshotted": 1}, (
+ f"the reclaim itself did not land ({summary!r}), so the rest of this test is "
+ "meaningless"
+ )
+
+ args = _parse_watch_update([watch.id, "--name", "Renamed by the user"])
+ stderr = io.StringIO()
+ with (
+ redirect_stderr(stderr),
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_update(args)
+
+ assert result == 1, (
+ "the command reported success for a write the database refused; the stored "
+ "watch is whatever the teardown left, not what the user was shown"
+ )
+ payload = json.loads(stderr.getvalue())
+ assert payload["code"] == "definition_write_conflict"
+ assert payload["details"]["watch_id"] == watch.id
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None
+ assert stored.enabled is False, (
+ "the stale full-row write re-enabled a watch the teardown paused; its "
+ "supervisor starts cycles again against a session that no longer exists"
+ )
+ assert stored.last_error == "the bound agent session was cleared"
+ assert SESSION_SETTINGS_SNAPSHOT_KEY in stored.metadata, (
+ "the stale write replaced the reclaim's settings snapshot with the "
+ "pre-teardown metadata"
+ )
+ assert stored.name == "Watch CI", (
+ "the refused write partially landed — a lost compare-and-set must change NOTHING"
+ )
+ # HFR-271's rule: the store the COMMAND used is still in scope, and it is the half a
+ # fresh read cannot see. A refusal must leave both halves saying the same thing.
+ live = store.get_watch(watch.id)
+ assert live is not None and live.to_dict() == stored.to_dict(), (
+ "the write was refused and the live store kept the mutation: it still serves "
+ f"name={None if live is None else live.name!r} "
+ f"enabled={None if live is None else live.enabled!r} while the row says "
+ f"name={stored.name!r} enabled={stored.enabled!r}"
+ )
diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.py
index 81b860a03..cc8666e28 100644
--- a/tests/test_command_handler_user_names.py
+++ b/tests/test_command_handler_user_names.py
@@ -1,5 +1,7 @@
import importlib.util
+import os
import sys
+import tempfile
import types
import unittest
from pathlib import Path
@@ -7,6 +9,12 @@ from unittest.mock import patch
from modules.im import MessageContext
+# Imported before ``_load_command_handlers_class`` runs: that loader swaps
+# ``sys.modules`` under a ``patch.dict``, so a module first imported inside it is
+# dropped on exit and re-imported later as a SECOND object with its own
+# ContextVar. Pre-importing keeps one identity for the teardown ledger below.
+import storage.session_reclaim # noqa: F401
+
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@@ -290,6 +298,85 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):
[("wx-chat", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],
)
+ async def test_new_command_reports_paused_bound_definitions(self):
+ """D2 — `/new` pauses definitions pinned to the session it clears, and says so.
+
+ Without the notice the user's daily report silently stops with no
+ indication that an everyday command switched it off.
+ """
+ from storage.session_reclaim import current_reclaim_ledger
+
+ controller = _StubController({"display_name": "小王"})
+
+ async def _clear_and_reclaim(session_key):
+ ledger = current_reclaim_ledger()
+ assert ledger is not None, "/new did not open a teardown context"
+ ledger.append(
+ {
+ "definition_id": "task1",
+ "definition_type": "scheduled",
+ "mode": "pause",
+ "session_id": "ses1",
+ }
+ )
+ return {"claude": 1}
+
+ controller.agent_service.clear_sessions = _clear_and_reclaim # type: ignore[attr-defined]
+ handler = CommandHandlers(controller)
+ context = MessageContext(user_id="wx-user", channel_id="wx-chat")
+
+ await handler.handle_new(context)
+
+ self.assertEqual(len(controller.im_client.sent_messages), 1)
+ text = controller.im_client.sent_messages[0][1]
+ self.assertIn("已开启新的会话", text)
+ self.assertIn("已暂停 1 个", text)
+ self.assertIn("vibe task resume", text)
+
+ async def test_new_command_gives_watches_their_own_recovery_commands(self):
+ """HFR-058 — a paused watch must be told the commands that can reach it.
+
+ Tasks and watches are reclaimed by the same teardown but are managed by
+ two different command groups. ``vibe task resume <watch-id>`` fails with
+ ``task_not_found``, so a combined notice hands the watch half of the
+ audience directions that cannot work -- and the watch stays paused.
+ """
+ from storage.session_reclaim import current_reclaim_ledger
+
+ controller = _StubController({"display_name": "小王"})
+
+ async def _clear_and_reclaim(session_key):
+ ledger = current_reclaim_ledger()
+ assert ledger is not None, "/new did not open a teardown context"
+ ledger.append(
+ {
+ "definition_id": "task1",
+ "definition_type": "scheduled",
+ "mode": "pause",
+ "session_id": "ses1",
+ }
+ )
+ ledger.append(
+ {
+ "definition_id": "watch1",
+ "definition_type": "watch",
+ "mode": "pause",
+ "session_id": "ses1",
+ }
+ )
+ return {"claude": 1}
+
+ controller.agent_service.clear_sessions = _clear_and_reclaim # type: ignore[attr-defined]
+ handler = CommandHandlers(controller)
+ context = MessageContext(user_id="wx-user", channel_id="wx-chat")
+
+ await handler.handle_new(context)
+
+ text = controller.im_client.sent_messages[0][1]
+ self.assertIn("vibe task resume", text)
+ self.assertIn("vibe watch resume", text)
+ self.assertIn("vibe watch list", text)
+
async def test_setcwd_keeps_existing_scope_session_and_shows_new_hint(self):
controller = _StubController({"display_name": "小王"})
controller.settings_manager.session_row = {"agent_backend": "claude"}
@@ -445,6 +532,241 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("私信", text)
+class _RecordingBackendAgent:
+ """One registered backend adapter, over REAL storage.
+
+ ``clear_sessions`` reproduces the adapter's storage-facing line verbatim --
+ ``modules/agents/codex/agent.py`` and its siblings all run
+ ``self.sessions.clear_agent_sessions(session_key, self.name)`` -- and drops
+ only the in-memory runtime bookkeeping (turn registry, session locks) that
+ has no bearing on which rows survive. The store underneath is the real
+ ``config.v2_sessions.SessionsStore``, so the SQL that decides survival is
+ production's, not the test's.
+ """
+
+ def __init__(self, name: str, sessions, calls: list):
+ self.name = name
+ self.sessions = sessions
+ self._calls = calls
+
+ async def clear_sessions(self, session_key: str) -> int:
+ self._calls.append(("clear_agent_sessions", session_key, self.name))
+ return self.sessions.clear_agent_sessions(session_key, self.name)
+
+
+class _RealStorageAgentService:
+ """Mirrors ``AgentService.clear_sessions``: fan out to EVERY registered backend.
+
+ The fan-out is the point. ``/new`` does not clear only the backend that owns
+ the live session; it clears all of them, which is how a clear issued for
+ ``claude`` reaches a row bound to ``codex``.
+ """
+
+ def __init__(self, sessions, names, calls: list):
+ self.default_agent = "codex"
+ self.agents = {name: _RecordingBackendAgent(name, sessions, calls) for name in names}
+
+ async def clear_sessions(self, session_key: str) -> dict:
+ cleared: dict = {}
+ for name, agent in self.agents.items():
+ count = await agent.clear_sessions(session_key)
+ if count:
+ cleared[name] = count
+ return cleared
+
+
+class NewCommandStorageIntegrationTests(unittest.IsolatedAsyncioTestCase):
+ """HFR-242 — `/new` end to end, over real storage rather than a service call.
+
+ The service-method regressions (HFR-240/241) call ``delete_agent_sessions``
+ directly, which is the path that was FIXED rather than the path a user
+ takes. That is how the previous fix passed its own test while ``/new`` still
+ destroyed the row: the guard sat in the ``session_anchor_prefix`` branch, and
+ ``handle_new`` reaches storage through ``agent_service.clear_sessions()``
+ FIRST -- backend-wide, no prefix -- so the row was already gone before the
+ guarded clear ran. Only a test that drives ``handle_new`` itself, through
+ both calls in their real order, can catch that class of miss.
+ """
+
+ async def test_new_keeps_a_superseded_session_and_its_definitions_but_clears_the_live_one(self):
+ from sqlalchemy import select as sa_select
+
+ from config.v2_sessions import SessionsStore
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions, run_definitions
+
+ session_key = "slack::C9"
+ anchor = "slack_C9"
+ now = "2026-06-08T00:00:00Z"
+
+ with tempfile.TemporaryDirectory() as tmp_home, patch.dict(
+ os.environ, {"AVIBE_HOME": tmp_home}, clear=False
+ ):
+ state_dir = Path(tmp_home) / "state"
+ state_dir.mkdir(parents=True, exist_ok=True)
+ store = SessionsStore(sessions_path=state_dir / "sessions.json")
+ engine = None
+ try:
+ # The row `/new` must NOT destroy: bound to codex with a native id
+ # that is write-once, then superseded when claude claims the same
+ # anchor. Superseding renames the anchor and keeps the row on
+ # purpose -- its transcript is not recoverable.
+ superseded_id = store.bind_agent_session(session_key, "codex", anchor, "codex-native-1")
+ self.assertIsNotNone(superseded_id)
+ live_id = store.ensure_agent_session_id(session_key, "claude", anchor)
+ self.assertIsNotNone(live_id)
+ self.assertNotEqual(live_id, superseded_id)
+
+ engine = create_sqlite_engine(store.db_path)
+ with engine.connect() as conn:
+ superseded_anchor = conn.execute(
+ sa_select(agent_sessions.c.session_anchor).where(
+ agent_sessions.c.id == superseded_id
+ )
+ ).scalar_one()
+ self.assertIn(":superseded:", superseded_anchor, "fixture did not actually supersede the row")
+
+ # A scheduled task pinned to each row. The pinned/live pair is what
+ # separates "the guard works" from "the guard preserves everything".
+ with engine.begin() as conn:
+ for def_id, sid in (("task_pinned", superseded_id), ("task_live", live_id)):
+ conn.execute(
+ run_definitions.insert().values(
+ id=def_id,
+ definition_type="scheduled",
+ enabled=1,
+ deleted_at=None,
+ session_id=sid,
+ created_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ calls: list = []
+ real_clear_base = store.clear_session_base
+
+ def _recording_clear_base(user_id, base_session_id):
+ calls.append(("clear_session_base", user_id, base_session_id))
+ return real_clear_base(user_id, base_session_id)
+
+ store.clear_session_base = _recording_clear_base # type: ignore[method-assign]
+
+ controller = _StubController({"display_name": "Alex"})
+ controller.sessions = store
+ controller.agent_service = _RealStorageAgentService(store, ["claude", "codex"], calls)
+ handler = CommandHandlers(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C9",
+ platform="slack",
+ platform_specific={"platform": "slack"},
+ )
+
+ await handler.handle_new(context)
+
+ # `/new`'s real call order: every backend cleared scope-wide FIRST,
+ # the anchor-prefixed clear only after. A guard that lives in the
+ # second call is dead code by the time it runs.
+ self.assertEqual(
+ calls,
+ [
+ ("clear_agent_sessions", session_key, "claude"),
+ ("clear_agent_sessions", session_key, "codex"),
+ ("clear_session_base", session_key, anchor),
+ ],
+ )
+
+ with engine.connect() as conn:
+ surviving = {
+ row["id"]: dict(row)
+ for row in conn.execute(sa_select(agent_sessions)).mappings()
+ }
+ definitions = {
+ row["id"]: dict(row)
+ for row in conn.execute(sa_select(run_definitions)).mappings()
+ }
+ # The LIVE half, captured while the store is still the one `/new` ran
+ # against. Everything above reads the durable rows through an engine
+ # this test opened; the process that has to keep serving them is this
+ # ``SessionsStore``.
+ live_mappings = {
+ str(agent_name): dict(thread_map)
+ for agent_name, thread_map in store.state.session_mappings.get(
+ session_key, {}
+ ).items()
+ }
+ finally:
+ if engine is not None:
+ engine.dispose()
+ store.close()
+
+ # 1. The superseded session survived `/new`, transcript pointer intact.
+ self.assertIn(
+ superseded_id,
+ surviving,
+ "`/new` hard-deleted the superseded session row; superseding promises the row is kept, "
+ "and its native session id is write-once",
+ )
+ self.assertEqual(
+ surviving[superseded_id]["native_session_id"],
+ "codex-native-1",
+ "the superseded row survived but lost the native id that makes it resumable",
+ )
+
+ # 2. Its bound definition was never reclaimed: the session it targets is
+ # still there, so pausing it would silently stop a user's task for no
+ # reason -- the D2 regression in the opposite direction.
+ pinned = definitions["task_pinned"]
+ self.assertIsNone(pinned["deleted_at"], "the definition pinned to a SURVIVING session was soft-deleted")
+ self.assertEqual(
+ pinned["enabled"],
+ 1,
+ "the definition pinned to a SURVIVING session was paused; nothing was torn down under it",
+ )
+
+ # 3. The live row in the same scope WAS cleared -- the guard is not simply
+ # preserving everything -- and its definition is PAUSED, not deleted
+ # (D2: `/new` is an everyday command, archive is the terminal one).
+ self.assertNotIn(live_id, surviving, "`/new` failed to clear the live session it is supposed to clear")
+ live_def = definitions["task_live"]
+ self.assertIsNone(live_def["deleted_at"], "a `/new` teardown soft-deleted a definition; D2 requires a pause")
+ self.assertEqual(live_def["enabled"], 0, "the definition still fires into a deleted session")
+ self.assertTrue(live_def["last_error"], "the definition was paused with no explanation")
+
+ # 4. HFR-274 -- AND THE LIVE HALF AGREES WITH ALL OF THAT. Everything above
+ # reads the durable rows through an engine this test opened. The running
+ # process keeps its own map of anchor -> session id, and
+ # ``clear_session_base`` used to prune it by the same prefix rule the SQL
+ # once used: ``<anchor>:superseded:<id>`` starts with the anchor, so the
+ # local pointer to the row the guard deliberately KEPT was deleted anyway
+ # and ``save_state`` made it permanent. A row nothing can reach is not a
+ # row that was kept.
+ mapped_anchors = {
+ thread_id for thread_map in live_mappings.values() for thread_id in thread_map
+ }
+ self.assertIn(
+ superseded_anchor,
+ mapped_anchors,
+ "the live session map lost its entry for the superseded session the database "
+ f"kept ({superseded_id} at {superseded_anchor}); the map holds {live_mappings!r}",
+ )
+ self.assertNotIn(
+ anchor,
+ mapped_anchors,
+ "the live session map still points at the anchor `/new` cleared: "
+ f"{live_mappings!r}",
+ )
+ self.assertIn("/new", live_def["last_error"])
+
+ # 4. The user is told about exactly the one definition that was paused.
+ # Two would mean the superseded row was reclaimed as well.
+ self.assertEqual(len(controller.im_client.sent_messages), 1)
+ text = controller.im_client.sent_messages[0][1]
+ self.assertIn("已开启新的会话", text)
+ self.assertIn("已暂停 1 个", text)
+
+
async def _clear_sessions(_settings_key):
return {}
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index fd057e041..4b4cc3419 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -744,3 +744,121 @@ def test_update_session_legacy_blank_backend_keeps_initial_pin_escape(isolated_s
# Now pinned: a different backend is rejected.
with pytest.raises(sessions_service.SessionBackendLockedError):
sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude")
+
+
+# --- HFR-247: the override marker must not outlive the columns it describes ----
+
+
+def test_workbench_default_action_drops_the_explicit_override_marker(isolated_state, tmp_path):
+ """HFR-247 — the Chat header's "Default" must actually restore the defaults.
+
+ ``agent_sessions.metadata_json.explicit_setting_overrides`` tells dispatch
+ that this session's NULL ``model`` / ``reasoning_effort`` are a deliberate pin
+ ("inherit nothing"), not the ordinary "inherit from the Agent". Only the
+ ``create_once`` rebind wrote it -- but any writer of those columns replaces
+ what the marker describes. ``update_session`` only rewrote ``metadata_json``
+ on a title change or a scope move, so the Workbench "Default" action (present
+ nulls for the whole route) left the marker in place: the session then showed a
+ cleared route, and every turn still ran with NO model and NO reasoning effort
+ while claiming to run as the default Agent. The control looked like it worked
+ and routed nothing.
+ """
+
+ import asyncio
+
+ from config import paths
+ from core.handlers.message_handler import MessageHandler
+ from core.internal_server import _build_session_context
+ from core.vibe_agents import VibeAgentStore
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+ from tests.test_scheduled_tasks import _DispatchController, _DispatchSessionHandler
+
+ workdir = tmp_path / "workdir"
+ workdir.mkdir()
+
+ agent_store = VibeAgentStore()
+ try:
+ agent_store.ensure_builtin_default_agents(["codex"])
+ agent_store.set_default_agent_name("codex")
+ # The Agent the cleared session must fall back to. Distinctive values so
+ # "inherited the Agent's defaults" cannot pass on a None == None compare.
+ default_agent = agent_store.update(
+ "codex", model="gpt-5.5-default", reasoning_effort="xhigh"
+ )
+ finally:
+ agent_store.close()
+ assert default_agent.model == "gpt-5.5-default"
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn, workdir=str(workdir))
+ # A session that pins NOTHING on purpose -- the shape a preserved
+ # ``create_once`` rebind reserves (D3) and the user then opens in Chat.
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="codex",
+ agent_variant="codex",
+ model=None,
+ reasoning_effort=None,
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+ sid = session["id"]
+
+ # An UNRELATED edit must not touch a marker entry it knows nothing about.
+ renamed = sessions_service.update_session(conn, sid, title="Nightly digest")
+ assert renamed["metadata"][SESSION_SETTINGS_OVERRIDE_KEY] == [
+ "model",
+ "reasoning_effort",
+ ], "a title-only edit dropped an override marker it never wrote"
+
+ # The Chat header's "Default" item: present nulls for the whole route.
+ cleared = sessions_service.update_session(
+ conn,
+ sid,
+ agent_id=None,
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ )
+
+ assert cleared["model"] is None
+ assert cleared["reasoning_effort"] is None
+ assert SESSION_SETTINGS_OVERRIDE_KEY not in cleared["metadata"], (
+ "'Default' replaced model/reasoning_effort but left the explicit-override "
+ "marker, so dispatch keeps honouring a pin the user just removed"
+ )
+ # The title metadata the earlier edit wrote is still there: reconciling the
+ # marker must compose with the other metadata writers, not replace them.
+ assert cleared["metadata"]["title_source"] == "user"
+
+ # The deliverable is the turn, not the row. Build the REAL workbench dispatch
+ # context from the stored row and run the REAL MessageHandler.
+ context = _build_session_context(sid, message_id="m1")
+ controller = _DispatchController(paths.get_sqlite_state_path(), workdir)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_DispatchSessionHandler(str(workdir)))
+ controller.message_handler = handler
+ controller.session_handler = handler.session_handler
+ try:
+ asyncio.run(handler.handle_user_message(context, "hello"))
+ finally:
+ controller.sessions.close()
+ controller.vibe_agent_store.close()
+
+ assert len(controller.agent_service.dispatched) == 1
+ backend_name, request = controller.agent_service.dispatched[0]
+ assert backend_name == default_agent.backend
+ assert request.vibe_agent_name == default_agent.name
+ assert request.vibe_agent_model == "gpt-5.5-default", (
+ f"dispatch handed the backend model={request.vibe_agent_model!r}: the stale "
+ "marker still forces the cleared session's NULL, so 'Default' changed the "
+ "stored row and nothing else"
+ )
+ assert request.vibe_agent_reasoning_effort == "xhigh", (
+ f"dispatch handed the backend reasoning_effort="
+ f"{request.vibe_agent_reasoning_effort!r} instead of the default Agent's"
+ )
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 07193077f..b4a22a7d3 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -17,6 +17,7 @@ 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.controller import Controller
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.message_output import stop_output_for
from core.run_settlement import (
@@ -29,9 +30,12 @@ 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 (
+ BINDING_FOLLOWS_SESSION_METADATA_KEY,
+ BINDING_RECOVERY_METADATA_KEY,
ParsedSessionKey,
ScheduledTaskService,
ScheduledTaskStore,
+ SessionBindingChange,
TaskExecutionRequest,
TaskExecutionStore,
_agent_run_message_for_request,
@@ -43,7 +47,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.models import agent_runs, run_definitions
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
from storage.agent_session_rows import create_agent_session_row
@@ -122,6 +126,58 @@ def test_resolve_session_id_target_keeps_scope_anchor_threadless(tmp_path: Path)
assert resolved.session_key.thread_id is None
+def test_superseding_a_bound_row_keeps_its_thread_routing(tmp_path: Path) -> None:
+ """HFR-057. Superseding must not silently unroute a bound session's definitions.
+
+ When another backend claims an anchor whose row already has a native id, the
+ row is kept and its anchor moved to ``superseded:<id>``. Pinned tasks and
+ watches stay attached to that row, but ``resolve_session_id_target`` derives
+ the thread solely from ``session_anchor`` -- and ``superseded:<id>`` splits to
+ the base ``superseded``, which matches no platform prefix. The thread is lost,
+ so ``--post-to thread`` definitions deliver to the channel root forever. The
+ row still exists, so the unresolvable-binding recovery never fires either.
+ """
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "vibe.sqlite"
+ target = parse_session_key("telegram::channel::-1001::thread::42")
+ scope_key = target.session_scope
+ session_anchor = session_anchor_for_target(target)
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = service.bind_agent_session(
+ scope_key=scope_key,
+ agent_name="codex",
+ session_anchor=session_anchor,
+ native_session_id="codex-native-1",
+ )
+ finally:
+ service.close()
+ assert session_id is not None
+
+ before = resolve_session_id_target(session_id, db_path=db_path)
+ assert before.session_key.thread_id == "42", "precondition: thread routing resolves"
+
+ # Another backend claims the same anchor; the bound row is superseded.
+ service = SQLiteSessionsService(db_path)
+ try:
+ other = service.ensure_agent_session_id(
+ scope_key=scope_key,
+ agent_name="claude",
+ session_anchor=session_anchor,
+ )
+ finally:
+ service.close()
+ assert other != session_id, "precondition: a fresh row took the freed anchor"
+
+ after = resolve_session_id_target(session_id, db_path=db_path)
+ assert after.session_key.thread_id == "42", (
+ "superseded row lost its thread routing: definitions pinned to it now "
+ f"deliver to the channel root (thread_id={after.session_key.thread_id!r})"
+ )
+
+
def test_resolve_session_id_target_preserves_reserved_user_scope(tmp_path: Path) -> None:
from storage.sessions_service import SQLiteSessionsService
@@ -6932,3 +6988,3373 @@ def test_dead_accepted_owner_converges_run_session_and_persisted_fifo(
assert controller.session_turns.turn_state(session_id)["pending_input_count"] == 0
asyncio.run(_exercise())
+
+
+# --- P5 (PR5): a pinned session binding must not break permanently ---
+# Scenario IDs: HFR-054 (auto-pause backstop) / HFR-055 (create_once rebind)
+# / HFR-056 (D3 settings preservation).
+
+
+def _binding_env(tmp_path: Path, monkeypatch, *, backends=("claude", "codex"), default="codex") -> Path:
+ """Migrated DB + enabled Agents + a slack channel scope, for binding tests."""
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ monkeypatch.setattr(paths, "get_state_dir", lambda: db_path.parent)
+ monkeypatch.setattr(paths, "get_sqlite_state_path", lambda: db_path)
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.ensure_builtin_default_agents(list(backends))
+ agent_store.set_default_agent_name(default)
+ finally:
+ agent_store.close()
+ with create_sqlite_engine(db_path).begin() as conn:
+ upsert_scope(conn, "slack", "channel", "C123", now="2026-07-27T00:00:00Z")
+ return db_path
+
+
+def _binding_service(tmp_path: Path, store: ScheduledTaskStore, calls: list) -> ScheduledTaskService:
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ calls.append(message)
+ return None
+
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_kw: None))
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+ service.scheduler = _StubScheduler()
+ return service
+
+
+#: A system prompt no default fixture would produce, so "the fallback Agent's
+#: prompt reached the request" cannot pass on a None == None comparison.
+_FALLBACK_AGENT_SYSTEM_PROMPT = "You are the scope default Agent. Answer tersely."
+
+
+class _DispatchIMClient:
+ """The minimum IM surface ``MessageHandler`` touches on a scheduled turn."""
+
+ def __init__(self) -> None:
+ self.sent: list[str] = []
+ self.formatter = SimpleNamespace(format_error=lambda text: text)
+
+ def should_use_thread_for_reply(self) -> bool:
+ return True
+
+ def should_use_thread_for_dm_session(self) -> bool:
+ return False
+
+ def should_use_message_id_for_channel_session(self, _context=None) -> bool:
+ return True
+
+ async def prepare_turn_context(self, context, source):
+ return context
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ self.sent.append(text)
+ return "msg-1"
+
+
+class _CapturingAgentService:
+ """Stands in for the backend registry and records what dispatch received.
+
+ The recorded ``request`` is the REAL ``modules.agents.base.AgentRequest`` the
+ real ``MessageHandler`` built — the values under test (Agent identity, model,
+ reasoning effort, system prompt) are re-derived there, downstream of both the
+ stored session row and the scheduler's context payload.
+ """
+
+ def __init__(self) -> None:
+ self.default_agent = "codex"
+ self.agents: dict = {}
+ self.dispatched: list = []
+
+ async def handle_message(self, agent_name, request):
+ self.dispatched.append((agent_name, request))
+ return None
+
+
+class _DispatchSessionHandler:
+ def __init__(self, working_path: str) -> None:
+ self.working_path = working_path
+
+ def get_session_info(self, context, source="human"):
+ base = "slack_C123"
+ return (base, self.working_path, f"{base}:{self.working_path}")
+
+ @staticmethod
+ def should_allocate_scheduled_anchor(context, source="human") -> bool:
+ return False
+
+ @staticmethod
+ def alias_session_base(context, *, source_base_session_id, alias_base_session_id, clear_source=False):
+ return False
+
+
+class _DispatchController:
+ """Controller double wired for the REAL ``MessageHandler`` dispatch path.
+
+ Only the collaborators ``MessageHandler`` actually reaches on a scheduled
+ turn are doubled. Agent identity resolution deliberately is NOT: it runs
+ against the real :class:`~core.vibe_agents.VibeAgentStore` on the test DB,
+ because which VibeAgent the turn lands on is exactly what is under test.
+ """
+
+ def __init__(self, db_path: Path, working_path: Path) -> None:
+ from core.processing_indicator import ProcessingIndicatorService
+ from storage.sessions_service import SQLiteSessionsService
+
+ self.db_path = db_path
+ self.config = SimpleNamespace(
+ platform="slack",
+ ack_mode="reaction",
+ include_time_info=False,
+ include_user_info=False,
+ language="en",
+ )
+ self.im_client = _DispatchIMClient()
+ self.sessions = SQLiteSessionsService(db_path)
+ self.settings_manager = SimpleNamespace(
+ sessions=self.sessions,
+ get_channel_routing=lambda _settings_key: None,
+ get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_kw: None),
+ )
+ self.platform_settings_managers = {"slack": self.settings_manager}
+ self.session_manager = SimpleNamespace()
+ self.receiver_tasks: dict = {}
+ self.agent_service = _CapturingAgentService()
+ # Reached only on HUMAN turns (the Workbench dispatch path); a bare
+ # namespace makes the handler's ``getattr`` probes miss and move on.
+ self.agent_auth_service = SimpleNamespace()
+ self.primary_platform = "slack"
+ from core.vibe_agents import VibeAgentStore
+
+ self.vibe_agent_store = VibeAgentStore(db_path)
+ self.processing_indicator = ProcessingIndicatorService(self)
+ self.completed_turns: list = []
+
+ # -- VibeAgent resolution: the REAL controller methods, not a mirror --------
+ #
+ # Bound straight off ``Controller`` rather than reimplemented here. The
+ # precedence between an override name, ``agent_run_target`` /
+ # ``agent_session_target`` and channel routing IS the thing under test, so a
+ # hand-written copy could agree with the test and disagree with production --
+ # the proxy pattern these regressions exist to close. Only the collaborators
+ # they read (`vibe_agent_store`, `_get_settings_key`,
+ # `get_settings_manager_for_context`, `primary_platform`) are doubled, and
+ # the store underneath is the real one on the test DB.
+ resolve_vibe_agent_for_context = Controller.resolve_vibe_agent_for_context
+ resolve_agent_for_context = Controller.resolve_agent_for_context
+ # Re-wrapped: accessing it off ``Controller`` resolves the descriptor to a
+ # plain function, which would rebind as an instance method here.
+ _agent_run_target_payload = staticmethod(Controller._agent_run_target_payload)
+
+ # -- misc controller surface ----------------------------------------------
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+ def get_settings_manager_for_context(self, context):
+ return self.settings_manager
+
+ def _get_settings_key(self, context) -> str:
+ from core.message_context import resolve_context_scope_settings_key
+
+ return resolve_context_scope_settings_key(context)
+
+ def _get_session_key(self, context) -> str:
+ from core.message_context import build_context_session_key, resolve_context_settings_key
+
+ platform = context.platform or (context.platform_specific or {}).get("platform") or "slack"
+ return build_context_session_key(
+ context, platform=platform, settings_key=resolve_context_settings_key(context)
+ )
+
+ def _get_lang(self) -> str:
+ return "en"
+
+ def update_thread_message_id(self, context):
+ return None
+
+ def mark_turn_complete(self, context) -> None:
+ self.completed_turns.append(context)
+
+ async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", **_kwargs):
+ return None
+
+
+def _dispatching_binding_service(
+ tmp_path: Path, store: ScheduledTaskStore, *, db_path: Path
+) -> ScheduledTaskService:
+ """``_binding_service`` with the PRODUCTION dispatch path attached.
+
+ ``_binding_service`` replaces ``handle_scheduled_message`` with a double that
+ records the prompt string. That proves a run fired, but every value the
+ binding-recovery tests care about — which VibeAgent the turn runs as, its
+ backend, its system prompt, its model / reasoning effort — is re-derived
+ INSIDE ``MessageHandler`` from the session row and the scheduler's context
+ payload, i.e. strictly downstream of anything the prompt-recording double can
+ observe. So the real handler is wired in here and the assertions move to the
+ ``AgentRequest`` it hands to ``AgentService.handle_message``.
+ """
+ from core.handlers.message_handler import MessageHandler
+
+ working_path = tmp_path / "workdir"
+ working_path.mkdir(parents=True, exist_ok=True)
+ controller = _DispatchController(db_path, working_path)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_DispatchSessionHandler(str(working_path)))
+ controller.message_handler = handler
+ controller.session_handler = handler.session_handler
+
+ service = ScheduledTaskService(
+ controller=controller,
+ store=store,
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+ service.scheduler = _StubScheduler()
+ return service
+
+
+def _spy_binding_notices(service: ScheduledTaskService) -> list:
+ notices: list = []
+ original = service._notify_binding_change
+
+ async def _spy(task, change):
+ notices.append(change)
+ return await original(task, change)
+
+ service._notify_binding_change = _spy # type: ignore[method-assign]
+ return notices
+
+
+def test_execute_task_pauses_and_notifies_when_pinned_session_is_missing(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-054 — an unresolvable pinned session must not fire forever.
+
+ ``resolve_session_id_target`` raises, ``_execute_task`` records the error and
+ leaves ``enabled=1``, so the definition re-fires and re-fails on every cron
+ minute with nobody told. The backstop pauses it and notifies once.
+ """
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ calls: list = []
+ service = _binding_service(tmp_path, store, calls)
+ notices = _spy_binding_notices(service)
+
+ asyncio.run(service._run_task(task.id))
+
+ updated = store.get_task(task.id)
+ assert updated is not None
+ assert updated.enabled is False, "a permanently broken binding kept firing"
+ assert updated.last_error
+ assert "sesdoesnotexist" in updated.last_error
+ assert not calls
+ assert len(notices) == 1
+ assert notices[0].action == "paused"
+
+
+def test_existing_policy_never_rebinds(tmp_path: Path, monkeypatch) -> None:
+ """HFR-054 — ``existing`` is user-pinned: pause and notify, never re-point.
+
+ Silently reserving a different session for a user-pinned task would lose the
+ continuity the pin exists to guarantee.
+ """
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ service = _binding_service(tmp_path, store, [])
+
+ asyncio.run(service._run_task(task.id))
+
+ updated = store.get_task(task.id)
+ assert updated is not None
+ assert updated.session_id == "sesdoesnotexist"
+ assert updated.enabled is False
+
+
+def test_create_once_rebinds_when_session_deleted(tmp_path: Path, monkeypatch) -> None:
+ """HFR-055 — ``create_once`` reserved its own session, so it may re-reserve.
+
+ ``/new`` hard-deletes the session a ``create_once`` definition reserved at
+ definition time and nothing updates ``run_definitions.session_id``. The
+ definition re-reserves, keeps running, and always says so.
+ """
+ db_path = _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ calls: list = []
+ service = _binding_service(tmp_path, store, calls)
+ notices = _spy_binding_notices(service)
+
+ asyncio.run(service._run_task(task.id))
+
+ updated = store.get_task(task.id)
+ assert updated is not None
+ assert updated.enabled is True, "a rebindable definition was paused"
+ assert updated.session_id and updated.session_id != "sesdoesnotexist"
+ resolve_session_id_target(updated.session_id, db_path=db_path)
+ assert calls == ["send digest"], "the rebound run never executed"
+ assert len(notices) == 1
+ assert notices[0].action == "rebound"
+
+
+def test_repeated_failures_do_not_notify_twice(tmp_path: Path, monkeypatch) -> None:
+ """HFR-054 — one broken binding is one notification, not one per fire.
+
+ A daily cron on a dead session would otherwise notify daily. The dedup is
+ keyed on the failure signature, so re-firing the same unresolved binding
+ (a resumed-but-still-broken definition) stays quiet.
+ """
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ service = _binding_service(tmp_path, store, [])
+ notices = _spy_binding_notices(service)
+
+ for _ in range(2):
+ store.set_enabled(task.id, True)
+ current = store.get_task(task.id)
+ assert current is not None
+ asyncio.run(service._execute_task(current, execution_id="exec-1", disable_one_shot=False))
+
+ assert len(notices) == 1
+
+
+def test_rebind_preserves_model_of_the_deleted_session(tmp_path: Path, monkeypatch) -> None:
+ """HFR-056 — the executable form of D3.
+
+ ``run_definitions`` has no ``model``/``reasoning_effort`` column and the session
+ row is hard-deleted, so without the reclaim snapshot ``_reserve_runtime_session``
+ re-resolves the CURRENT scope Agent and silently changes the task's settings.
+ Here the deleted session ran on ``claude`` with an explicit model while the
+ default Agent is ``codex``: the rebind must keep the old settings.
+ """
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(model="legacy-model", reasoning_effort="high", agent_name="claude")
+ )
+
+ # The SQLite-backed store is the one the reclaim snapshot is written into.
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # ``/new`` in that channel.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ # The scheduler process that fires this definition next reads it fresh; the
+ # reclaim has already paused it, so resume it the way a user would.
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ service = _binding_service(tmp_path, store, [])
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ assert reloaded.metadata.get("session_settings_snapshot"), "reclaim wrote no settings snapshot"
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ rebound = store.get_task(task.id)
+ assert rebound is not None
+ assert rebound.session_id and rebound.session_id != pinned
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(
+ agent_sessions.c.model,
+ agent_sessions.c.reasoning_effort,
+ agent_sessions.c.agent_backend,
+ ).where(agent_sessions.c.id == rebound.session_id)
+ ).one()
+ assert row.model == "legacy-model"
+ assert row.reasoning_effort == "high"
+ assert row.agent_backend == "claude"
+
+
+def test_rebind_falls_back_to_scope_defaults_when_the_snapshot_agent_is_gone(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-243 — the non-preserving rebind must not retry the Agent that just failed.
+
+ ``_rebind_create_once_session`` tries the snapshot's settings first and, when
+ that reservation fails, falls back to a reset one whose whole purpose is to
+ degrade to scope defaults -- its own notice says "settings could not be
+ recovered, so scope defaults were used". But the fallback re-sent
+ ``task.agent_name``, and for a ``create_once`` definition that is the SAME
+ name the snapshot carries. A deleted or disabled Agent therefore failed
+ ``require_enabled`` twice, both attempts were exhausted, and the definition
+ was paused -- the permanent failure the fallback exists to prevent.
+ """
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.base import AgentRequest
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.create(name="nightly", backend="claude", model="legacy-model")
+ default_agent = agent_store.get_default_agent()
+ assert default_agent is not None and default_agent.name != "nightly"
+ # A distinctive prompt so "the fallback Agent's system prompt reached the
+ # request" cannot pass vacuously on a None-vs-None comparison.
+ default_agent = agent_store.update(
+ default_agent.name, system_prompt=_FALLBACK_AGENT_SYSTEM_PROMPT
+ )
+ finally:
+ agent_store.close()
+ assert default_agent.system_prompt == _FALLBACK_AGENT_SYSTEM_PROMPT
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(agent_name="nightly", model="legacy-model")
+ )
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ # The definition was pinned to the same Agent the session ran on, which is
+ # what makes the fallback's re-send a repeat of the failure.
+ agent_name="nightly",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new` in that channel deletes the row and writes the settings snapshot.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ # ...and the Agent the snapshot names is then deleted.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ assert agent_store.remove("nightly")
+ finally:
+ agent_store.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ notices = _spy_binding_notices(service)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ assert reloaded.metadata.get("session_settings_snapshot"), "reclaim wrote no settings snapshot"
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ rebound = store.get_task(task.id)
+ assert rebound is not None
+ assert rebound.enabled is True, (
+ "the definition was paused because the fallback retried the deleted Agent; "
+ "the reset attempt is supposed to degrade to scope defaults"
+ )
+ # Reserving a session is not the deliverable. A rebind that produces a row but
+ # never fires the run leaves the user with a definition that is enabled,
+ # looks healthy, and silently does nothing -- so the run itself is asserted,
+ # not just its binding.
+ assert len(dispatched) == 1, "the definition rebound but the run never reached the backend"
+ assert rebound.session_id and rebound.session_id != pinned, "no replacement session was reserved"
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(
+ agent_sessions.c.agent_name,
+ agent_sessions.c.agent_backend,
+ ).where(agent_sessions.c.id == rebound.session_id)
+ ).one()
+ assert row.agent_name == default_agent.name, "the rebind did not land on the scope/default Agent"
+ assert row.agent_backend == default_agent.backend
+ assert len(notices) == 1
+ assert notices[0].action == "rebound"
+ assert notices[0].settings_preserved is False, (
+ "a rebind that could not use the snapshot must say so, or the user reads a "
+ "settings reset as a settings-preserving recovery"
+ )
+
+ # The rebound ROW is not the deliverable either: ``MessageHandler`` re-derives
+ # the turn's Agent identity from the definition's own pin FIRST, so a row that
+ # says "default" and a pin that still says "nightly" dispatch under different
+ # Agents. Assert on the request the backend was actually handed.
+ retry_backend, retry_request = dispatched[0]
+ assert retry_request.message == "send digest", "the definition's prompt was not the turn input"
+ assert retry_backend == default_agent.backend
+ assert retry_request.vibe_agent_name == default_agent.name, (
+ "the retry reached the backend under the wrong Agent identity"
+ )
+ assert retry_request.vibe_agent_backend == default_agent.backend
+ assert retry_request.vibe_agent_system_prompt == _FALLBACK_AGENT_SYSTEM_PROMPT, (
+ "the fallback Agent's system prompt never reached the request, so the turn "
+ "ran with different instructions than the Agent it claims to run as"
+ )
+
+ # ...and it must still be true on a LATER, SEPARATE fire. The retry could be
+ # right by accident (in-memory task object) while the persisted definition
+ # still pins the dead Agent, in which case tomorrow's cron minute regresses.
+ # Re-read through a fresh store, exactly like the next scheduler tick does.
+ next_fire_store = ScheduledTaskStore()
+ next_fire_task = next_fire_store.get_task(task.id)
+ assert next_fire_task is not None
+ asyncio.run(
+ service._execute_task(next_fire_task, execution_id="exec-2", disable_one_shot=False)
+ )
+
+ # The durable half, asserted at the persistence layer as well as through
+ # dispatch: a retry-only fix (pass the fallback Agent to this one
+ # ``_execute_request`` and leave the definition alone) satisfies exec-1 and
+ # fails here, which is exactly the shape this pair exists to catch.
+ assert next_fire_task.agent_name is None, (
+ "the definition still pins the deleted Agent, so every future fire re-sends it "
+ "as vibe_agent_name and dispatches under an Agent that cannot be resolved"
+ )
+ assert len(dispatched) == 2, "the second fire never reached the backend"
+ later_backend, later_request = dispatched[1]
+ assert later_backend == default_agent.backend
+ assert later_request.vibe_agent_name == default_agent.name, (
+ "the fallback Agent did not survive to the next fire; the definition still "
+ "pins the deleted Agent durably"
+ )
+ assert later_request.vibe_agent_backend == default_agent.backend
+ assert later_request.vibe_agent_system_prompt == _FALLBACK_AGENT_SYSTEM_PROMPT
+ assert "nightly" not in {request.vibe_agent_name for _backend, request in dispatched}, (
+ "a dispatched turn still identified as the deleted Agent"
+ )
+ for _backend, request in dispatched:
+ assert isinstance(request, AgentRequest), "the captured request is not the production type"
+
+
+def test_rebind_keeps_a_snapshot_null_model_instead_of_adopting_the_agents(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-244 — a snapshot's NULL model is a pinned value, not a missing one.
+
+ ``_reserve_runtime_session`` read ``model is not None`` as "an override was
+ supplied", so a snapshot recording ``model=NULL`` -- the session pinned
+ nothing and inherited whatever its Agent had at the time -- was
+ indistinguishable from passing no override at all. If the Agent is edited
+ between the reclaim and the rebind, the replacement session silently acquires
+ a model the original never had, while the recovery is still recorded as
+ settings-preserving. The record says preserved; the session is not.
+ """
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.base import AgentRequest
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ # Pins neither a model nor a reasoning effort, so neither does the session.
+ agent_store.create(name="nightly", backend="claude")
+ finally:
+ agent_store.close()
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(agent_name="nightly", model=None, reasoning_effort=None)
+ )
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new` in that channel: the snapshot records model=NULL.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ # The Agent is edited AFTER the session was reclaimed -- an ordinary Agent
+ # Settings edit, with no way to know a reclaimed session points at it.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.update("nightly", model="claude-opus-4-6", reasoning_effort="high")
+ finally:
+ agent_store.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ notices = _spy_binding_notices(service)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ snapshot = reloaded.metadata.get("session_settings_snapshot")
+ assert snapshot, "reclaim wrote no settings snapshot"
+ assert snapshot.get("model") is None, "precondition: the snapshot pinned no model"
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ rebound = store.get_task(task.id)
+ assert rebound is not None
+ assert rebound.session_id and rebound.session_id != pinned
+
+ # What the backend was ACTUALLY handed. A NULL in the session row is only half
+ # the guarantee: ``MessageHandler`` reads a NULL session column as "inherit
+ # from the Agent at dispatch time" -- correct for every other session, and
+ # exactly the value D3 says must NOT be adopted here -- so the preserved nulls
+ # have to survive into the request, which is the only thing the agent sees.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ edited_agent = agent_store.require_enabled("nightly")
+ finally:
+ agent_store.close()
+ # Proves the request's nulls are a real override, not an empty fixture.
+ assert edited_agent.model == "claude-opus-4-6"
+ assert edited_agent.reasoning_effort == "high"
+
+ assert len(dispatched) == 1, "the rebound definition never reached the backend"
+ backend_name, request = dispatched[0]
+ assert isinstance(request, AgentRequest), "the captured request is not the production type"
+ assert backend_name == edited_agent.backend
+ assert request.vibe_agent_name == "nightly", (
+ "precondition: the turn still runs as the same Agent, only its settings differ"
+ )
+ assert request.vibe_agent_model is None, (
+ f"dispatch handed the backend model={request.vibe_agent_model!r} from the Agent's "
+ "CURRENT settings; the snapshot pinned none and D3 says preserve that"
+ )
+ assert request.vibe_agent_reasoning_effort is None, (
+ f"dispatch handed the backend reasoning_effort="
+ f"{request.vibe_agent_reasoning_effort!r} the session never had"
+ )
+
+ # ...and the durable record must agree. Read AFTER dispatch on purpose: the
+ # turn-start route materialization writes the resolved model back onto empty
+ # session columns, so an adopted model does not just mis-route this run, it
+ # becomes the session's pinned model for every run after it.
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(
+ agent_sessions.c.model,
+ agent_sessions.c.reasoning_effort,
+ ).where(agent_sessions.c.id == rebound.session_id)
+ ).one()
+ assert row.model is None, (
+ f"the rebound session acquired model={row.model!r} from the Agent's CURRENT "
+ "settings; the snapshot pinned none and D3 says preserve it"
+ )
+ assert row.reasoning_effort is None, (
+ f"the rebound session acquired reasoning_effort={row.reasoning_effort!r} it never had"
+ )
+ assert len(notices) == 1
+ assert notices[0].settings_preserved is True, (
+ "this rebind DID use the snapshot, so it must not be reported as a reset"
+ )
+
+
+#: The system prompt of the Agent the reset rebind lands on, and of the Agent that
+#: later becomes the default. Distinct strings so "the turn ran as the Agent it
+#: claims to" is asserted on content, not on a None == None comparison.
+_REBOUND_AGENT_SYSTEM_PROMPT = "You are the rebound session's Agent. Answer tersely."
+_SUCCESSOR_AGENT_SYSTEM_PROMPT = "You are the NEW scope default. Answer at length."
+
+
+def test_unrelated_task_update_keeps_the_rebound_sessions_agent_authority(
+ tmp_path: Path, monkeypatch, capsys
+) -> None:
+ """HFR-245 — "follow the rebound Session's Agent" must survive ordinary edits.
+
+ A reset rebind clears ``task.agent_name`` because the Agent the definition
+ pinned is the one that was just found unusable; authority moves to the session
+ the rebind reserved. But an absent ``agent_name`` is ALSO what "never pinned
+ one" looks like, and ``vibe task update`` re-resolves an omitted Agent for
+ every non-``existing`` policy and writes it back. So a later
+ ``vibe task update <id> --name ...`` -- an edit about the name and nothing else
+ -- silently re-pinned whatever Agent the scope resolved to at that moment, and
+ because the definition's pin outranks the session row at dispatch, every future
+ fire moved onto that Agent (and its system prompt) instead of the session's.
+ The user changes a label and their nightly task quietly changes personality.
+ """
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.base import AgentRequest
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+ from unittest.mock import patch
+
+ from vibe import cli
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.create(name="nightly", backend="claude", model="legacy-model")
+ rebound_agent = agent_store.get_default_agent()
+ assert rebound_agent is not None and rebound_agent.name != "nightly"
+ rebound_agent = agent_store.update(
+ rebound_agent.name, system_prompt=_REBOUND_AGENT_SYSTEM_PROMPT
+ )
+ finally:
+ agent_store.close()
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(agent_name="nightly", model="legacy-model")
+ )
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ name="digest",
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ agent_name="nightly",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # ``/new`` in that channel, then the snapshot's Agent is deleted: the rebind
+ # cannot preserve the settings and resets to the scope/default Agent.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+ agent_store = VibeAgentStore(db_path)
+ try:
+ assert agent_store.remove("nightly")
+ finally:
+ agent_store.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ rebound = ScheduledTaskStore().get_task(task.id)
+ assert rebound is not None
+ assert rebound.session_id and rebound.session_id != pinned
+ assert rebound.agent_name is None
+ assert rebound.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "the reset rebind dropped the Agent pin but recorded nothing durable, so the "
+ "cleared state cannot be told apart from 'the user never pinned an Agent'"
+ )
+
+ def _run_update(*argv: str) -> None:
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, *argv])
+ cli_store = ScheduledTaskStore()
+ cli_agent_store = VibeAgentStore(db_path)
+ try:
+ with (
+ patch("vibe.cli._ensure_config", return_value=None),
+ patch("vibe.cli._task_store", return_value=cli_store),
+ patch("vibe.cli._agent_store", return_value=cli_agent_store),
+ ):
+ assert cli.cmd_task_update(args) == 0, capsys.readouterr().err
+ finally:
+ cli_agent_store.close()
+ capsys.readouterr()
+
+ # The scope's default Agent is then changed -- an ordinary Agent Settings edit,
+ # with no way to know a rebound definition points at the previous default. It
+ # happens BEFORE the unrelated edits below, which is what makes the difference
+ # observable: re-resolving an omitted Agent inside ``task update`` resolves
+ # TODAY's default, not the Agent the rebound session actually carries.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ successor = agent_store.create(
+ name="successor", backend="claude", system_prompt=_SUCCESSOR_AGENT_SYSTEM_PROMPT
+ )
+ agent_store.set_default_agent_name(successor.name)
+ finally:
+ agent_store.close()
+ assert successor.name != rebound_agent.name
+
+ # The REAL update command, on an edit that has nothing to do with the Agent.
+ _run_update("--name", "renamed digest")
+ after_rename = ScheduledTaskStore().get_task(task.id)
+ assert after_rename is not None
+ assert after_rename.name == "renamed digest"
+ assert after_rename.agent_name is None, (
+ f"a --name-only update re-pinned agent_name={after_rename.agent_name!r}; the "
+ "rebound session's Agent no longer governs the definition"
+ )
+ assert after_rename.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "an unrelated update dropped the follow-the-session state"
+ )
+
+ # The next fire must still run as the REBOUND SESSION's Agent, with that
+ # Agent's system prompt -- read through a fresh store, exactly like the next
+ # scheduler tick does.
+ next_fire_task = ScheduledTaskStore().get_task(task.id)
+ assert next_fire_task is not None
+ asyncio.run(
+ service._execute_task(next_fire_task, execution_id="exec-2", disable_one_shot=False)
+ )
+ assert len(dispatched) == 2, "the later fire never reached the backend"
+ later_backend, later_request = dispatched[1]
+ assert isinstance(later_request, AgentRequest), "the captured request is not the production type"
+ assert later_request.vibe_agent_name == rebound_agent.name, (
+ "the fire dispatched under the new scope default instead of the Agent the "
+ "rebound session carries"
+ )
+ assert later_backend == rebound_agent.backend
+ assert later_request.vibe_agent_system_prompt == _REBOUND_AGENT_SYSTEM_PROMPT, (
+ "the turn ran with the new default Agent's instructions while the session "
+ "says it runs as its own Agent"
+ )
+ assert successor.name not in {request.vibe_agent_name for _backend, request in dispatched}
+
+ # A second unrelated edit: the state has to survive repeated edits, not just
+ # the first one.
+ _run_update("--name", "renamed digest again")
+ after_second_rename = ScheduledTaskStore().get_task(task.id)
+ assert after_second_rename is not None
+ assert after_second_rename.agent_name is None, (
+ f"the second update re-pinned agent_name={after_second_rename.agent_name!r} -- "
+ "today's scope default, not the Agent the rebound session actually runs as"
+ )
+ assert after_second_rename.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True
+
+ # An EXPLICIT Agent is the user pinning again: the follow state ends.
+ _run_update("--agent", rebound_agent.name)
+ repinned = ScheduledTaskStore().get_task(task.id)
+ assert repinned is not None
+ assert repinned.agent_name == rebound_agent.name
+ assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in repinned.metadata, (
+ "an explicit --agent must clear the follow-the-session state, otherwise the "
+ "user's new pin is treated as accidental on the next edit"
+ )
+
+
+def test_unrelated_task_update_keeps_the_follow_state_before_the_default_moves(
+ tmp_path: Path, monkeypatch, capsys
+) -> None:
+ """HFR-245 (literal order) — the persisted follow-the-session state is the defect.
+
+ Same regression as ``test_unrelated_task_update_keeps_the_rebound_sessions_agent
+ _authority``, in the order the report describes it: rebind, then an unrelated
+ ``vibe task update --name``, then the scope default moves, then a later fire.
+
+ In THIS order the load-bearing assertion is step 3 -- the persisted state right
+ after the unrelated edit: ``agent_name`` must still be unpinned and the durable
+ follow-the-session marker must still be there. On the pre-fix code the edit
+ re-resolves an omitted Agent and writes back whatever the scope resolves to at
+ that moment, which is the CURRENT default, which is still the very Agent the
+ rebound session carries. So the definition acquires a hard Agent pin whose value
+ happens to be right, and every downstream assertion agrees with reality.
+
+ That is why the dispatch assertions at the end are GUARDS here, not the proof:
+ they only diverge once the default moves AFTER the pin was written, which is the
+ other test's ordering. Read together, the two orderings say the pin must not be
+ created (this test) and must not be honoured over the session if it somehow is
+ (the other one). Neither ordering alone covers both.
+ """
+ from core.vibe_agents import VibeAgentStore
+ from modules.agents.base import AgentRequest
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+ from unittest.mock import patch
+
+ from vibe import cli
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.create(name="nightly", backend="claude", model="legacy-model")
+ rebound_agent = agent_store.get_default_agent()
+ assert rebound_agent is not None and rebound_agent.name != "nightly"
+ rebound_agent = agent_store.update(
+ rebound_agent.name, system_prompt=_REBOUND_AGENT_SYSTEM_PROMPT
+ )
+ finally:
+ agent_store.close()
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(agent_name="nightly", model="legacy-model")
+ )
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ name="digest",
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ agent_name="nightly",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # 1. ``/new`` in that channel, then the snapshot's Agent is deleted: the rebind
+ # cannot preserve the settings, so it resets to the scope/default Agent and
+ # hands Agent authority to the session it just reserved.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+ agent_store = VibeAgentStore(db_path)
+ try:
+ assert agent_store.remove("nightly")
+ finally:
+ agent_store.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ rebound = ScheduledTaskStore().get_task(task.id)
+ assert rebound is not None
+ assert rebound.session_id and rebound.session_id != pinned
+ assert rebound.agent_name is None
+ assert rebound.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "the reset rebind dropped the Agent pin but recorded nothing durable, so the "
+ "cleared state cannot be told apart from 'the user never pinned an Agent'"
+ )
+ rebound_session_id = rebound.session_id
+
+ # 2. An unrelated edit through the REAL command: nothing about the Agent.
+ parser = cli.build_parser()
+ args = parser.parse_args(["task", "update", task.id, "--name", "renamed digest"])
+ cli_store = ScheduledTaskStore()
+ cli_agent_store = VibeAgentStore(db_path)
+ try:
+ with (
+ patch("vibe.cli._ensure_config", return_value=None),
+ patch("vibe.cli._task_store", return_value=cli_store),
+ patch("vibe.cli._agent_store", return_value=cli_agent_store),
+ ):
+ assert cli.cmd_task_update(args) == 0, capsys.readouterr().err
+ finally:
+ cli_agent_store.close()
+ capsys.readouterr()
+
+ # 3. THE load-bearing assertion. Nothing observable has changed yet -- the
+ # default Agent has not moved -- so this is the only place the defect exists
+ # right now. The edit must not have converted "follow the bound Session's
+ # Agent" into a hard pin, however harmless today's resolved value looks.
+ after_rename = ScheduledTaskStore().get_task(task.id)
+ assert after_rename is not None
+ assert after_rename.name == "renamed digest"
+ assert after_rename.agent_name is None, (
+ f"a --name-only update re-pinned agent_name={after_rename.agent_name!r}. It "
+ "equals today's default, so nothing looks wrong yet -- but the definition now "
+ "carries a hard Agent pin that outranks its bound Session at dispatch, and it "
+ "will keep pointing here after the default moves"
+ )
+ assert after_rename.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "an unrelated update dropped the durable follow-the-session state, so the "
+ "next edit cannot tell the cleared Agent from 'never pinned one'"
+ )
+ assert after_rename.session_id == rebound_session_id, (
+ "precondition: the unrelated edit must not have re-bound the Session either"
+ )
+
+ # 4. NOW the scope default moves -- an ordinary Agent Settings edit, with no way
+ # to know a rebound definition points at the previous default.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ successor = agent_store.create(
+ name="successor", backend="claude", system_prompt=_SUCCESSOR_AGENT_SYSTEM_PROMPT
+ )
+ agent_store.set_default_agent_name(successor.name)
+ finally:
+ agent_store.close()
+ assert successor.name != rebound_agent.name
+
+ # 5. Guards, not the proof (see the docstring): a later real fire must still run
+ # as the REBOUND SESSION's Agent, with that Agent's system prompt -- read
+ # through a fresh store, exactly like the next scheduler tick does.
+ next_fire_task = ScheduledTaskStore().get_task(task.id)
+ assert next_fire_task is not None
+ asyncio.run(
+ service._execute_task(next_fire_task, execution_id="exec-2", disable_one_shot=False)
+ )
+ assert len(dispatched) == 2, "the later fire never reached the backend"
+ later_backend, later_request = dispatched[1]
+ assert isinstance(later_request, AgentRequest), "the captured request is not the production type"
+ assert later_request.vibe_agent_name == rebound_agent.name, (
+ "the fire dispatched under the new scope default instead of the Agent the "
+ "rebound session carries"
+ )
+ assert later_backend == rebound_agent.backend
+ assert later_request.vibe_agent_system_prompt == _REBOUND_AGENT_SYSTEM_PROMPT, (
+ "the turn ran with the new default Agent's instructions while the session "
+ "says it runs as its own Agent"
+ )
+ assert successor.name not in {request.vibe_agent_name for _backend, request in dispatched}
+
+
+#: The Agent the bound watch Session runs as. Distinctive so "the session's Agent
+#: reached the request" cannot pass on a None == None comparison.
+_WATCH_SESSION_AGENT_SYSTEM_PROMPT = "You are the watch session's Agent. Answer tersely."
+
+
+def test_unrelated_watch_update_keeps_the_follow_session_agent_authority(
+ tmp_path: Path, monkeypatch, capsys
+) -> None:
+ """HFR-256 — ``vibe watch update`` had no follow-the-session logic at all.
+
+ ``vibe task update`` keeps three durable Agent-authority states (HFR-245..247,
+ HFR-255): ``--clear-agent`` (or an already-rebound definition) hands Agent
+ authority to the bound Session and records it durably; an unrelated edit
+ preserves that; an explicit ``--agent`` ends it. ``cmd_watch_update`` is the
+ sibling definition command over the same ``run_definitions`` rows and had NONE
+ of it: ``--clear-agent`` / ``--agent`` were a silent ``if``/``elif``, and the
+ command then ran the same ``agent_name is None and session_policy != 'existing'``
+ re-resolution, writing today's scope / default Agent straight back as a HARD PIN.
+ So ``--clear-agent`` was silently undone, and any unrelated edit re-pinned a
+ watch whose Agent authority belonged to its Session.
+
+ The proof is NOT the CLI payload. After the unrelated edit the scope default is
+ moved and the watch is FIRED through its production path -- the real
+ ``ManagedWatchService._run_watch`` reads the STORED definition, ``_enqueue_hook``
+ turns it into a queued ``watch`` request carrying ``agent_name``, and the real
+ ``ScheduledTaskService`` claim/execute path hands it to the real
+ ``MessageHandler``. The assertions are on the ``AgentRequest`` that handler built,
+ i.e. the Agent identity, backend and system prompt the turn actually runs as.
+ Only the waiter subprocess is stubbed (its stdout has no bearing on Agent
+ identity).
+ """
+ from unittest.mock import patch
+
+ from core.vibe_agents import VibeAgentStore
+ from core.watches import (
+ ManagedWatchService,
+ ManagedWatchStore,
+ WatchRuntimeStateStore,
+ _CycleResult,
+ )
+ from modules.agents.base import AgentRequest
+
+ from vibe import cli
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ # The Agent the bound Session runs as ("claude"), and a DIFFERENT current default
+ # ("codex"). The gap between them is what makes a re-pin observable at all.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ session_agent = agent_store.update("claude", system_prompt=_WATCH_SESSION_AGENT_SYSTEM_PROMPT)
+ original_default = agent_store.get_default_agent()
+ assert original_default is not None and original_default.name != session_agent.name
+ finally:
+ agent_store.close()
+
+ # The Session a ``create_once`` definition reserves, through the production
+ # helper ``vibe watch add --create-session`` uses -- so the row carries its own
+ # Agent identity exactly as a real one does.
+ with patch("vibe.cli._ensure_config", return_value=None):
+ pinned = cli._reserve_definition_session(
+ agent_name=session_agent.name,
+ deliver_key="slack::channel::C123",
+ help_command="vibe watch add --help",
+ )
+ assert resolve_session_id_target(pinned).agent_name == session_agent.name
+
+ watch = ManagedWatchStore().add_watch(
+ name="ci watch",
+ session_key="",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix="CI finished.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key="slack::channel::C123",
+ session_id=pinned,
+ agent_name=session_agent.name,
+ session_policy="create_once",
+ message="CI finished.",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ def _run_update(*argv: str) -> None:
+ """The REAL ``vibe watch update`` command, on a fresh store each time."""
+ parser = cli.build_parser()
+ args = parser.parse_args(["watch", "update", watch.id, *argv])
+ cli_agent_store = VibeAgentStore(db_path)
+ try:
+ with (
+ patch("vibe.cli._ensure_config", return_value=None),
+ patch("vibe.cli._watch_store", return_value=ManagedWatchStore()),
+ patch("vibe.cli._agent_store", return_value=cli_agent_store),
+ ):
+ assert cli.cmd_watch_update(args) == 0, capsys.readouterr().err
+ finally:
+ cli_agent_store.close()
+ capsys.readouterr()
+
+ def _fire_watch(execution_label: str) -> None:
+ """Fire the watch through its PRODUCTION path, reading the stored definition.
+
+ A fresh ``ManagedWatchStore`` / ``ManagedWatchService`` per fire, exactly like
+ the next service tick. Only ``_run_cycle`` (the waiter subprocess) is stubbed.
+ """
+ fire_store = ManagedWatchStore()
+ fire_store.set_enabled(watch.id, True)
+ watch_service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=fire_store,
+ request_store=service.request_store,
+ runtime_store=WatchRuntimeStateStore(),
+ )
+ watch_service._running = True
+ watch_service._requires_service_lease = False
+
+ async def _fake_cycle(*_args, **_kwargs):
+ return _CycleResult(exit_code=0, stdout=f"ci is green ({execution_label})", stderr="", timed_out=False)
+
+ watch_service._run_cycle = _fake_cycle # type: ignore[method-assign]
+ asyncio.run(watch_service._run_watch(watch.id))
+
+ pending = [item for item in service.request_store.list_pending() if item.task_id == watch.id]
+ assert len(pending) == 1, f"the watch fire enqueued {len(pending)} request(s), expected exactly one"
+ assert pending[0].request_type == "watch"
+ claimed = service.request_store.claim(pending[0].id)
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ service = _dispatching_binding_service(tmp_path, ScheduledTaskStore(), db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+
+ # 1. ``--clear-agent`` hands Agent authority back to the bound Session. Both
+ # halves are load-bearing: the cleared pin, and the DURABLE record of why it
+ # is cleared -- without the marker the state cannot be told apart from "the
+ # user never pinned an Agent", which is what the re-resolution acts on.
+ _run_update("--clear-agent")
+ after_clear = ManagedWatchStore().get_watch(watch.id)
+ assert after_clear is not None
+ assert after_clear.agent_name is None, (
+ f"--clear-agent was silently undone: the command re-resolved and re-pinned "
+ f"agent_name={after_clear.agent_name!r} (today's scope/default Agent), so the "
+ "bound Session never gets Agent authority"
+ )
+ assert after_clear.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "--clear-agent recorded nothing durable, so the next unrelated edit cannot "
+ "tell the cleared Agent from 'never pinned one' and will re-pin it"
+ )
+
+ # 2. An unrelated edit -- nothing about the Agent -- must preserve BOTH.
+ _run_update("--name", "renamed ci watch")
+ after_rename = ManagedWatchStore().get_watch(watch.id)
+ assert after_rename is not None
+ assert after_rename.name == "renamed ci watch"
+ assert after_rename.agent_name is None, (
+ f"a --name-only update re-pinned agent_name={after_rename.agent_name!r}; the "
+ "bound Session's Agent no longer governs the watch"
+ )
+ assert after_rename.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True, (
+ "an unrelated update dropped the durable follow-the-session state"
+ )
+ assert after_rename.session_id == pinned, (
+ "precondition: the unrelated edit must not have re-bound the Session either"
+ )
+
+ # 3. The scope default now MOVES -- an ordinary Agent Settings edit, with no way
+ # to know a watch points at the previous default. This is what makes the pin
+ # the earlier edits would have written observably wrong, and it happens before
+ # one more unrelated edit so the wrong value is the one that gets written.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ successor = agent_store.create(
+ name="successor", backend="claude", system_prompt=_SUCCESSOR_AGENT_SYSTEM_PROMPT
+ )
+ agent_store.set_default_agent_name(successor.name)
+ finally:
+ agent_store.close()
+ assert successor.name != session_agent.name
+
+ _run_update("--name", "renamed ci watch again")
+ after_second_rename = ManagedWatchStore().get_watch(watch.id)
+ assert after_second_rename is not None
+ assert after_second_rename.agent_name is None, (
+ f"the second update re-pinned agent_name={after_second_rename.agent_name!r} -- "
+ "today's default, not the Agent the bound Session actually runs as"
+ )
+ assert after_second_rename.metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY) is True
+
+ # 4. THE PROOF: fire the watch for real. The Agent identity the turn runs as is
+ # re-derived inside the real ``MessageHandler``, strictly downstream of the
+ # stored definition and of anything the CLI printed.
+ _fire_watch("first")
+ assert len(dispatched) == 1, "the watch fire never reached the backend"
+ backend, request = dispatched[0]
+ assert isinstance(request, AgentRequest), "the captured request is not the production type"
+ assert request.vibe_agent_name == session_agent.name, (
+ f"the watch hook dispatched as {request.vibe_agent_name!r} instead of the Agent "
+ "the bound Session carries -- the stored definition carries a pin the unrelated "
+ "edit wrote, and that pin outranks the Session row at dispatch"
+ )
+ assert backend == session_agent.backend
+ assert request.vibe_agent_system_prompt == _WATCH_SESSION_AGENT_SYSTEM_PROMPT, (
+ "the turn ran with another Agent's instructions while the Session says it runs "
+ "as its own Agent"
+ )
+ assert successor.name not in {item.vibe_agent_name for _backend, item in dispatched}
+
+ # 5. An EXPLICIT ``--agent`` is the user pinning again: the follow state ends.
+ # The state is seeded straight onto the stored row first, so this step tests
+ # the EXIT independently of how the definition entered the state -- a reset
+ # rebind writes exactly this shape onto a create_once definition.
+ seed_store = ManagedWatchStore()
+ seeded = seed_store.get_watch(watch.id)
+ assert seeded is not None
+ seeded.agent_name = None
+ seeded.metadata = {**(seeded.metadata or {}), BINDING_FOLLOWS_SESSION_METADATA_KEY: True}
+ seed_store.upsert_watch(seeded)
+
+ _run_update("--agent", session_agent.name)
+ repinned = ManagedWatchStore().get_watch(watch.id)
+ assert repinned is not None
+ assert repinned.agent_name == session_agent.name
+ assert BINDING_FOLLOWS_SESSION_METADATA_KEY not in repinned.metadata, (
+ "an explicit --agent must clear the follow-the-session state, otherwise the "
+ "user's new pin is treated as accidental on the next edit"
+ )
+
+ # A guard, not the proof: with the pin restored the fire must still run as that
+ # Agent and never as the new default. It agrees with the follow-the-session
+ # reading here (the pin names the Session's own Agent, which is the only value
+ # ``_resolve_agent_for_target`` accepts for a Session-bound definition), so it
+ # cannot by itself distinguish pin from follow -- the durable assertions above do.
+ _fire_watch("second")
+ assert len(dispatched) == 2, "the later fire never reached the backend"
+ later_backend, later_request = dispatched[1]
+ assert isinstance(later_request, AgentRequest)
+ assert later_request.vibe_agent_name == session_agent.name
+ assert later_backend == session_agent.backend
+ assert later_request.vibe_agent_system_prompt == _WATCH_SESSION_AGENT_SYSTEM_PROMPT
+
+
+def _reclaim_now(session_id: str, *, mode: str, reason: str) -> dict[str, int]:
+ """Run the shared teardown reclaim against the isolated state database."""
+ from storage.session_reclaim import reclaim_bound_definitions
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return reclaim_bound_definitions(conn, session_id, mode=mode, reason=reason)
+ finally:
+ engine.dispose()
+
+
+def _bare_session_row(*, workdir: Path, anchor: str) -> str:
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return create_agent_session_row(
+ conn,
+ scope_id=None,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ model="gpt-5.5-codex",
+ native_session_id="codex-native",
+ workdir=str(workdir),
+ require_workdir=False,
+ )
+ finally:
+ engine.dispose()
+
+
+def _stored_definition_row(definition_id: str) -> dict[str, Any]:
+ from storage.models import run_definitions
+
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ row = (
+ conn.execute(select(run_definitions).where(run_definitions.c.id == definition_id))
+ .mappings()
+ .first()
+ )
+ finally:
+ engine.dispose()
+ assert row is not None
+ return dict(row)
+
+
+def test_task_result_stamp_cannot_resurrect_a_definition_the_archive_deleted(tmp_path: Path) -> None:
+ """HFR-261, ``deleted_at`` half — nothing in memory even carries the column.
+
+ THE PRODUCTION STORY. A one-shot task fires. While its run is in flight the user
+ archives the bound Session, and ``reclaim_bound_definitions(mode='delete')``
+ soft-deletes the definition: archive is terminal, so a paused definition could
+ otherwise be re-enabled onto a dead session later. The run then finishes and the
+ scheduler stamps its result.
+
+ THE DEFECT IS THE COLUMN THAT IS NOT THERE. ``ScheduledTask`` has no
+ ``deleted_at`` field at all -- the store only ever lists live rows -- so
+ ``_scheduled_task_values`` wrote ``deleted_at=NULL`` unconditionally. A run-result
+ stamp keyed on ``id`` alone therefore UN-DELETED the definition, restored its
+ ``enabled`` switch and replaced the reclaim's settings snapshot: the task came back
+ from an archive the user confirmed, in a list the archive dialog had already
+ reported as cleaned up.
+
+ ``mark_task_result`` is a best-effort runtime stamp, so the refusal is reported by
+ its return value (its caller already treats ``False`` as "nothing recorded")
+ rather than by an exception through the fire path.
+ """
+ from storage.session_reclaim import RECLAIM_DELETE, SESSION_SETTINGS_SNAPSHOT_KEY
+
+ store = ScheduledTaskStore()
+ session_id = _bare_session_row(workdir=tmp_path, anchor="slack_C1")
+ task = store.add_task(
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ prompt="run once",
+ schedule_type="at",
+ run_at="2026-07-28T09:00:00+00:00",
+ timezone_name="UTC",
+ metadata={"origin": "cli"},
+ )
+
+ summary = _reclaim_now(session_id, mode=RECLAIM_DELETE, reason="the session was archived")
+ assert summary == {"paused": 0, "deleted": 1, "snapshotted": 1}, (
+ f"the archive reclaim itself did not land ({summary!r})"
+ )
+
+ # The in-flight run finishing, from the mirror the fire was decided from.
+ recorded = store.mark_task_result(task.id, error=None)
+
+ row = _stored_definition_row(task.id)
+ assert row["deleted_at"] is not None, (
+ "the run-result stamp resurrected a definition the archive soft-deleted; it is "
+ "back in every task list, bound to a session the user archived"
+ )
+ assert row["last_run_at"] is None, (
+ "the refused write partially landed — a lost compare-and-set must change "
+ "NOTHING, not just the guarded columns"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert SESSION_SETTINGS_SNAPSHOT_KEY in stored_metadata, (
+ "the stale write replaced the reclaim's settings snapshot with the "
+ "pre-teardown metadata"
+ )
+ assert recorded is False, (
+ "the store reported the run result as recorded while the write was refused; a "
+ "lost write must be reported to nobody"
+ )
+ assert ScheduledTaskStore().get_task(task.id) is None, (
+ "the deleted definition is being served again"
+ )
+ # HFR-271's rule: the fresh store above cannot see the mirror ``store`` mutated
+ # before the refusal, and that mirror is what ``reconcile_jobs`` schedules from.
+ assert store.get_task(task.id) is None, (
+ "the live store still serves the definition the archive deleted, so the "
+ "scheduler keeps firing it until the process restarts"
+ )
+
+
+def test_cycle_result_cannot_restore_the_metadata_a_snapshot_refresh_replaced(tmp_path: Path) -> None:
+ """HFR-261, snapshot-marker half — the reclaim shape the other guards miss.
+
+ THE THIRD RECLAIM SHAPE. For a definition that is ALREADY paused,
+ ``reclaim_bound_definitions(mode='pause')`` changes neither ``enabled`` nor
+ ``deleted_at`` nor ``session_id``: it only refreshes
+ ``session_settings_snapshot``, because that snapshot is the ONLY copy of the dying
+ session's workdir / agent / model and a later ``create_once`` rebind reads it to
+ carry them forward (D3). So the three lifecycle predicates all match, and a stale
+ full-row write would still restore the pre-teardown metadata and send the
+ definition back on the wrong route.
+
+ That is why the guard also re-asserts the snapshot's ``captured_at``: it is the
+ state this reclaim actually owns. Driven here through ``mark_cycle_result`` -- a
+ cycle landing after a manual pause, which the store explicitly supports -- so the
+ proof does not depend on the CLI.
+ """
+ from core.watches import ManagedWatchStore
+ from storage.session_reclaim import RECLAIM_PAUSE, SESSION_SETTINGS_SNAPSHOT_KEY
+
+ store = ManagedWatchStore()
+ session_id = _bare_session_row(workdir=tmp_path, anchor="slack_C2")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ metadata={"origin": "cli"},
+ )
+ store.set_enabled(watch.id, False)
+
+ summary = _reclaim_now(session_id, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared")
+ assert summary == {"paused": 0, "deleted": 0, "snapshotted": 1}, (
+ f"this test needs the SNAPSHOT-ONLY reclaim shape, and got {summary!r}: an "
+ "already-paused definition is neither paused again nor deleted"
+ )
+ reclaimed_snapshot = json.loads(_stored_definition_row(watch.id)["metadata_json"])[
+ SESSION_SETTINGS_SNAPSHOT_KEY
+ ]
+
+ recorded = store.mark_cycle_result(watch.id, exit_code=0, error=None, event_detected=True)
+
+ stored_metadata = json.loads(_stored_definition_row(watch.id)["metadata_json"] or "{}")
+ assert stored_metadata.get(SESSION_SETTINGS_SNAPSHOT_KEY) == reclaimed_snapshot, (
+ "the stale cycle-result write restored the pre-teardown metadata over the "
+ "reclaim's settings snapshot; that snapshot is the only record of the dying "
+ "session's workdir/agent/model, so a later create_once rebind would resolve "
+ f"today's defaults instead. Stored: {stored_metadata!r}"
+ )
+ assert recorded is False, (
+ "the store reported the cycle result as recorded while the write was refused"
+ )
+ # HFR-271's rule: ``store`` is the object that mutated its cached ManagedWatch before
+ # the refusal, so a refusal is only proven once IT agrees with the row above.
+ live = store.get_watch(watch.id)
+ assert live is not None and live.metadata.get(SESSION_SETTINGS_SNAPSHOT_KEY) == reclaimed_snapshot, (
+ "the write was refused and the live store kept the pre-teardown metadata: "
+ f"{None if live is None else live.metadata!r}"
+ )
+
+
+#: The ``existing`` probe ``_upsert_definition`` runs before its guarded UPDATE.
+#: Committing the competing teardown when THIS read completes puts it exactly
+#: inside the window the guard exists for: after the caller decided what to write,
+#: before the write takes the lock.
+_DEFINITION_EXISTS_SELECT = (
+ "SELECT run_definitions.id FROM run_definitions WHERE run_definitions.id = ? LIMIT ? OFFSET ?"
+)
+
+
+def _commit_reclaim_after(engine, session_id: str, *, read: str, mode: str, reason: str) -> dict:
+ """Commit the REAL teardown reclaim from a genuinely separate connection.
+
+ The task-side twin of ``_commit_competing_bind_after`` in
+ ``tests/test_sqlite_sessions_store.py``: hooks ``after_cursor_execute`` on the
+ engine the code under test uses, and when ``read`` completes opens its own
+ engine, runs ``reclaim_bound_definitions`` and COMMITS. Control returns to the
+ caller mid-write, so its next statement runs against a database another writer
+ has already changed. Fires once; the returned dict records it, so a rendered-SQL
+ drift shows up as "never raced" instead of a vacuous pass.
+ """
+ from sqlalchemy import event
+
+ from storage.session_reclaim import reclaim_bound_definitions
+
+ state: dict = {"fired": 0, "summary": None}
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != read:
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with other.begin() as other_conn:
+ state["summary"] = reclaim_bound_definitions(
+ other_conn, session_id, mode=mode, reason=reason
+ )
+ finally:
+ other.dispose()
+
+ return state
+
+
+def _scheduled_service_with_ledger(
+ tmp_path: Path, store: ScheduledTaskStore, calls: list
+) -> ScheduledTaskService:
+ """``_binding_service``, but on the SQLite request store — the real run ledger.
+
+ ``_binding_service`` uses a file-backed ``TaskExecutionStore``; the run ledger
+ HFR-264 is about is ``agent_runs``, which only the SQLite backend writes, and
+ ``get_run`` is how the CLI and the Harness read a run's terminal state.
+ """
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ calls.append(message)
+ return None
+
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_kw: None))
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=store,
+ request_store=TaskExecutionStore(),
+ )
+ service.scheduler = _StubScheduler()
+ return service
+
+
+def test_a_refused_result_stamp_cannot_complete_the_run_ok(tmp_path: Path, monkeypatch) -> None:
+ """HFR-264 — the consuming end of ``mark_task_result``'s refusal.
+
+ THE PRODUCTION STORY. A one-shot task fires and its turn succeeds. While the run
+ is in flight the user archives the bound Session, and
+ ``reclaim_bound_definitions(mode='delete')`` soft-deletes the definition. The fire
+ then stamps its terminal result from the pre-teardown mirror, and HFR-261's guard
+ correctly REFUSES it — ``last_run_at``, ``last_error`` and the one-shot disable are
+ not stored.
+
+ THE DEFECT WAS DOWNSTREAM OF THE GUARD. ``_execute_task`` discarded that ``False``
+ and returned a ``TaskExecutionResult`` with ``error=None``, so
+ ``_execute_claimed_request`` completed the run ``ok=True``: the database refused
+ the stale stamp and BOTH the caller and the run ledger reported success. The user
+ sees a green run for a task whose stored state never moved, and an ``at`` task that
+ was never disabled can fire again.
+
+ Driven through the REAL claimed-request path with the archive committed from a
+ second connection INSIDE the write window, and asserted on the run ledger
+ ``agent_runs`` row — which is what ``vibe task runs`` and the Harness detail pane
+ read.
+ """
+ from storage.session_reclaim import RECLAIM_DELETE
+
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None, "this test needs the SQLite-backed store; the guard lives there"
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ session_id = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert session_id is not None
+ task = store.add_task(
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-07-28T09:00:00+00:00",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"origin": "cli"},
+ )
+
+ calls: list = []
+ service = _scheduled_service_with_ledger(tmp_path, store, calls)
+ queued = service.request_store.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ claimed = service.request_store.claim(queued.id)
+ assert claimed is not None
+
+ race = _commit_reclaim_after(
+ store._sqlite.engine,
+ session_id,
+ read=_DEFINITION_EXISTS_SELECT,
+ mode=RECLAIM_DELETE,
+ reason="the session was archived",
+ )
+
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ assert race["fired"] == 1, (
+ "the competing archive never landed inside the write window, so this test "
+ "proved nothing; the rendered SQL of the guarded upsert's existence probe drifted"
+ )
+ assert race["summary"] == {"paused": 0, "deleted": 1, "snapshotted": 1}, (
+ f"the archive reclaim itself did not land ({race['summary']!r})"
+ )
+ assert calls, "the turn never ran, so this is not the success-shaped fire under test"
+
+ run = service.request_store.get_run(queued.id)
+ assert run is not None
+ assert run["status"] == "failed", (
+ "the run ledger recorded a success for a fire whose terminal stamp the "
+ f"database refused (status={run['status']!r}); the stored task never moved"
+ )
+ from core.scheduled_tasks import _TASK_RESULT_NOT_RECORDED_ERROR
+
+ assert run["error"] == _TASK_RESULT_NOT_RECORDED_ERROR, (
+ f"the refusal reached the ledger without saying why: {run['error']!r}"
+ )
+
+ row = _stored_definition_row(task.id)
+ assert row["deleted_at"] is not None, (
+ "the result stamp resurrected a definition the archive soft-deleted"
+ )
+ assert row["last_run_at"] is None and row["last_error"] is None, (
+ "the refused write partially landed — a lost compare-and-set must change NOTHING"
+ )
+
+
+def test_a_refused_recovery_record_does_not_notify_a_transition_it_cannot_dedup(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-266 — ``record_binding_recovery``'s refusal was discarded too.
+
+ ``_emit_binding_change`` promises "once per binding transition, never once per
+ fire", and the ONLY thing that makes it once is the durable
+ ``metadata.binding_recovery`` marker it writes first. That write is guarded
+ (HFR-261) and refuses when the definition was reclaimed, repointed or removed in
+ the window — and its ``False`` was ignored, so the notice went out with nothing
+ behind it: a daily cron re-notifies every day, about a recovery the stored
+ definition no longer reflects.
+ """
+ from storage.session_reclaim import RECLAIM_DELETE
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None
+ session_id = _bare_session_row(workdir=tmp_path, anchor="slack_C123")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"origin": "cli"},
+ )
+ # Bind it to the real session AFTER creation so the reclaim below has a row to
+ # reclaim, without the fire being able to resolve it.
+ with create_sqlite_engine(paths.get_sqlite_state_path()).begin() as conn:
+ conn.execute(
+ update(run_definitions).where(run_definitions.c.id == task.id).values(session_id=session_id)
+ )
+ store.load()
+
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ notices = _spy_binding_notices(service)
+ change = SessionBindingChange(
+ action="paused",
+ task_id=task.id,
+ reason="missing",
+ previous_session_id=session_id,
+ detail="paused: the bound agent session no longer exists.",
+ )
+
+ race = _commit_reclaim_after(
+ store._sqlite.engine,
+ session_id,
+ read=_DEFINITION_EXISTS_SELECT,
+ mode=RECLAIM_DELETE,
+ reason="the session was archived",
+ )
+
+ asyncio.run(service._emit_binding_change(change))
+
+ assert race["fired"] == 1, "the competing archive never landed inside the write window"
+ assert notices == [], (
+ "a binding-change notice was delivered while its dedup marker was refused; "
+ "'once per transition' becomes once per fire, forever"
+ )
+ row = _stored_definition_row(task.id)
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert BINDING_RECOVERY_METADATA_KEY not in stored_metadata, (
+ "the refused write partially landed"
+ )
+
+
+def test_rebind_propagates_an_operational_fault_instead_of_resetting_the_route(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-265 — a transient fault must not be read as "that Agent is gone".
+
+ THE FALLBACK'S JOB (HFR-243) is narrow: the snapshot names an Agent the user has
+ since deleted or disabled, so the reset attempt degrades to scope defaults and
+ says so. It decided that from a BROAD ``except Exception``, which cannot tell a
+ settled catalog fact from SQLite contention, a migration failure or a filesystem
+ error. On any of those the retry SUCCEEDED against scope defaults,
+ ``_persist_task_session_id`` wrote the reset route, ``agent_name`` was dropped and
+ ``binding_follows_session`` was stamped — so a momentary database fault
+ PERMANENTLY cost the task the Agent and model the snapshot was holding for it,
+ under a notice claiming the settings "could not be recovered".
+
+ The condition now has a type (``AgentUnavailableError``) raised by the
+ Agent-resolution layer and caught narrowly. Everything else propagates, with the
+ definition's route and lifecycle untouched and NO fallback reservation.
+ """
+ import sqlite3
+
+ from sqlalchemy.exc import OperationalError
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.create(name="nightly", backend="claude", model="legacy-model")
+ finally:
+ agent_store.close()
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor="slack_C123:definition_abc",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned is not None
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned)
+ .values(agent_name="nightly", model="legacy-model")
+ )
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ agent_name="nightly",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new` deletes the session row and writes the settings snapshot the preserved
+ # rebind reads.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ before = _stored_definition_row(task.id)
+
+ calls: list = []
+ service = _scheduled_service_with_ledger(tmp_path, store, [])
+ notices = _spy_binding_notices(service)
+ original_reserve = service._reserve_runtime_session
+
+ def _reserve(**kwargs):
+ calls.append(kwargs)
+ return original_reserve(**kwargs)
+
+ service._reserve_runtime_session = _reserve # type: ignore[method-assign]
+
+ # THE OPERATIONAL FAULT, at the Agent-resolution layer the real rebind reaches.
+ def _contended(self, name): # noqa: ANN001
+ raise OperationalError("SELECT agents.id ...", {}, sqlite3.OperationalError("database is locked"))
+
+ monkeypatch.setattr(VibeAgentStore, "require_enabled", _contended)
+
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None
+ assert reloaded.metadata.get("session_settings_snapshot"), "reclaim wrote no settings snapshot"
+
+ with pytest.raises(OperationalError):
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ assert len(calls) == 1, (
+ f"the reset attempt ran after an operational fault ({len(calls)} reservations); "
+ "a transient error was treated as a deleted Agent and the task's route was reset"
+ )
+ assert calls[0]["agent_name"] == "nightly", "the ONE attempt was not the preserving one"
+
+ after = _stored_definition_row(task.id)
+ assert after["session_id"] == before["session_id"], (
+ "the definition was repointed after an operational fault; the snapshot it "
+ "needed for a later preserved rebind is gone with it"
+ )
+ assert after["agent_name"] == "nightly", (
+ "the definition lost its Agent pin to a transient database error"
+ )
+ assert after["enabled"] == before["enabled"], "the lifecycle moved on an operational fault"
+ assert after["metadata_json"] == before["metadata_json"], (
+ "the definition's durable metadata changed — a reset rebind stamped "
+ "binding_follows_session, or the snapshot was replaced"
+ )
+ assert notices == [], "an operational fault was reported to the user as a binding recovery"
+
+
+def test_agent_resolution_types_the_deleted_or_disabled_condition(tmp_path: Path, monkeypatch) -> None:
+ """HFR-265, the contract half — the type the narrow catch is written against.
+
+ The rebind fallback must degrade for exactly two facts (the Agent was deleted, the
+ Agent was disabled) and for nothing else. Inferring them from ``except Exception``
+ is what let an infrastructure fault cost a task its route, so the Agent-resolution
+ layer now says which it is. ``AgentUnavailableError`` subclasses ``ValueError`` and
+ keeps the old messages, so every existing ``except ValueError`` caller — the CLI,
+ the UI server, the controller's route resolution — is unchanged.
+ """
+ from core.vibe_agents import AgentUnavailableError, VibeAgentStore
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+ agent_store = VibeAgentStore(db_path)
+ try:
+ agent_store.create(name="nightly", backend="claude", enabled=False)
+ with pytest.raises(AgentUnavailableError) as missing:
+ agent_store.require_enabled("does-not-exist")
+ with pytest.raises(AgentUnavailableError) as disabled:
+ agent_store.require_enabled("nightly")
+ finally:
+ agent_store.close()
+
+ assert missing.value.reason == "missing"
+ assert missing.value.agent_name == "does-not-exist"
+ assert str(missing.value) == "agent 'does-not-exist' not found"
+ assert disabled.value.reason == "disabled"
+ assert disabled.value.agent_name == "nightly"
+ assert str(disabled.value) == "agent 'nightly' is disabled"
+ assert isinstance(missing.value, ValueError) and isinstance(disabled.value, ValueError), (
+ "the typed contract must stay a ValueError, or every existing caller changes behaviour"
+ )
+
+
+def test_execute_task_does_not_dispatch_when_the_rebind_persist_is_refused(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-268 — a rebind the guard refused must not fire the turn it was for.
+
+ THE PRODUCTION STORY. A ``create_once`` task is pinned to a Session. ``/new``
+ deletes that session, the reclaim pauses the task and writes its settings
+ snapshot, the user resumes it, and the schedule fires. The fire finds the pinned
+ session unresolvable, so ``_recover_pinned_session_binding`` reserves a
+ replacement and persists the rebind. While that is happening a SECOND teardown
+ lands — another ``/new``, or the archive dialog — and pauses the definition again.
+
+ THE GUARD WAS ASKED, AND ITS ANSWER WAS DROPPED. ``_write_task`` is guarded
+ (HFR-261) and correctly refuses to restore the binding and the enabled state the
+ teardown just cleared. But ``_persist_task_session_id`` swallowed the
+ ``DefinitionWriteConflict`` and returned ``None``, so ``action`` stayed
+ ``"rebound"`` and ``_execute_task`` went on to run the prompt and post the reply
+ into the freshly reserved session — a real agent turn, delivered to the user's
+ channel, for a definition the database had just torn down. Same class as HFR-267:
+ the effect outlived the refusal. The refusal also covers the soft-delete shape
+ (``expect.deleted_at`` is ``None``), so "the rebind stands for THIS fire only"
+ was not a safe reading of it.
+
+ Driven through the REAL ``_execute_task`` with the REAL production dispatch path
+ attached, and the competing reclaim committed from a genuinely separate engine.
+ """
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr268",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new`: the session row goes, the reclaim pauses the task and snapshots its
+ # settings so a rebind can preserve them.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ # The user resumes it and the schedule fires. THIS is the read the fire acts
+ # from; nothing reloads it again before the rebind is written.
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None and reloaded.enabled is True
+ assert reloaded.metadata.get("session_settings_snapshot"), "the reclaim wrote no settings snapshot"
+
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ notices = _spy_binding_notices(service)
+
+ # THE COMPETING TEARDOWN, committed from its own engine after that read.
+ reason = "the bound agent session was cleared"
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ summary = reclaim_bound_definitions(conn, pinned, mode=RECLAIM_PAUSE, reason=reason)
+ finally:
+ engine.dispose()
+ assert summary["paused"] == 1, f"the competing teardown never landed ({summary!r}), so this test proves nothing"
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ assert dispatched == [], (
+ "the fire dispatched an agent turn on a rebind the store REFUSED; the prompt "
+ "runs and its reply is posted for a definition the teardown just paused"
+ )
+
+ stored = ScheduledTaskStore().get_task(task.id)
+ assert stored is not None
+ assert stored.session_id == pinned, (
+ "the refused rebind was stored anyway, overwriting the binding the teardown cleared"
+ )
+ assert stored.enabled is False, "the refused rebind re-enabled the definition the teardown paused"
+ assert [notice.action for notice in notices] == ["reclaimed"], (
+ f"the user was notified of a rebind that was never stored: {[n.action for n in notices]}"
+ )
+ assert "not rebound" in (notices[0].detail or ""), (
+ f"the notice does not say the rebind was refused: {notices[0].detail!r}"
+ )
+ assert stored.last_error and "not rebound" in stored.last_error, (
+ f"the durable error does not record the refused rebind: {stored.last_error!r}"
+ )
+
+
+def _spy_reserved_sessions(service: ScheduledTaskService) -> list[str]:
+ """Record every session id ``_reserve_runtime_session`` actually handed back.
+
+ The id is the only handle on the row the reservation created: it is random, it is
+ never written to the definition on the refused path, and diffing the table would
+ also catch rows a concurrent writer created. Spying on the return value names
+ exactly the row THIS call is responsible for.
+ """
+
+ reserved: list[str] = []
+ original = service._reserve_runtime_session
+
+ def _spy(**kwargs):
+ session_id = original(**kwargs)
+ reserved.append(session_id)
+ return session_id
+
+ service._reserve_runtime_session = _spy # type: ignore[method-assign]
+ return reserved
+
+
[email protected]("placement", ["scoped", "standalone"])
+def test_a_refused_rebind_reclaims_the_session_and_workspace_it_reserved(
+ tmp_path: Path, monkeypatch, placement: str
+) -> None:
+ """HFR-270 — a rebind the guard refused must not leave its replacement behind.
+
+ THE PRODUCTION STORY, one step past HFR-268. The same race: a ``create_once``
+ definition's pinned session is gone, the fire reserves a replacement, and a second
+ teardown pauses the definition before the rebind can be stored. HFR-268 made the
+ refusal stop the dispatch. It did not undo the reservation.
+
+ ``_rebind_create_once_session`` COMMITS the replacement row before
+ ``_persist_task_session_id`` is ever called -- a separate service, a separate
+ transaction, and for the standalone placement a ``mkdir`` of a Show Page workspace
+ as well. When the guard then refuses, nothing points at that row: the definition
+ still names the session the teardown cleared, the notice says "not rebound", and
+ the row survives as a live, unreferenced background session, with its workspace, for
+ as long as the database does. Every subsequent fire that loses the same race leaks
+ another one.
+
+ Two placements because the reservation has two shapes and only one of them creates
+ a directory: a definition whose deliver key resolves to a Scope reserves inside that
+ Scope and INHERITS a shared workdir (which the reclaim must NOT delete -- it belongs
+ to the Scope, not to this row), while one whose deliver key names no Scope reserves
+ standalone and gets a Show Page workspace of its own (which the reclaim MUST remove,
+ because this reservation is the only thing that ever created it).
+
+ The concurrent winner in the fixture is the load-bearing negative: a reclaim written
+ as "delete the background sessions that nothing references" would take it too. Only
+ the row this call created may go.
+ """
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ if placement == "scoped":
+ deliver_key = "slack::channel::C123"
+ task_metadata: dict = {"session_scope_id": "slack::channel::C123"}
+ else:
+ # A deliver key that names no Scope: neither ``parse_scope_id`` nor
+ # ``parse_session_key`` accepts it, so the reservation goes down the
+ # standalone branch and mkdirs a Show Page workspace of its own.
+ deliver_key = "web::show::hfr270"
+ task_metadata = {}
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr270",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key=deliver_key,
+ metadata=task_metadata,
+ )
+
+ # `/new`: the pinned session goes and the reclaim pauses the definition.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ # THE CONCURRENT WINNER: a sibling definition's rebind that DID land, reserved
+ # after the same teardown and through the SAME branch as the one under test, so
+ # it is indistinguishable from the loser by age, visibility, anchor shape or
+ # workdir. For the scoped placement that workdir is the SHARED one the loser also
+ # got, which is what makes "the reclaim removed a directory it did not create" a
+ # failing assertion rather than a hypothetical.
+ if placement == "scoped":
+ winner = sessions.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_C123:runtime_winner",
+ agent_name="codex",
+ )
+ else:
+ winner = sessions.reserve_standalone_agent_session(
+ agent_backend="codex",
+ session_anchor="standalone_hfr270_winner",
+ agent_name="codex",
+ )
+ reserved_winner = sessions.get_agent_session_by_id(str(winner))
+ finally:
+ sessions.close()
+ assert winner and reserved_winner
+ winner_workdir = Path(str(reserved_winner["workdir"]))
+ # The standalone branch mkdirs its own workspace; a scoped reservation only records
+ # the Scope's shared path, which exists in production because turns run in it.
+ winner_workdir.mkdir(parents=True, exist_ok=True)
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None and reloaded.enabled is True
+
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ reserved = _spy_reserved_sessions(service)
+ notices = _spy_binding_notices(service)
+
+ # THE COMPETING TEARDOWN, from its own engine, after the read the fire acts from.
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ summary = reclaim_bound_definitions(
+ conn, pinned, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared"
+ )
+ finally:
+ engine.dispose()
+ assert summary["paused"] == 1, (
+ f"the competing teardown never landed ({summary!r}), so this test proves nothing"
+ )
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ assert [notice.action for notice in notices] == ["reclaimed"], (
+ f"the rebind was not refused, so the leak this test is about never happened: "
+ f"{[n.action for n in notices]}"
+ )
+ assert dispatched == [], "HFR-268 regressed: a refused rebind dispatched its turn"
+ assert len(reserved) == 1, (
+ f"expected exactly one reservation on the refused path, got {reserved!r}"
+ )
+ orphan = reserved[0]
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ orphan_row = sessions.get_agent_session_by_id(orphan)
+ winner_row = sessions.get_agent_session_by_id(winner)
+ finally:
+ sessions.close()
+
+ assert orphan_row is None, (
+ f"the refused rebind left its replacement session {orphan} behind "
+ f"(workdir={None if orphan_row is None else orphan_row.get('workdir')!r}): a live, "
+ "unreferenced background session that nothing will ever run, delete or show, and "
+ "one more of them for every fire that loses this race"
+ )
+ orphan_workspace = Path(paths.get_show_page_dir(orphan))
+ assert not orphan_workspace.exists(), (
+ f"the refused rebind left the Show Page workspace {orphan_workspace} it created"
+ )
+ if placement == "standalone":
+ assert Path(paths.get_show_pages_dir()).is_dir(), (
+ "the standalone placement never reached the workspace branch, so the "
+ "directory half of this test proves nothing"
+ )
+
+ assert winner_row is not None, (
+ "the reclaim took a session this call did not reserve: the concurrent winner's "
+ "row is gone, so a rebind that DID land has just been orphaned by one that did not"
+ )
+ assert winner_workdir.is_dir(), (
+ f"the reclaim removed {winner_workdir}, which the released reservation did not "
+ "create: for the scoped placement that directory is the Scope's, shared with "
+ "every session in it"
+ )
+
+ stored = ScheduledTaskStore().get_task(task.id)
+ assert stored is not None and stored.session_id == pinned, (
+ "the refused rebind was stored anyway"
+ )
+ live = store.get_task(task.id)
+ assert live is not None and live.session_id == pinned and live.enabled is False, (
+ "the live store mirror still shows the rebind the database refused "
+ f"(session_id={None if live is None else live.session_id!r}, "
+ f"enabled={None if live is None else live.enabled!r})"
+ )
+
+
+#: Spelled out rather than imported from ``core.scheduled_tasks``: this is a DURABLE
+#: definition-metadata key, so the name itself is the contract a later fire (and any
+#: operator reading ``run_definitions.metadata_json``) depends on.
+_ORPHAN_RESERVATIONS_KEY = "orphaned_reservations"
+
+
+def test_a_release_that_fails_records_the_orphan_instead_of_reporting_a_reclaim(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-276 — the consuming end of HFR-270's own cleanup.
+
+ THE PRODUCTION STORY, one layer inside the fix. Same race as HFR-268/HFR-270: a
+ ``create_once`` definition's pinned Session is gone, the fire reserves a
+ replacement, a second teardown pauses the definition, and the guarded rebind is
+ refused. HFR-270 then gives the replacement back. That release is deliberately
+ NEVER FATAL -- it runs on a path that is already reporting a failure to the user
+ and must not raise a second exception on top of it -- so ``_release_reserved_session``
+ catches everything and returns ``False``.
+
+ THE CALLER IGNORED THE ANSWER. ``_recover_pinned_session_binding`` emitted
+ ``action="reclaimed"`` unconditionally, so a locked database or an I/O fault during
+ the release produced exactly the orphan HFR-270 promises cannot remain, told the
+ user the opposite, and lost the only handle on it: the reserved session's id is
+ random, it is never written to the definition, and nothing else ever knew it. The
+ next fire that loses the same race reserves and leaks another one, untracked.
+
+ THE REQUIREMENT HAS TWO CLAUSES and a truthful terminal outcome only satisfies the
+ first. The losing path must not report a completed reclaim, AND it must not keep
+ accumulating UNTRACKED reservations -- so the id is recorded durably on the
+ definition (``metadata.orphaned_reservations``, the same ``run_definitions``
+ metadata the binding-recovery record already uses) and a later fire retries the
+ release from it.
+
+ THE FAULT IS INJECTED INSIDE THE RELEASE, which is the only moment that satisfies
+ both preconditions at once: the replacement row already exists (the reservation
+ committed) and the rebind CAS has already lost (the definition still names the
+ session the teardown cleared). The injection asserts both, so a refactor that moved
+ the release earlier could not leave this test passing vacuously.
+ """
+ import sqlite3
+
+ from sqlalchemy.exc import OperationalError
+
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr276",
+ native_session_id="native-1",
+ )
+ finally:
+ sessions.close()
+ assert pinned
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new`: the pinned session goes and the reclaim pauses the definition.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None and reloaded.enabled is True
+
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ reserved = _spy_reserved_sessions(service)
+ notices = _spy_binding_notices(service)
+
+ # THE COMPETING TEARDOWN, from its own engine, after the read the fire acts from.
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ summary = reclaim_bound_definitions(
+ conn, pinned, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared"
+ )
+ finally:
+ engine.dispose()
+ assert summary["paused"] == 1, (
+ f"the competing teardown never landed ({summary!r}), so this test proves nothing"
+ )
+
+ # THE OPERATIONAL FAULT, inside the release itself: the shape a locked database
+ # takes on the DELETE, which ``_release_reserved_session`` is required to swallow.
+ observed: dict[str, Any] = {"calls": 0, "fail": True}
+ original_release = SQLiteSessionsService.release_reserved_agent_session
+
+ def _failing_release(self, session_id, *, reason): # noqa: ANN001, ANN202
+ observed["calls"] += 1
+ observed["session_id"] = str(session_id)
+ observed["row_existed"] = self.get_agent_session_by_id(str(session_id)) is not None
+ observed["stored_session_id"] = _stored_definition_row(task.id)["session_id"]
+ if not observed["fail"]:
+ return original_release(self, session_id, reason=reason)
+ raise OperationalError(
+ "DELETE FROM agent_sessions ...", {}, sqlite3.OperationalError("database is locked")
+ )
+
+ monkeypatch.setattr(
+ SQLiteSessionsService, "release_reserved_agent_session", _failing_release
+ )
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ assert observed["calls"] == 1, (
+ f"the release was not attempted exactly once ({observed!r}), so the failure this "
+ "test injects never reached the branch under test"
+ )
+ assert observed["row_existed"] is True, (
+ "the replacement session did not exist when the release ran, so the fault was "
+ "injected before the reservation committed and no orphan is possible"
+ )
+ assert observed["stored_session_id"] == pinned, (
+ "the definition had already been repointed when the release ran, so the rebind "
+ f"CAS did NOT lose ({observed['stored_session_id']!r}) and this is a different case"
+ )
+ assert dispatched == [], "HFR-268 regressed: a refused rebind dispatched its turn"
+ assert len(reserved) == 1, f"expected exactly one reservation, got {reserved!r}"
+ orphan = reserved[0]
+ assert observed["session_id"] == orphan, (
+ "the release was attempted against a session this fire did not reserve"
+ )
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ orphan_row = sessions.get_agent_session_by_id(orphan)
+ finally:
+ sessions.close()
+ assert orphan_row is not None, (
+ "the injected fault did not actually prevent the release, so there is no orphan "
+ "and the reporting/tracking assertions below prove nothing"
+ )
+
+ # CLAUSE ONE: the outcome must not claim the session was reclaimed. ``action`` is
+ # what the notice, the durable ``binding_recovery`` record and every future
+ # consumer key off, so "reclaimed" here is the lie, not a wording preference.
+ assert [notice.action for notice in notices] == ["orphaned"], (
+ "the failed cleanup was reported as a completed reclaim: the user is told the "
+ f"replacement was given back while it is still live ({[n.action for n in notices]})"
+ )
+ notice = notices[0]
+ assert notice.orphaned_session_id == orphan and notice.orphan_tracked is True
+ assert orphan in (notice.detail or "") and "could NOT be given back" in (notice.detail or ""), (
+ f"the notice does not name the session that leaked: {notice.detail!r}"
+ )
+
+ # CLAUSE TWO: the reservation must not be UNTRACKED. Durable row and live mirror
+ # both, because a fact that only one of them holds is not a fact the next fire can
+ # act on (the round-18 rule applied to a record instead of a rollback).
+ durable_metadata = json.loads(_stored_definition_row(task.id)["metadata_json"] or "{}")
+ durable_entries = durable_metadata.get(_ORPHAN_RESERVATIONS_KEY) or []
+ assert [entry.get("session_id") for entry in durable_entries] == [orphan], (
+ f"the orphaned reservation {orphan} was not durably recorded on the definition "
+ f"({durable_entries!r}): its id is random and nothing else ever knew it, so the "
+ "leak is untracked and no later attempt can find it"
+ )
+ live = store.get_task(task.id)
+ assert live is not None
+ live_entries = (live.metadata or {}).get(_ORPHAN_RESERVATIONS_KEY) or []
+ assert [entry.get("session_id") for entry in live_entries] == [orphan], (
+ f"the live store mirror does not carry the orphan record ({live_entries!r}), so "
+ "the next fire reads a definition that has forgotten it"
+ )
+ assert live.session_id == pinned and live.enabled is False, (
+ "recording the orphan restored the binding or the enabled state the teardown "
+ f"cleared (session_id={live.session_id!r}, enabled={live.enabled!r})"
+ )
+ assert _stored_definition_row(task.id)["session_id"] == pinned, (
+ "recording the orphan wrote the refused rebind through after all"
+ )
+ stored = ScheduledTaskStore().get_task(task.id)
+ assert stored is not None and stored.last_error and orphan in stored.last_error, (
+ f"the durable error does not name the leaked session: {stored.last_error!r}"
+ )
+
+ # AND THE RECORD IS ACTIONABLE, THROUGH THE FIRE PATH: with the database healthy
+ # again, the NEXT FIRE of the same definition -- ``_execute_task``, not a helper
+ # called by hand -- reads the record, finishes the release and drops the entry.
+ # That is what makes the accumulation tracked-and-retryable rather than merely
+ # written down, and it is why the record lives on the definition that reserved it.
+ observed["fail"] = False
+ next_fire = ScheduledTaskStore()
+ refire = next_fire.get_task(task.id)
+ assert refire is not None
+ assert (refire.metadata or {}).get(_ORPHAN_RESERVATIONS_KEY), (
+ "the re-read definition carries no orphan record, so the retry has nothing to act on"
+ )
+ later = _dispatching_binding_service(tmp_path, next_fire, db_path=db_path)
+
+ asyncio.run(later._execute_task(refire, execution_id="exec-2", disable_one_shot=False))
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.get_agent_session_by_id(orphan) is None, (
+ "the next fire did not release the recorded orphan, so the durable fact leads "
+ "nowhere and the reservation accumulates anyway"
+ )
+ finally:
+ sessions.close()
+ durable_after = json.loads(_stored_definition_row(task.id)["metadata_json"] or "{}")
+ assert not durable_after.get(_ORPHAN_RESERVATIONS_KEY), (
+ "the released orphan is still recorded durably, so every later fire retries a "
+ f"session that is already gone ({durable_after.get(_ORPHAN_RESERVATIONS_KEY)!r})"
+ )
+ live_after = next_fire.get_task(task.id)
+ assert live_after is not None and not (live_after.metadata or {}).get(
+ _ORPHAN_RESERVATIONS_KEY
+ ), "the live mirror still records an orphan the retry released"
+
+
+def test_an_adopted_reservation_is_dropped_from_the_retry_record_without_being_touched(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-279 — the retry record must not hold an adopted winner hostage.
+
+ ONE LAYER INSIDE HFR-276's OWN FIX. ``release_reserved_agent_session`` answers
+ ``False`` for three different facts -- gone, adopted, faulted -- and the retry's
+ absence-only probe resolved only the first. A tracked reservation that was since
+ ADOPTED (a native session dispatched into it, or a definition pointing at it) is
+ not absent and can never be released, so its entry stayed on
+ ``orphaned_reservations`` forever and every later fire of the original definition
+ re-took SQLite's write lock (the release's ``BEGIN IMMEDIATE``) to retry a cleanup
+ that cannot succeed.
+
+ THE CONTRACT, all four verdicts of the classification the fix introduces:
+
+ * absent row -- resolved, dropped from the record;
+ * native-bound or definition-referenced row -- an adopted winner: resolved and
+ dropped WITHOUT being read under the write lock, let alone mutated;
+ * still empty-native and unreferenced -- a genuine orphan: released;
+ * a classification that cannot read -- kept (its own test below).
+
+ Both adoption arms are exercised, and the winner invariance is the FULL row (the
+ HFR-251 lesson): route/anchor, workdir, pins and metadata markers, visibility and
+ every timestamp, byte-for-byte -- plus the adopting definition's full row. The
+ release spy pins the mechanism itself: no release attempt is made for either
+ adopted row or for the absent id, so the winner never pays the loser's lock again.
+ """
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr279",
+ native_session_id="native-hfr279-pinned",
+ )
+ adopted_native = sessions.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_C123:runtime_hfr279_native",
+ )
+ adopted_definition = sessions.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_C123:runtime_hfr279_def",
+ )
+ genuine = sessions.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_C123:runtime_hfr279_orphan",
+ )
+ assert pinned and adopted_native and adopted_definition and genuine
+ # The first adoption arm: a turn was dispatched into the row after it was
+ # recorded as orphaned, so it has a transcript and is a reservation no more.
+ bound = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:runtime_hfr279_native",
+ native_session_id="native-hfr279-winner",
+ )
+ assert bound == adopted_native, f"the native bind created a new row ({bound!r})"
+ finally:
+ sessions.close()
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ # The second adoption arm: another definition adopted the tracked reservation
+ # after all, so the row is its live binding and run_definitions points at it.
+ winner = store.add_task(
+ session_key="",
+ session_id=adopted_definition,
+ session_policy="create_once",
+ prompt="the winner's digest",
+ schedule_type="cron",
+ cron="30 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ assert store.record_orphaned_reservations(
+ task.id,
+ [
+ {"session_id": adopted_native, "reason": "hfr279 native arm", "at": "2026-07-29T00:00:00Z"},
+ {"session_id": adopted_definition, "reason": "hfr279 definition arm", "at": "2026-07-29T00:00:00Z"},
+ {"session_id": genuine, "reason": "hfr279 genuine orphan", "at": "2026-07-29T00:00:00Z"},
+ {"session_id": "sess-gone-hfr279", "reason": "hfr279 absent id", "at": "2026-07-29T00:00:00Z"},
+ ],
+ )
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ native_winner_before = sessions.get_agent_session_by_id(adopted_native)
+ definition_winner_before = sessions.get_agent_session_by_id(adopted_definition)
+ finally:
+ sessions.close()
+ assert native_winner_before is not None and definition_winner_before is not None
+ winner_definition_before = _stored_definition_row(winner.id)
+
+ calls: list = []
+ service = _binding_service(tmp_path, store, calls)
+ release_attempts: list[str] = []
+ original_release = ScheduledTaskService._release_reserved_session
+
+ def _spy_release(self, session_id, *, reason): # noqa: ANN001, ANN202
+ release_attempts.append(str(session_id))
+ return original_release(self, session_id, reason=reason)
+
+ monkeypatch.setattr(ScheduledTaskService, "_release_reserved_session", _spy_release)
+
+ fire = store.get_task(task.id)
+ assert fire is not None
+ asyncio.run(service._execute_task(fire, execution_id="exec-hfr279", disable_one_shot=False))
+
+ # THE MECHANISM: only the genuine orphan was worth a release attempt. Neither
+ # adopted row -- nor the absent id -- was made to pay the release's write lock.
+ assert release_attempts == [genuine], (
+ f"the retry attempted releases against {release_attempts!r}; an adopted winner "
+ "or an absent id reaching the guarded release means the classification did not "
+ "run, or did not run first"
+ )
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.get_agent_session_by_id(genuine) is None, (
+ "the genuine orphan was not released, so the classification resolved the "
+ "wrong verdict for the one entry that IS still this definition's to clean"
+ )
+ native_winner_after = sessions.get_agent_session_by_id(adopted_native)
+ definition_winner_after = sessions.get_agent_session_by_id(adopted_definition)
+ finally:
+ sessions.close()
+ assert native_winner_after == native_winner_before, (
+ "the natively-bound winner's row changed while its entry was being resolved: "
+ f"{native_winner_before!r} -> {native_winner_after!r}"
+ )
+ assert definition_winner_after == definition_winner_before, (
+ "the definition-adopted winner's row changed while its entry was being resolved: "
+ f"{definition_winner_before!r} -> {definition_winner_after!r}"
+ )
+ assert _stored_definition_row(winner.id) == winner_definition_before, (
+ "resolving the loser's record mutated the ADOPTING definition's row"
+ )
+
+ durable_after = json.loads(_stored_definition_row(task.id)["metadata_json"] or "{}")
+ assert not durable_after.get(_ORPHAN_RESERVATIONS_KEY), (
+ "the retry record still holds resolved entries "
+ f"({durable_after.get(_ORPHAN_RESERVATIONS_KEY)!r}): an adopted or absent id "
+ "kept there is retried -- and re-locked -- on every later fire, forever"
+ )
+ live_after = store.get_task(task.id)
+ assert live_after is not None and not (live_after.metadata or {}).get(
+ _ORPHAN_RESERVATIONS_KEY
+ ), "the live mirror still carries entries the durable record dropped"
+
+
+def test_a_retry_classification_that_cannot_read_keeps_the_entry(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-279, the fault verdict — a probe that could not read must keep the entry.
+
+ The classification exists to take entries OFF the record, which makes its own
+ failure mode the dangerous one: reading "could not classify" as "resolved" would
+ drop a genuine orphan on the very fault -- a locked or unavailable database --
+ that produced it. The contract is the conservative fourth verdict: keep the
+ entry, touch nothing, do not guess. The release spy pins that no release is
+ attempted either: a row whose state is unknown is not this fire's to delete.
+ """
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr279_fault",
+ native_session_id="native-hfr279-fault",
+ )
+ genuine = sessions.reserve_agent_session(
+ scope_key="slack::channel::C123",
+ agent_backend="codex",
+ session_anchor="slack_C123:runtime_hfr279_fault",
+ )
+ finally:
+ sessions.close()
+ assert pinned and genuine
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ entry = {"session_id": genuine, "reason": "hfr279 fault arm", "at": "2026-07-29T00:00:00Z"}
+ assert store.record_orphaned_reservations(task.id, [entry])
+
+ def _unreadable(self, session_id): # noqa: ANN001, ANN202
+ raise RuntimeError("disk I/O error")
+
+ monkeypatch.setattr(
+ SQLiteSessionsService, "classify_reserved_agent_session", _unreadable
+ )
+ release_attempts: list[str] = []
+ original_release = ScheduledTaskService._release_reserved_session
+
+ def _spy_release(self, session_id, *, reason): # noqa: ANN001, ANN202
+ release_attempts.append(str(session_id))
+ return original_release(self, session_id, reason=reason)
+
+ monkeypatch.setattr(ScheduledTaskService, "_release_reserved_session", _spy_release)
+
+ calls: list = []
+ service = _binding_service(tmp_path, store, calls)
+ fire = store.get_task(task.id)
+ assert fire is not None
+ asyncio.run(
+ service._execute_task(fire, execution_id="exec-hfr279-fault", disable_one_shot=False)
+ )
+
+ assert release_attempts == [], (
+ f"a release was attempted ({release_attempts!r}) for an entry whose state the "
+ "classification could not establish"
+ )
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.get_agent_session_by_id(genuine) is not None, (
+ "the unreadable entry's row was deleted anyway"
+ )
+ finally:
+ sessions.close()
+ durable_after = json.loads(_stored_definition_row(task.id)["metadata_json"] or "{}")
+ kept = durable_after.get(_ORPHAN_RESERVATIONS_KEY) or []
+ assert [item.get("session_id") for item in kept] == [genuine], (
+ f"the entry did not survive the unreadable classification ({kept!r}); dropping "
+ "it loses the only recorded handle on a still-live reservation"
+ )
+
+
+def test_a_locked_database_that_refuses_release_and_record_still_recovers_the_orphan(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-276, the shared-fault half — the durable handle must survive the fault itself.
+
+ THE HOLE THE FIRST HFR-276 REGRESSION LEFT. It monkeypatched the release to raise
+ while leaving SQLite healthy, so the ``orphaned_reservations`` record that
+ immediately follows always landed. In the stated production cases -- a locked or
+ unavailable database, an I/O fault -- both writes go through the SAME database, so
+ the fault that refused the release refuses the record too: the code then reported
+ ``action="orphaned"`` truthfully, but the id was in a log line and nowhere else,
+ untracked and unretryable.
+
+ THE FAULT HERE IS REAL. A second connection takes ``BEGIN IMMEDIATE`` on the same
+ database file the instant the release is entered and holds it across the record
+ write, so both fail with SQLite's own ``database is locked`` -- the release inside
+ its guarded transaction, the record inside ``_write_task``, which RAISES on a
+ faulted write (HFR-272) rather than returning ``False``. That raise is itself part
+ of the regression: the first fix only ever consumed the boolean, so the production
+ fault unwound past the notice branch the monkeypatched test appeared to cover.
+
+ THE DURABLE HANDLE IS THE RESERVATION ROW ITSELF. The row committed before the
+ fault -- that is what makes it an orphan -- and it carries the reserving
+ definition's id in its own metadata, stamped inside the reservation's transaction:
+ if the reservation exists, so does the stamp, no matter what later writes were
+ refused. The fault then ends the way a transient fault ends -- by going away,
+ writing nothing -- and the NEXT FIRE, from freshly constructed stores (the restart
+ shape), recovers the id from the stamp, releases the row, and rebinds. A third
+ fire pins the sweep's own safety: the rebound session is stamped AND adopted, and
+ must never be swept.
+ """
+ import sqlite3 as sqlite3_module
+
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+ from storage.sessions_service import (
+ RESERVED_BY_DEFINITION_METADATA_KEY,
+ SQLiteSessionsService,
+ )
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ pinned = sessions.bind_agent_session(
+ scope_key="slack::channel::C123",
+ agent_name="codex",
+ session_anchor="slack_C123:definition_hfr276_fault",
+ native_session_id="native-hfr276-fault",
+ )
+ finally:
+ sessions.close()
+ assert pinned
+
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=pinned,
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ # `/new`: the pinned session goes and the reclaim pauses the definition.
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.delete_agent_sessions(
+ scope_key="slack::channel::C123",
+ session_anchor_prefix="slack_C123",
+ )
+ finally:
+ sessions.close()
+ store = ScheduledTaskStore()
+ store.set_enabled(task.id, True)
+ reloaded = store.get_task(task.id)
+ assert reloaded is not None and reloaded.enabled is True
+
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ reserved = _spy_reserved_sessions(service)
+ notices = _spy_binding_notices(service)
+
+ # THE COMPETING TEARDOWN, from its own engine, after the read the fire acts from:
+ # what makes the guarded rebind lose, exactly as in the first HFR-276 regression.
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ summary = reclaim_bound_definitions(
+ conn, pinned, mode=RECLAIM_PAUSE, reason="the bound agent session was cleared"
+ )
+ finally:
+ engine.dispose()
+ assert summary["paused"] == 1, (
+ f"the competing teardown never landed ({summary!r}), so this test proves nothing"
+ )
+
+ # THE SHARED FAULT: a real write lock on the real database file, taken the moment
+ # the release is entered and lifted only after the record write has failed against
+ # it. Nothing about the release or the record is stubbed; both hit SQLite and get
+ # SQLite's answer.
+ holder = sqlite3_module.connect(str(db_path))
+ fault = {"armed": True, "held": False, "release_calls": 0, "record_failures": 0}
+ original_release = SQLiteSessionsService.release_reserved_agent_session
+ original_record = ScheduledTaskStore.record_orphaned_reservations
+
+ def _release_under_fault(self, session_id, *, reason): # noqa: ANN001, ANN202
+ if fault["armed"]:
+ fault["armed"] = False
+ holder.execute("BEGIN IMMEDIATE")
+ fault["held"] = True
+ fault["release_calls"] += 1
+ return original_release(self, session_id, reason=reason)
+
+ def _record_under_fault(self, task_id, entries): # noqa: ANN001, ANN202
+ try:
+ return original_record(self, task_id, entries)
+ except Exception:
+ if fault["held"]:
+ fault["record_failures"] += 1
+ raise
+ finally:
+ if fault["held"]:
+ holder.rollback()
+ fault["held"] = False
+
+ monkeypatch.setattr(
+ SQLiteSessionsService, "release_reserved_agent_session", _release_under_fault
+ )
+ monkeypatch.setattr(
+ ScheduledTaskStore, "record_orphaned_reservations", _record_under_fault
+ )
+
+ asyncio.run(service._execute_task(reloaded, execution_id="exec-1", disable_one_shot=False))
+
+ assert fault["release_calls"] == 1, (
+ f"the fault was never armed around a release ({fault!r}), so nothing below "
+ "exercises the shared failure"
+ )
+ assert fault["record_failures"] == 1, (
+ f"the record write did not fail under the same lock that refused the release "
+ f"({fault!r}); the shared-fault claim is exactly that both fail for one reason"
+ )
+ assert dispatched == [], "HFR-268 regressed: a refused rebind dispatched its turn"
+ assert len(reserved) == 1, f"expected exactly one reservation, got {reserved!r}"
+ orphan = reserved[0]
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ orphan_row = sessions.get_agent_session_by_id(orphan)
+ finally:
+ sessions.close()
+ assert orphan_row is not None, (
+ "the locked database did not actually prevent the release, so there is no "
+ "orphan and nothing below proves recovery"
+ )
+ orphan_stamp = json.loads(orphan_row.get("metadata_json") or "{}").get(
+ RESERVED_BY_DEFINITION_METADATA_KEY
+ )
+ assert orphan_stamp == task.id, (
+ f"the reservation does not name its definition ({orphan_stamp!r}); with the "
+ "record refused, that stamp is the only durable handle on the id"
+ )
+
+ durable = json.loads(_stored_definition_row(task.id)["metadata_json"] or "{}")
+ assert not durable.get(_ORPHAN_RESERVATIONS_KEY), (
+ "the orphan record landed despite the lock, so this test degenerated into the "
+ "healthy-database case the first regression already covers"
+ )
+ assert [notice.action for notice in notices] == ["orphaned"], (
+ f"the truthful terminal outcome regressed under the real fault "
+ f"({[n.action for n in notices]})"
+ )
+ notice = notices[0]
+ assert notice.orphaned_session_id == orphan and notice.orphan_tracked is True, (
+ "the stamped orphan was reported as untracked: the row itself durably names "
+ f"this definition (tracked={notice.orphan_tracked!r})"
+ )
+ assert "stamp" in (notice.detail or ""), (
+ f"the notice does not say how the next run finds the id: {notice.detail!r}"
+ )
+
+ # THE FAULT IS GONE AND THE PROCESS RESTARTED: fresh store, fresh service, nothing
+ # in memory. The only handles that survive are the database rows themselves.
+ next_fire = ScheduledTaskStore()
+ refire = next_fire.get_task(task.id)
+ assert refire is not None
+ assert not (refire.metadata or {}).get(_ORPHAN_RESERVATIONS_KEY), (
+ "the restarted store carries an orphan record the locked database supposedly "
+ "refused; the fault injection above did not do what it claims"
+ )
+ later = _dispatching_binding_service(tmp_path, next_fire, db_path=db_path)
+ asyncio.run(later._execute_task(refire, execution_id="exec-2", disable_one_shot=False))
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ assert sessions.get_agent_session_by_id(orphan) is None, (
+ "the next fire did not recover the orphan from its stamp: with the record "
+ "refused, the leak is permanent and HFR-276's durability claim is false"
+ )
+ finally:
+ sessions.close()
+
+ # THE FIRE ALSO REBOUND, and the rebound session is stamped AND adopted: the sweep
+ # must classify it as a winner and never touch it (HFR-279 guarding HFR-276).
+ rebound = next_fire.get_task(task.id)
+ assert rebound is not None and rebound.session_id and rebound.session_id != pinned, (
+ f"the recovery fire did not rebind (session_id={None if rebound is None else rebound.session_id!r})"
+ )
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ adopted_row_before = sessions.get_agent_session_by_id(rebound.session_id)
+ finally:
+ sessions.close()
+ assert adopted_row_before is not None
+ assert json.loads(adopted_row_before.get("metadata_json") or "{}").get(
+ RESERVED_BY_DEFINITION_METADATA_KEY
+ ) == task.id, "the rebound session is not stamped; the durable handle is not being written"
+
+ third_fire = ScheduledTaskStore()
+ third = third_fire.get_task(task.id)
+ assert third is not None
+ third_service = _dispatching_binding_service(tmp_path, third_fire, db_path=db_path)
+ asyncio.run(third_service._execute_task(third, execution_id="exec-3", disable_one_shot=False))
+
+ sessions = SQLiteSessionsService(db_path)
+ try:
+ adopted_row_after = sessions.get_agent_session_by_id(rebound.session_id)
+ finally:
+ sessions.close()
+ assert adopted_row_after is not None, (
+ "a later fire swept the definition's OWN adopted session: the stamp made the "
+ "live binding look like an orphan and the sweep destroyed it"
+ )
+ still_bound = third_fire.get_task(task.id)
+ assert still_bound is not None and still_bound.session_id == rebound.session_id, (
+ f"the third fire re-pointed the definition (session_id="
+ f"{None if still_bound is None else still_bound.session_id!r})"
+ )
+
+
+#: Every guarded writer that mutates the cached ``ScheduledTask`` before persisting it.
+_TASK_MIRROR_WRITERS = {
+ "set_enabled": lambda store, task_id: store.set_enabled(task_id, False),
+ "mark_task_result": lambda store, task_id: store.mark_task_result(task_id, error="boom"),
+ "record_binding_recovery": lambda store, task_id: store.record_binding_recovery(
+ task_id, {"signature": "sig", "action": "paused"}
+ ),
+ "update_task": lambda store, task_id: store.update_task(
+ task_id,
+ **{**_TASK_FIXTURE_PAYLOAD, "name": "renamed"},
+ ),
+}
+
+#: Values a round trip through ``run_definitions`` returns unchanged, so a baseline
+#: mismatch cannot be mistaken for a mirror the failed write left ahead.
+_TASK_FIXTURE_PAYLOAD = {
+ "name": "original",
+ "session_key": "slack::channel::C1",
+ "prompt": "send digest",
+ "schedule_type": "cron",
+ "post_to": None,
+ "deliver_key": None,
+ "cron": "0 * * * *",
+ "run_at": None,
+ "timezone_name": "UTC",
+}
+
+
+def _fail_the_definition_write(engine) -> dict:
+ """Make the ``run_definitions`` write itself fail, the way a real fault would."""
+ from sqlalchemy import event
+
+ state: dict = {"fired": 0}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ normalized = " ".join(statement.split()).upper()
+ if not normalized.startswith(("UPDATE RUN_DEFINITIONS", "INSERT INTO RUN_DEFINITIONS")):
+ return
+ state["fired"] += 1
+ raise RuntimeError("definition write failed: disk I/O error")
+
+ event.listens_for(engine, "before_cursor_execute")(_boom)
+ return state
+
+
[email protected]("writer", list(_TASK_MIRROR_WRITERS))
+def test_a_definition_write_that_raises_leaves_no_live_task_mirror_ahead_of_the_database(
+ writer: str,
+) -> None:
+ """HFR-272 — the task store's twin of HFR-271.
+
+ ``ScheduledTaskStore`` is the same write-through cache with the same choke point:
+ every writer edits the cached ``ScheduledTask`` and hands the whole row to
+ ``_write_task``, and ``_write_task`` reloaded only when the compare-and-set RETURNED
+ ``False``. A raised write -- a full disk, a locked database, a fault between the
+ statement and the commit -- rolls the transaction back just as completely and used to
+ leave the mutation in the mirror, where ``reconcile_jobs`` schedules from it and
+ ``_read_state`` derives the NEXT compare-and-set's expectation from it. Found by
+ applying HFR-271's rule (a rollback is proven only when the durable row and the live
+ object agree) to the sibling store rather than by a second production report.
+ """
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ task = store.add_task(**_TASK_FIXTURE_PAYLOAD)
+
+ durable_before = ScheduledTaskStore().get_task(task.id)
+ live_before = store.get_task(task.id)
+ assert durable_before is not None and live_before is not None
+ assert live_before.to_dict() == durable_before.to_dict(), (
+ "the fixture starts with the mirror already disagreeing with the row, so the "
+ "assertion below would pass or fail for the wrong reason"
+ )
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ _TASK_MIRROR_WRITERS[writer](store, task.id)
+
+ assert boom["fired"] >= 1, (
+ f"{writer} never wrote a run_definitions row, so no fault was injected and this "
+ "test proves nothing"
+ )
+
+ durable_after = ScheduledTaskStore().get_task(task.id)
+ assert durable_after is not None
+ assert durable_after.to_dict() == durable_before.to_dict(), (
+ f"{writer} committed something despite the injected fault; this test can no "
+ "longer tell a rolled-back mirror from a written one"
+ )
+
+ live = store.get_task(task.id)
+ assert live is not None, f"{writer} dropped the task from the live store"
+ assert live.to_dict() == durable_after.to_dict(), (
+ f"{writer} left the live mirror ahead of the database. The transaction rolled "
+ "back; the cached ScheduledTask kept the edit. Differing fields: "
+ + repr(
+ {
+ key: (value, durable_after.to_dict().get(key))
+ for key, value in live.to_dict().items()
+ if durable_after.to_dict().get(key) != value
+ }
+ )
+ )
+
+
+def test_a_failed_create_leaves_no_phantom_task_in_the_live_store() -> None:
+ """HFR-275 — the task store's twin: the create entry point rolls back too.
+
+ ``upsert_task`` is the one writer that can put an id in the mirror the database has
+ NEVER seen. The caller is told the task could not be created, while ``reconcile_jobs``
+ -- which schedules out of exactly this dict -- fires its prompt into the channel on
+ the next tick, with no durable row to stop it and nothing that will reload it away.
+ """
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ before = {task.id for task in store.list_tasks()}
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.add_task(**_TASK_FIXTURE_PAYLOAD)
+
+ assert boom["fired"] >= 1, "no run_definitions write was attempted, so nothing failed"
+ phantom = {task.id for task in store.list_tasks()} - before
+ assert not phantom, (
+ f"the failed create left {sorted(phantom)} in the live store: a task the database "
+ "never accepted, that reconcile_jobs will schedule and fire anyway"
+ )
+ assert not {task.id for task in ScheduledTaskStore().list_tasks()} - before, (
+ "the create committed despite the injected fault, so this test proves nothing"
+ )
+
+
+def test_a_failed_delete_does_not_stop_a_task_the_database_still_has() -> None:
+ """HFR-275 — the delete entry point, the same class in the safer direction.
+
+ ``remove_task`` drops the entry before the soft delete. Absent reads as "gone" and
+ stops the schedule, which is the conservative direction, but it is silent and does
+ NOT heal: the row is still there and UNCHANGED, so ``maybe_reload`` sees no external
+ write and the task the user was told could not be deleted simply stops firing until
+ the process restarts.
+ """
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ task = store.add_task(**_TASK_FIXTURE_PAYLOAD)
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.remove_task(task.id)
+
+ assert boom["fired"] >= 1, "no run_definitions write was attempted, so nothing failed"
+ durable = ScheduledTaskStore().get_task(task.id)
+ assert durable is not None, (
+ "the delete committed despite the injected fault, so this test proves nothing"
+ )
+ live = store.get_task(task.id)
+ assert live is not None, (
+ f"the failed delete dropped task {task.id} from the live store while the database "
+ "still has it: it stops firing, silently, until the process restarts"
+ )
+ assert live.to_dict() == durable.to_dict()
+
+
+#: The two statement shapes the fault below intercepts. The list read is the one
+#: ``ScheduledTaskStore.load`` issues (it is the only ``run_definitions`` SELECT that
+#: filters by ``definition_type``), so the guard's own ``SELECT id ... LIMIT 1`` still
+#: runs and the write is genuinely ATTEMPTED before it fails.
+_DEFINITION_LIST_READ_MARKERS = ("FROM RUN_DEFINITIONS", "DEFINITION_TYPE = ?")
+
+
+def _fail_the_definition_write_and_the_reload(engine) -> dict:
+ """A transient fault that takes out the guarded write AND the recovery read.
+
+ The real shape of HFR-277: whatever broke the write (a locked database, a full
+ disk, an I/O error) is still there a millisecond later when the store tries to
+ reload, so the recovery ``load`` fails too and the entry is dropped. Flip
+ ``state["live"]`` to ``False`` to end the fault WITHOUT committing anything --
+ which is the whole point, because a commit would bump ``PRAGMA data_version`` and
+ heal the mirror for a reason that has nothing to do with the fix.
+ """
+ from sqlalchemy import event
+
+ state: dict = {"writes": 0, "reads": 0, "live": True}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if not state["live"]:
+ return
+ normalized = " ".join(statement.split()).upper()
+ if normalized.startswith(("UPDATE RUN_DEFINITIONS", "INSERT INTO RUN_DEFINITIONS")):
+ state["writes"] += 1
+ raise RuntimeError("definition write failed: disk I/O error")
+ if all(marker in normalized for marker in _DEFINITION_LIST_READ_MARKERS):
+ state["reads"] += 1
+ raise RuntimeError("definition read failed: disk I/O error")
+
+ event.listens_for(engine, "before_cursor_execute")(_boom)
+ return state
+
+
+def test_a_dropped_task_mirror_recovers_with_no_unrelated_commit_to_wake_it() -> None:
+ """HFR-277 — the consuming end of HFR-271/272's own recovery path.
+
+ THE DEFECT, and it is one WE introduced. When a guarded write fails and the
+ immediate recovery ``load`` fails too, ``_reload_after_lost_write`` drops the entry
+ from the live map -- deliberately, because an absent definition is safer to act on
+ than a mutated one the database never accepted -- and promises that ``maybe_reload``
+ will bring it back "once the database is reachable again". It did not. The only thing
+ ``maybe_reload`` consulted was ``SqliteInvalidationProbe``, i.e. ``PRAGMA
+ data_version``, which moves only when another connection COMMITS. The failed write
+ ROLLED BACK, so data_version never moved: every later tick answered "nothing
+ changed", and the task stayed durably enabled in SQLite and invisible in-process
+ until the service restarted or some unrelated write happened to bump the counter.
+ ``reconcile_jobs`` schedules out of exactly this dict, so a cron task simply stopped
+ firing, with the row still saying it is enabled.
+
+ THE CLAUSE THAT IS THE TEST: nothing commits between the failure and the recovery.
+ A witness probe on its own connection asserts data_version is unchanged at that
+ instant, so a mirror that comes back can only have come back because the store
+ remembered it had to reload -- not because another writer woke it up. The fault ends
+ the way a transient fault does, by going away, not by writing anything.
+ """
+ from storage.db import SqliteInvalidationProbe, create_sqlite_engine
+
+ store = ScheduledTaskStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ task = store.add_task(**_TASK_FIXTURE_PAYLOAD)
+ durable_before = ScheduledTaskStore().get_task(task.id)
+ assert durable_before is not None and durable_before.enabled, (
+ "the fixture must start from a definition the database has, and has enabled"
+ )
+
+ # Settle the store's own probe on the fixture's commits first: a pending
+ # data_version bump would reload the mirror below for the wrong reason.
+ store.maybe_reload()
+ assert store.maybe_reload() is False, "the store's probe is not settled"
+ witness_engine = create_sqlite_engine(store._sqlite.db_path)
+ witness = SqliteInvalidationProbe(witness_engine)
+ witness.has_external_write()
+ assert witness.has_external_write() is False, "the witness probe is not settled"
+
+ fault = _fail_the_definition_write_and_the_reload(store._sqlite.engine)
+ try:
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.mark_task_result(task.id, error="boom")
+
+ assert fault["writes"] >= 1, "no run_definitions write was attempted"
+ assert fault["reads"] >= 1, (
+ "the recovery reload was never attempted, so the entry was not dropped for "
+ "the reason this test is about"
+ )
+ assert store.get_task(task.id) is None, (
+ "the failed write did not drop the mirror entry, so there is nothing for "
+ "maybe_reload to recover and this test proves nothing"
+ )
+ assert [item.id for item in store.list_tasks()] == [], (
+ "the dropped entry is still listed; the precondition is a mirror that has "
+ "LOST the definition"
+ )
+
+ # The fault clears the way a transient one does: nothing is written.
+ fault["live"] = False
+ assert witness.has_external_write() is False, (
+ "something COMMITTED between the failed write and the reload below. A "
+ "data_version bump heals the mirror on its own, so this test would pass "
+ "without the fix"
+ )
+
+ assert store.maybe_reload() is True, (
+ "maybe_reload reported 'nothing changed' for a mirror the store itself knows "
+ "is incomplete. data_version cannot see a rolled-back write, so the dropped "
+ "task stays invisible to reconcile_jobs until the process restarts"
+ )
+ live = store.get_task(task.id)
+ assert live is not None, (
+ f"task {task.id} is still missing from the live store after a reload; it is "
+ "enabled in SQLite and will never be scheduled again"
+ )
+ assert live.to_dict() == durable_before.to_dict(), (
+ "the recovered entry does not match the durable row. Differing fields: "
+ + repr(
+ {
+ key: (value, durable_before.to_dict().get(key))
+ for key, value in live.to_dict().items()
+ if durable_before.to_dict().get(key) != value
+ }
+ )
+ )
+ assert [item.id for item in store.list_tasks()] == [task.id]
+ assert store.maybe_reload() is False, (
+ "the store keeps reloading unconditionally; the flag must be cleared by the "
+ "reload that repaired the mirror"
+ )
+ finally:
+ witness.close()
+ witness_engine.dispose()
+
+ durable_after = ScheduledTaskStore().get_task(task.id)
+ assert durable_after is not None and durable_after.to_dict() == durable_before.to_dict(), (
+ "the durable row changed, so the failed write committed something and the "
+ "recovery above was reading a different definition than the one that was dropped"
+ )
diff --git a/tests/test_session_archive.py b/tests/test_session_archive.py
index bf6a6b050..c967d38b1 100644
--- a/tests/test_session_archive.py
+++ b/tests/test_session_archive.py
@@ -4,6 +4,7 @@ row becomes inert (never re-bound by inbound routing or task resolution)."""
from __future__ import annotations
import asyncio
+import json
import sys
from pathlib import Path
from unittest.mock import Mock
@@ -22,8 +23,9 @@ from storage import vault_service as vs
from storage import workbench_sessions_service as wss
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import agent_runs, messages, run_definitions, show_pages, vault_grants, vault_requests
+from storage.models import agent_runs, agent_sessions, messages, run_definitions, show_pages, vault_grants, vault_requests
from storage.vault_crypto import Sealed
+from storage.session_reclaim import session_teardown_context
from storage.sessions_service import SQLiteSessionsService
NOW = "2026-06-08T00:00:00Z"
@@ -524,3 +526,189 @@ def test_show_event_rejected_for_archived_session(monkeypatch, tmp_path: Path) -
assert exc.value.code == "session_archived"
finally:
store.close()
+
+
+# --- P5 (PR5): hard-deleting a session must not orphan definitions bound to it ---
+# Scenario IDs: HFR-049 (pause, never soft-delete) / HFR-050 (settings snapshot).
+
+
+def test_delete_agent_sessions_reclaims_bound_definitions(monkeypatch, tmp_path: Path) -> None:
+ """HFR-049 — the `/new` teardown path pauses bound definitions.
+
+ ``/new`` reaches ``delete_agent_sessions`` (scope-wide via each backend's
+ ``clear_agent_sessions``, and anchor-prefixed via ``clear_session_base``) and
+ HARD-deletes the session rows. Nothing updated ``run_definitions.session_id``,
+ so a ``create_once`` task pinned to that session fired and failed forever.
+
+ Per D2 this path PAUSES (``enabled=0`` + ``last_error``), it does not
+ soft-delete: archive is terminal, ``/new`` is an everyday command. Asserting
+ only "it stopped firing" would pass against a soft-delete, so both halves are
+ pinned here.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ service = SQLiteSessionsService(db_path)
+ try:
+ sid = _bind_session(service, channel="C9", anchor="slack_C9", native="nat1")
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == sid)
+ .values(model="claude-sonnet-legacy", reasoning_effort="high")
+ )
+ _insert_def(conn, def_id="task1", session_id=sid, definition_type="scheduled")
+ _insert_def(conn, def_id="watch1", session_id=sid, definition_type="watch")
+ _insert_def(conn, def_id="task_dead", session_id=sid, definition_type="scheduled", deleted_at=NOW)
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ with session_teardown_context(reason="bound session cleared by /new") as reclaimed:
+ removed = service.delete_agent_sessions(
+ scope_key="slack::channel::C9",
+ session_anchor_prefix="slack_C9",
+ )
+ finally:
+ service.close()
+ assert removed == 1
+ # The teardown ledger is how `/new` reports "N tasks paused" without every
+ # layer between the command handler and storage growing a return value.
+ assert sorted(entry["definition_type"] for entry in reclaimed) == ["scheduled", "watch"]
+ assert {entry["mode"] for entry in reclaimed} == {"pause"}
+
+ with engine.connect() as conn:
+ rows = {row["id"]: dict(row) for row in conn.execute(select(run_definitions)).mappings()}
+
+ for def_id in ("task1", "watch1"):
+ row = rows[def_id]
+ assert row["deleted_at"] is None, f"{def_id} was soft-deleted; D2 requires a pause"
+ assert row["enabled"] == 0, f"{def_id} still fires into a deleted session"
+ assert row["last_error"], f"{def_id} paused with no explanation"
+ assert "/new" in row["last_error"]
+ # D3: the rebind must carry the old settings forward, and ``run_definitions``
+ # has no model/reasoning_effort column — so reclaim is the only place that
+ # still sees both rows.
+ snapshot = json.loads(row["metadata_json"])["session_settings_snapshot"]
+ assert snapshot["session_id"] == sid
+ assert snapshot["model"] == "claude-sonnet-legacy"
+ assert snapshot["reasoning_effort"] == "high"
+ assert snapshot["agent_backend"] == "claude"
+
+ # An already-reclaimed definition is untouched.
+ assert rows["task_dead"]["deleted_at"] == NOW
+ assert rows["task_dead"]["enabled"] == 1
+
+
+def test_archive_still_soft_deletes_bound_definitions(monkeypatch, tmp_path: Path) -> None:
+ """HFR-050 — the shared reclaim helper keeps archive terminal.
+
+ ``reclaim_bound_definitions`` serves two callers with opposite outcomes. This
+ is the guard that extracting it did not turn archive into a pause.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ service = SQLiteSessionsService(db_path)
+ try:
+ sid = _bind_session(service, channel="C10", anchor="slack_C10", native="nat1")
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update().where(agent_sessions.c.id == sid).values(model="opus-legacy")
+ )
+ _insert_def(conn, def_id="task_arch", session_id=sid, definition_type="scheduled")
+ wss.archive_session(conn, sid)
+
+ with engine.connect() as conn:
+ row = dict(
+ conn.execute(select(run_definitions).where(run_definitions.c.id == "task_arch")).mappings().one()
+ )
+ assert row["deleted_at"] is not None
+ assert json.loads(row["metadata_json"])["session_settings_snapshot"]["model"] == "opus-legacy"
+
+
+def test_a_teardown_that_rolls_back_reports_nothing_as_reclaimed(monkeypatch, tmp_path: Path) -> None:
+ """HFR-273 — the ledger is live state, and it must roll back with its transaction.
+
+ Found by applying HFR-271's rule (a rollback is proven only when the durable row and
+ the live in-process state AGREE) to the one piece of teardown state that is not in
+ the database. ``reclaim_bound_definitions`` appends to the teardown ledger as it
+ pauses each definition, and the ledger is what ``handle_new`` counts to tell the user
+ "N tasks paused". It was append-only: a transaction that reclaimed and then ABORTED
+ -- a locked database on a later statement or on the COMMIT itself, the exact class of
+ fault this whole PR is about -- rolled the pause back and left the entry standing.
+
+ And nothing downstream corrects it. ``handle_new`` wraps ``clear_session_base`` in
+ ``except Exception: logger.debug(...)`` and then reports the ledger anyway, so the
+ user is told a task was paused while it is still enabled, still bound to the session
+ they just cleared, and still firing into it every schedule.
+
+ The fault is injected at the session DELETE, i.e. after the reclaim's UPDATE and
+ inside the same transaction, so the database rolls both back together and the only
+ question left is what the ledger says.
+ """
+ from sqlalchemy import event
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ service = SQLiteSessionsService(db_path)
+ try:
+ sid = _bind_session(service, channel="C7", anchor="slack_C7", native="nat1")
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ _insert_def(conn, def_id="task1", session_id=sid, definition_type="scheduled")
+ _insert_def(conn, def_id="watch1", session_id=sid, definition_type="watch")
+
+ fired = {"count": 0}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if not " ".join(statement.split()).upper().startswith("DELETE FROM AGENT_SESSIONS"):
+ return
+ fired["count"] += 1
+ raise RuntimeError("teardown failed: database is locked")
+
+ service = SQLiteSessionsService(db_path)
+ event.listens_for(service.engine, "before_cursor_execute")(_boom)
+ outcome: dict = {}
+ try:
+ with session_teardown_context(reason="bound session cleared by /new") as reclaimed:
+ try:
+ service.delete_agent_sessions(
+ scope_key="slack::channel::C7",
+ session_anchor_prefix="slack_C7",
+ )
+ except Exception as exc: # noqa: BLE001 - the injected fault is the point
+ outcome["error"] = exc
+ # Read INSIDE the context: ``handle_new`` swallows the failure above and
+ # reports the ledger from here, with the teardown context still open.
+ reported = list(reclaimed)
+ finally:
+ service.close()
+
+ assert fired["count"] >= 1, "the session DELETE never ran, so no fault was injected"
+ assert outcome.get("error") is not None, "the injected fault did not reach the caller"
+
+ with engine.connect() as conn:
+ rows = {row["id"]: dict(row) for row in conn.execute(select(run_definitions)).mappings()}
+ assert rows["task1"]["enabled"] == 1 and rows["watch1"]["enabled"] == 1, (
+ "the transaction did not roll the reclaim back, so this test cannot tell a "
+ "rolled-back ledger from an accurate one"
+ )
+
+ assert reported == [], (
+ "the transaction rolled back and the LIVE ledger did not: /new reports "
+ f"{len(reported)} definition(s) paused ({[entry.get('definition_id') for entry in reported]}) "
+ "that are still enabled, still bound to the session the user just cleared, and "
+ "still firing into it"
+ )
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index 9a11eb01d..dd83711e9 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1451,3 +1451,177 @@ def test_reserve_forked_session_silent_completion_is_terminal_no_trim(tmp_path:
result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
# A terminal exists after the input anchor → not a running turn → no trim.
assert result.fork.trim_latest_running_turn is False
+
+
+def test_forking_an_inherited_null_session_keeps_its_explicit_pins(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """HFR-248 — an OMITTED fork override COPIES the column, so it copies the pin.
+
+ ``reserve_forked_session`` resolves ``target_model = _clean_optional(model) if
+ model is not None else row["model"]``: when the caller passes no ``model`` /
+ ``reasoning_effort``, the fork's column is the SOURCE's column, verbatim. The
+ source's ``explicit_setting_overrides`` marker is a claim about that same
+ value, so for a copied field the claim is still true and must survive the fork.
+
+ The first version of this guard reconciled it exactly backwards — it cleared
+ the marker for the fields the fork had NOT supplied, i.e. precisely the copied
+ ones. Forking an explicit-null session (the user pinned "no model, no effort"
+ on purpose, or a preserved ``create_once`` rebind did, HFR-244) then produced a
+ fork that merely *looked* like it inherited nulls. Nothing is visible until the
+ Agent's defaults next move: the marker is gone, so turn-start materialization
+ (HFR-249) pins today's Agent default onto the fork and dispatch runs it with a
+ model and a reasoning effort the source had deliberately pinned away.
+
+ Asserted on the real ``AgentRequest``, because that is the only place the
+ difference is observable — a NULL session column means "inherit from the Agent"
+ to every other session, so the marker is the ONLY thing standing between the
+ fork's nulls and the Agent's live defaults.
+ """
+ import asyncio
+
+ from core.scheduled_tasks import ScheduledTaskStore
+ from modules.agents.base import AgentRequest
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+ from storage.sessions_service import resolve_scope_from_legacy_key
+ from tests.test_scheduled_tasks import _binding_env, _dispatching_binding_service
+
+ db_path = _binding_env(tmp_path, monkeypatch, backends=("claude", "codex"), default="codex")
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ # Pins neither a model nor an effort, exactly like the session below.
+ source_agent = agent_store.create(name="nightly", backend="claude")
+ finally:
+ agent_store.close()
+ assert source_agent.model is None and source_agent.reasoning_effort is None
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ source_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:definition_abc",
+ agent_backend="claude",
+ agent_variant="claude",
+ agent_id=source_agent.id,
+ agent_name=source_agent.name,
+ # NULL columns + the marker naming them: this session pins "nothing",
+ # it does not inherit.
+ model=None,
+ reasoning_effort=None,
+ native_session_id="native-1",
+ workdir=str(tmp_path),
+ title="Source",
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ # The fork supplies NEITHER setting: both columns are copied from the source.
+ forked = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+ assert forked.model is None and forked.reasoning_effort is None
+
+ # The Agent gains defaults AFTER the fork — an ordinary Agent Settings edit,
+ # with no way to know a fork of an explicit-null session points at it.
+ agent_store = VibeAgentStore(db_path)
+ try:
+ edited_agent = agent_store.update("nightly", model="claude-opus-4-6", reasoning_effort="high")
+ finally:
+ agent_store.close()
+ # Proves the request's nulls below are a real pin, not an empty fixture.
+ assert edited_agent.model == "claude-opus-4-6"
+ assert edited_agent.reasoning_effort == "high"
+
+ # A turn on the FORKED session, through the real MessageHandler dispatch path.
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=forked.session_id,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = service.controller.agent_service.dispatched
+ asyncio.run(service._execute_task(task, execution_id="exec-1", disable_one_shot=False))
+
+ assert len(dispatched) == 1, "the turn on the forked session never reached the backend"
+ backend_name, request = dispatched[0]
+ assert isinstance(request, AgentRequest), "the captured request is not the production type"
+ assert backend_name == edited_agent.backend
+ assert request.vibe_agent_name == "nightly", (
+ "precondition: the fork still runs as the source's Agent, only its settings moved"
+ )
+ assert request.vibe_agent_model is None, (
+ f"dispatch handed the backend model={request.vibe_agent_model!r} from the Agent's "
+ "CURRENT settings; the forked session pinned none and the fork copied that pin"
+ )
+ assert request.vibe_agent_reasoning_effort is None, (
+ f"dispatch handed the backend reasoning_effort="
+ f"{request.vibe_agent_reasoning_effort!r} the forked session never had"
+ )
+
+ # ...and the durable record must agree. Read AFTER dispatch on purpose: the
+ # turn-start route materialization is what converts a dropped marker into a
+ # PERMANENT change (HFR-249), so an unmarked fork does not just mis-route this
+ # run -- the Agent's current default becomes the fork's pinned model forever.
+ with engine.connect() as conn:
+ forked_row = conn.execute(
+ select(
+ agent_sessions.c.model,
+ agent_sessions.c.reasoning_effort,
+ agent_sessions.c.metadata_json,
+ ).where(agent_sessions.c.id == forked.session_id)
+ ).one()
+ forked_metadata = json.loads(forked_row.metadata_json or "{}")
+ assert set(forked_metadata.get(SESSION_SETTINGS_OVERRIDE_KEY) or ()) == {
+ "model",
+ "reasoning_effort",
+ }, (
+ "the fork copied the source's NULL model / reasoning_effort but dropped their "
+ f"explicit-override marker (metadata marker={forked_metadata.get(SESSION_SETTINGS_OVERRIDE_KEY)!r}); "
+ "the copied nulls now read as 'inherit from the Agent' and the next Agent "
+ "default change silently gives the fork settings the source pinned away"
+ )
+ assert forked_row.model is None, (
+ f"the forked session acquired model={forked_row.model!r} from the Agent's CURRENT "
+ "settings; the source pinned none and the fork copied that pin"
+ )
+ assert forked_row.reasoning_effort is None, (
+ f"the forked session acquired reasoning_effort={forked_row.reasoning_effort!r} it never had"
+ )
+
+ # The inverse half, so "preserve the marker" cannot degenerate into "always
+ # preserve it": a fork that SUPPLIES a concrete model owns that setting. Its
+ # column is non-NULL, dispatch reads it directly, and a marker entry claiming
+ # an explicit pin on a value the fork replaced would be stale on the next edit.
+ respecified = reserve_forked_session(
+ source_session_id=source_id, model="claude-sonnet-4-9", db_path=db_path
+ )
+ assert respecified.model == "claude-sonnet-4-9"
+ with engine.connect() as conn:
+ respecified_metadata = json.loads(
+ conn.execute(
+ select(agent_sessions.c.metadata_json).where(
+ agent_sessions.c.id == respecified.session_id
+ )
+ ).scalar_one()
+ or "{}"
+ )
+ marked = set(respecified_metadata.get(SESSION_SETTINGS_OVERRIDE_KEY) or ())
+ assert "model" not in marked, (
+ f"the fork replaced model with a concrete value but kept it marked explicit "
+ f"(marker={sorted(marked)}), so a later edit of that column keeps routing the "
+ "value the fork was given"
+ )
+ # The field the fork still did NOT supply is still copied, so still pinned.
+ assert "reasoning_effort" in marked, (
+ f"supplying model dropped the untouched reasoning_effort pin too (marker={sorted(marked)})"
+ )
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index f1804f696..ba6a6ef27 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -1,19 +1,21 @@
from __future__ import annotations
+import ast
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import pytest
-from sqlalchemy import select
+from sqlalchemy import event, select
+from sqlalchemy.exc import OperationalError
from config import paths
from config.v2_sessions import ActivePollInfo, SessionState, SessionsStore
from modules.sessions_facade import SessionsFacade
from storage.agent_session_rows import create_agent_session_row
from storage.db import create_sqlite_engine
-from storage.models import agent_sessions
+from storage.models import agent_sessions, run_definitions
from storage.sessions_service import SQLiteSessionsService, resolve_scope_from_legacy_key
from storage.settings_service import upsert_scope
@@ -459,6 +461,120 @@ def test_materialize_agent_session_route_fills_empty_columns_only(tmp_path: Path
service.close()
+def test_materialize_agent_session_route_never_fills_an_explicitly_pinned_field(
+ tmp_path: Path,
+) -> None:
+ """HFR-249 — a NULL the row pins EXPLICITLY is not an empty column to fill.
+
+ Turn-start materialization exists so a session created on an inherited default
+ stops drifting: the first turn writes the resolved model / effort into the NULL
+ columns. But a preserved ``create_once`` rebind (HFR-244) and a fork of an
+ explicit-null session (HFR-248) both carry NULL columns *on purpose* — the
+ session pinned "no model", and the ``explicit_setting_overrides`` marker is the
+ only thing distinguishing that from "inherited nothing yet". Materializing
+ those NULLs is worse than mis-routing one turn: it PERSISTS the Agent's current
+ default as the session's pinned model, which is exactly the outcome the rebind
+ was preventing, and no later Agent edit can undo it.
+
+ Both halves are asserted, because "skip pinned fields" is only correct if the
+ fill still happens for every ordinary row: an unmarked NULL column must still
+ be filled, otherwise the fix would have quietly disabled materialization.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ pinned_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:pinned",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_name="codex",
+ model=None,
+ reasoning_effort=None,
+ native_session_id="native-pinned",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+ inherited_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:inherited",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_name="codex",
+ model=None,
+ reasoning_effort=None,
+ native_session_id="native-inherited",
+ workdir=str(tmp_path),
+ metadata={},
+ )
+
+ # The pinned row: the first turn resolves the Agent's live default and
+ # offers it here. Nothing may be written.
+ materialized = service.materialize_agent_session_route(
+ pinned_id, model="gpt-5.5", reasoning_effort="xhigh"
+ )
+ row = service.get_agent_session_by_id(pinned_id)
+ assert row is not None
+ assert row["model"] is None, (
+ f"turn start pinned model={row['model']!r} onto a session that explicitly "
+ "pins none; the Agent's current default just became this session's model "
+ "for every run after it"
+ )
+ assert row["reasoning_effort"] is None, (
+ f"turn start pinned reasoning_effort={row['reasoning_effort']!r} onto a "
+ "session that explicitly pins none"
+ )
+ assert materialized is False, (
+ "materialization reported a write on a row that pins both settings "
+ "explicitly; every field it was offered was already spoken for"
+ )
+
+ # A HALF-pinned row: only the marked field is skipped, so the guard is
+ # per-field and not "any marker disables the whole write".
+ with service.engine.begin() as conn:
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == pinned_id)
+ .values(
+ metadata_json=json.dumps({SESSION_SETTINGS_OVERRIDE_KEY: ["model"]})
+ )
+ )
+ assert service.materialize_agent_session_route(
+ pinned_id, model="gpt-5.5", reasoning_effort="xhigh"
+ )
+ row = service.get_agent_session_by_id(pinned_id)
+ assert row is not None
+ assert row["model"] is None, "the still-marked model was filled anyway"
+ assert row["reasoning_effort"] == "xhigh", (
+ "the UNMARKED reasoning_effort was skipped too; one pinned field must not "
+ "freeze the whole route"
+ )
+
+ # The negative half: an ordinary inherited-NULL row still fills in, so the
+ # skip cannot be passing by having disabled materialization outright.
+ assert service.materialize_agent_session_route(
+ inherited_id, model="gpt-5.5", reasoning_effort="xhigh"
+ )
+ row = service.get_agent_session_by_id(inherited_id)
+ assert row is not None
+ assert row["model"] == "gpt-5.5", (
+ "an unmarked NULL column was not filled at turn start; the explicit-pin "
+ "skip has disabled ordinary materialization"
+ )
+ assert row["reasoning_effort"] == "xhigh"
+ finally:
+ service.close()
+
+
def test_reserve_agent_session_uses_runtime_default_when_scope_workdir_missing(tmp_path: Path) -> None:
from storage.models import scope_settings
@@ -1432,3 +1548,3832 @@ def test_sessions_store_preserves_legacy_non_string_session_values(tmp_path: Pat
assert reloaded.state.session_mappings["U1"]["claude"]["base"]["/repo"] == "session-1"
finally:
reloaded.close()
+
+
+# --- P5 (PR5): the (scope_id, session_anchor) invariant and keyed get-or-create ---
+# Scenario IDs: HFR-051 (schema drift) / HFR-052 (foreign-backend adoption)
+# / HFR-053 (find-then-create race).
+
+
+def test_models_declare_scope_anchor_unique_index() -> None:
+ """HFR-051 — ``storage/models.py`` must declare the anchor invariant.
+
+ The UNIQUE index on ``(scope_id, session_anchor)`` lived only in the Alembic
+ revision, while ``SQLiteSessionsService.__init__`` calls ``metadata.create_all``.
+ Any DB born from models-only — including every test that does not run
+ ``ensure_sqlite_state`` — silently lacked the invariant, which is why the
+ collisions below were never caught.
+ """
+ from storage.models import agent_sessions as agent_sessions_table
+
+ unique = {
+ tuple(column.name for column in index.columns)
+ for index in agent_sessions_table.indexes
+ if index.unique
+ }
+ assert ("scope_id", "session_anchor") in unique
+
+
+def test_ensure_agent_session_id_adopts_row_owned_by_other_backend(monkeypatch, tmp_path: Path) -> None:
+ """HFR-052 — lookup key must not be narrower than the constraint key.
+
+ ``_find_agent_session_row_id`` filters on ``agent_backend``; the unique index
+ is ``(scope_id, session_anchor)`` alone. A same-anchor row owned by another
+ backend is invisible to the finder but visible to the index, so the INSERT
+ explodes. A thread is ONE session per (scope, anchor), so the row is adopted.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ existing = service.ensure_agent_session_id(
+ scope_key="slack::channel::C500",
+ agent_name="codex",
+ session_anchor="slack_C500",
+ )
+ assert existing is not None
+
+ adopted = service.ensure_agent_session_id(
+ scope_key="slack::channel::C500",
+ agent_name="claude",
+ session_anchor="slack_C500",
+ )
+ assert adopted == existing
+ row = service.get_agent_session_by_id(existing)
+ assert row["agent_backend"] == "claude"
+ finally:
+ service.close()
+
+
+def test_bind_agent_session_survives_concurrent_insert(monkeypatch, tmp_path: Path) -> None:
+ """HFR-053 — the find-then-create window must be closed by the constraint.
+
+ SQLite deferred transactions take no write lock at the SELECT, so two callers
+ can both miss and both insert. Simulated by blinding the finder while the row
+ exists: the INSERT must lose gracefully and re-read, not raise.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage import sessions_service as sessions_service_module
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ winner = service.bind_agent_session(
+ scope_key="slack::channel::C501",
+ agent_name="claude",
+ session_anchor="slack_C501",
+ native_session_id="native-winner",
+ )
+ assert winner is not None
+
+ monkeypatch.setattr(
+ sessions_service_module,
+ "_find_agent_session_row_id",
+ lambda *args, **kwargs: None,
+ )
+ loser = service.bind_agent_session(
+ scope_key="slack::channel::C501",
+ agent_name="claude",
+ session_anchor="slack_C501",
+ native_session_id="native-loser",
+ )
+ assert loser == winner
+ # Write-once still holds: the racing caller does not steal the native.
+ assert service.get_agent_session_by_id(winner)["native_session_id"] == "native-winner"
+ finally:
+ service.close()
+
+
+def test_prefix_clear_does_not_delete_a_superseded_row(tmp_path):
+ """HFR-059 — superseding preserves the row; a prefix clear must not undo that.
+
+ ``/new`` reaches ``delete_agent_sessions(session_anchor_prefix=<anchor>)``,
+ whose predicate is ``anchor == prefix OR anchor LIKE '<prefix>:%'``, and
+ ``_delete_agent_session_rows`` HARD-deletes what it matches. Superseding
+ keeps the row on purpose ("Nothing is deleted") -- so the suffix marker that
+ preserves thread routing must not also drag the row into that prefix match.
+ """
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "vibe.sqlite"
+ scope_key = "telegram::channel::-1001"
+ anchor = "telegram_-1001_42"
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ bound = service.bind_agent_session(
+ scope_key=scope_key,
+ agent_name="codex",
+ session_anchor=anchor,
+ native_session_id="codex-native-1",
+ )
+ assert bound is not None
+ # Another backend claims the anchor: the bound row is superseded, not deleted.
+ service.ensure_agent_session_id(
+ scope_key=scope_key,
+ agent_name="claude",
+ session_anchor=anchor,
+ )
+ service.delete_agent_sessions(scope_key=scope_key, session_anchor_prefix=anchor)
+ survivors = service.get_agent_session_by_id(bound)
+ finally:
+ service.close()
+
+ assert survivors is not None, (
+ "the superseded row was hard-deleted by a prefix clear; supersede "
+ "promises the row is kept"
+ )
+
+
+def test_backend_wide_clear_does_not_delete_a_superseded_row(tmp_path):
+ """HFR-240 — /new reaches the backend-wide clear FIRST, so guarding only the
+ prefix clear guards nothing.
+
+ ``handle_new`` calls ``agent_service.clear_sessions()`` before
+ ``clear_session_base()``. The backend adapters route the first call to
+ ``clear_agent_sessions(scope_key, agent_name)`` with no
+ ``session_anchor_prefix``, so an exclusion nested inside the prefix branch is
+ skipped entirely and the superseded row is hard-deleted before the guarded
+ clear ever runs -- losing the transcript superseding promises to keep and
+ reclaiming the definitions pinned to it.
+ """
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "vibe.sqlite"
+ scope_key = "telegram::channel::-1001"
+ anchor = "telegram_-1001_42"
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ bound = service.bind_agent_session(
+ scope_key=scope_key,
+ agent_name="codex",
+ session_anchor=anchor,
+ native_session_id="codex-native-1",
+ )
+ assert bound is not None
+ service.ensure_agent_session_id(
+ scope_key=scope_key,
+ agent_name="claude",
+ session_anchor=anchor,
+ )
+ # This is /new's FIRST call: no anchor prefix, scoped to the superseded
+ # row's own backend.
+ service.delete_agent_sessions(scope_key=scope_key, agent_name="codex")
+ survivor = service.get_agent_session_by_id(bound)
+ finally:
+ service.close()
+
+ assert survivor is not None, (
+ "the superseded row was hard-deleted by the backend-wide clear that "
+ "/new performs before the guarded prefix clear"
+ )
+
+
+def test_backend_wide_clear_still_deletes_a_rows_with_an_empty_anchor(tmp_path):
+ """HFR-241 — the superseded exclusion must not preserve everything else.
+
+ Review asked for paired NULL/empty regressions. Only the empty case is
+ constructible: ``agent_sessions.session_anchor`` is ``NOT NULL`` in the model
+ and has been since the initial migration, so the DB rejects a NULL anchor
+ outright (``IntegrityError: NOT NULL constraint failed``). The SQL hazard is
+ real — ``NULL NOT LIKE '%x%'`` evaluates to NULL, not true — and the
+ predicate is written NULL-safe against it, but it cannot be reached from
+ this schema and a test asserting it would be testing the fixture.
+
+ What is reachable is the empty string, which ``NOT LIKE`` handles correctly
+ (returns 1), and this pins that only a real superseded marker survives.
+ """
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_sessions
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "vibe.sqlite"
+ scope_key = "telegram::channel::-1001"
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ empty_row = service.bind_agent_session(
+ scope_key=scope_key, agent_name="codex",
+ session_anchor="telegram_-1001_2", native_session_id="n2",
+ )
+ assert empty_row
+ with service.engine.begin() as conn:
+ conn.execute(sa_update(agent_sessions)
+ .where(agent_sessions.c.id == empty_row)
+ .values(session_anchor=""))
+
+ service.delete_agent_sessions(scope_key=scope_key, agent_name="codex")
+
+ assert service.get_agent_session_by_id(empty_row) is None, (
+ "an empty-anchor row survived a clear; the superseded exclusion is "
+ "preserving rows that carry no marker"
+ )
+ finally:
+ service.close()
+
+
+def test_legacy_adoption_replaces_the_whole_route_of_an_unbound_row(monkeypatch, tmp_path: Path) -> None:
+ """HFR-246 — adopting an unbound row must not leave the old backend's route on it.
+
+ ``_claim_anchor_row`` relabels an UNBOUND row to the incoming backend, but it
+ only replaced ``agent_id`` / ``agent_name`` / ``model`` / ``reasoning_effort``
+ when the incoming route supplied a non-``None`` value -- and the legacy
+ ``ensure_agent_session_id`` / ``bind_agent_session`` callers have no model /
+ effort parameters at all, so they pass ``None`` unconditionally. A thread whose
+ scope moved from Codex to Claude before its first turn therefore became
+ Claude-owned while still carrying the Codex Agent name, a Codex model and a
+ Codex reasoning effort (plus the explicit-override marker that pins them). The
+ next turn resolved that Codex Agent, so the thread ran on the backend the user
+ had just moved away from -- and a Claude backend handed a ``gpt-*`` model
+ fails outright.
+ """
+ import asyncio
+
+ from core.scheduled_tasks import ScheduledTaskStore
+ from core.vibe_agents import VibeAgentStore
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+ from tests.test_scheduled_tasks import _binding_env, _dispatching_binding_service
+
+ db_path = _binding_env(tmp_path, monkeypatch, backends=("claude", "codex"), default="claude")
+ anchor = "slack_C123:definition_abc"
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ codex_agent = agent_store.create(
+ name="nightly-codex", backend="codex", model="gpt-5.5-codex", reasoning_effort="high"
+ )
+ default_agent = agent_store.get_default_agent()
+ finally:
+ agent_store.close()
+ assert default_agent is not None and default_agent.backend == "claude"
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-27T00:00:00Z"
+ )
+ assert scope_id is not None
+ # Reserved for a Codex Agent, never bound: no native conversation exists,
+ # so nothing here is a committed user choice.
+ create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id=codex_agent.id,
+ agent_name=codex_agent.name,
+ model="gpt-5.5-codex",
+ reasoning_effort="high",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ # The scope route moved to Claude; the legacy ensure path adopts the row.
+ service = SQLiteSessionsService(db_path)
+ try:
+ adopted = service.ensure_agent_session_id(
+ scope_key="slack::channel::C123",
+ agent_name="claude",
+ session_anchor=anchor,
+ )
+ assert adopted is not None
+ row = service.get_agent_session_by_id(adopted)
+ finally:
+ service.close()
+
+ assert row["agent_backend"] == "claude"
+ assert row["agent_variant"] == "claude"
+ for column in ("agent_id", "agent_name", "model", "reasoning_effort"):
+ assert row[column] is None, (
+ f"the adopted row kept the previous backend's {column}={row[column]!r}; "
+ "a Claude-owned session is still routing Codex settings"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert SESSION_SETTINGS_OVERRIDE_KEY not in stored_metadata, (
+ "the adoption reset model/reasoning_effort but kept their explicit-override "
+ "marker, so dispatch still pins the old backend's settings"
+ )
+
+ # The row is only half the story: what the backend is HANDED is the failure the
+ # user sees. Fire a definition pinned to this session through the real
+ # MessageHandler dispatch path.
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=adopted,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ dispatch_service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = dispatch_service.controller.agent_service.dispatched
+ asyncio.run(
+ dispatch_service._execute_task(task, execution_id="exec-1", disable_one_shot=False)
+ )
+
+ assert len(dispatched) == 1, "the definition never reached the backend"
+ backend_name, request = dispatched[0]
+ assert backend_name == "claude", (
+ f"the turn was dispatched to the {backend_name!r} backend; the session was "
+ "adopted by Claude before it ever bound a native conversation"
+ )
+ assert request.vibe_agent_name != codex_agent.name, (
+ "the turn still identified as the Codex Agent the adopted row kept"
+ )
+ assert request.vibe_agent_model != "gpt-5.5-codex", (
+ f"dispatch handed the Claude backend model={request.vibe_agent_model!r} from "
+ "the stale Codex route"
+ )
+ assert request.vibe_agent_reasoning_effort != "high" or request.vibe_agent_model is None
+
+
+def test_native_bind_by_id_replaces_the_whole_route_of_an_unbound_row(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """HFR-250 — the SECOND adoption entry point must clear the old backend's settings too.
+
+ HFR-246 fixed ``_claim_anchor_row``, which resolves a row by
+ ``(scope, anchor)``. ``bind_agent_session_by_id`` is a different door into the
+ same state change: the Workbench / fork / subagent callers hand it an
+ explicitly targeted reserved row plus the Agent identity they resolved, so the
+ anchor lookup — and the complete-route replacement it performs — is never
+ involved. It used to set ``agent_backend`` / ``agent_variant`` unconditionally
+ while never touching ``model`` / ``reasoning_effort`` or the
+ ``explicit_setting_overrides`` marker, so a row reserved for OpenCode and then
+ bound under Codex became Codex-owned while still carrying an OpenCode model, an
+ OpenCode reasoning effort, and a marker pinning both as deliberate. The next
+ turn resolved the Codex backend and handed it that OpenCode model.
+
+ Asserted at BOTH ends: the stored row, and the ``AgentRequest`` the real
+ ``MessageHandler`` builds for the next turn on that session — the row is only
+ the cause, what the backend is HANDED is the failure the user sees.
+ """
+ import asyncio
+
+ from core.scheduled_tasks import ScheduledTaskStore
+ from core.vibe_agents import VibeAgentStore
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+ from tests.test_scheduled_tasks import _binding_env, _dispatching_binding_service
+
+ db_path = _binding_env(tmp_path, monkeypatch, backends=("opencode", "codex"), default="codex")
+ anchor = "slack_C123:definition_bind_by_id"
+
+ agent_store = VibeAgentStore(db_path)
+ try:
+ opencode_agent = agent_store.create(
+ name="review-opencode",
+ backend="opencode",
+ model="anthropic/claude-sonnet-4",
+ reasoning_effort="medium",
+ )
+ codex_agent = agent_store.create(
+ name="nightly-codex", backend="codex", model="gpt-5.5-codex", reasoning_effort="high"
+ )
+ finally:
+ agent_store.close()
+
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ # Reserved for the OpenCode Agent, never bound: no native conversation
+ # exists, so none of these settings is a committed user choice yet.
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id=opencode_agent.id,
+ agent_name=opencode_agent.name,
+ model="anthropic/claude-sonnet-4",
+ reasoning_effort="medium",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ # The caller resolved a Codex Agent for this row and binds the native id it
+ # just got back from the Codex backend.
+ service = SQLiteSessionsService(db_path)
+ try:
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="codex-native-250",
+ vibe_agent_id=codex_agent.id,
+ vibe_agent_name=codex_agent.name,
+ vibe_agent_backend="codex",
+ )
+ assert bound == reserved_id
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert row is not None
+ assert row["agent_backend"] == "codex"
+ assert row["agent_variant"] == "codex"
+ assert row["agent_id"] == codex_agent.id
+ assert row["agent_name"] == codex_agent.name
+ for column in ("model", "reasoning_effort"):
+ assert row[column] is None, (
+ f"the bound row kept the previous backend's {column}={row[column]!r}; "
+ "a Codex-owned session is still routing OpenCode settings"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert SESSION_SETTINGS_OVERRIDE_KEY not in stored_metadata, (
+ "the bind replaced the backend-owned route but kept the previous backend's "
+ "explicit-override marker, so dispatch still pins settings the bind cleared"
+ )
+
+ # The consuming end: fire a definition pinned to this session through the real
+ # MessageHandler dispatch path and inspect the AgentRequest it builds.
+ store = ScheduledTaskStore()
+ task = store.add_task(
+ session_key="",
+ session_id=reserved_id,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ dispatch_service = _dispatching_binding_service(tmp_path, store, db_path=db_path)
+ dispatched = dispatch_service.controller.agent_service.dispatched
+ asyncio.run(
+ dispatch_service._execute_task(task, execution_id="exec-1", disable_one_shot=False)
+ )
+
+ assert len(dispatched) == 1, "the definition never reached the backend"
+ backend_name, request = dispatched[0]
+ assert backend_name == "codex", (
+ f"the turn was dispatched to the {backend_name!r} backend; the bind moved "
+ "this session to Codex before it ever produced a turn"
+ )
+ assert request.vibe_agent_name == codex_agent.name, (
+ f"the turn identified as {request.vibe_agent_name!r}; the bind named the "
+ "Codex Agent as this session's owner"
+ )
+ assert request.vibe_agent_model != "anthropic/claude-sonnet-4", (
+ f"dispatch handed the Codex backend model={request.vibe_agent_model!r} from "
+ "the stale OpenCode route"
+ )
+ assert request.vibe_agent_reasoning_effort != "medium", (
+ "dispatch handed the Codex backend the OpenCode route's reasoning effort"
+ )
+
+
+def test_native_bind_by_id_keeps_the_backend_of_an_already_bound_row(tmp_path: Path) -> None:
+ """HFR-250, write-once half — an already-bound row must not switch backend identity.
+
+ The clearing branch above is only safe because it is restricted to rows that
+ have produced nothing. Once a row holds a native conversation, WRITE-ONCE
+ extends to the backend that produced it: re-labelling the row would leave that
+ transcript attributed to a backend that never generated it, and would clear the
+ settings the transcript actually ran on. So a later bind under a different
+ backend keeps the row's own identity and the native id it already has.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ bound_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:already_bound",
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ model="anthropic/claude-sonnet-4",
+ reasoning_effort="medium",
+ native_session_id="opencode-native-1",
+ workdir=str(tmp_path),
+ metadata={},
+ )
+
+ assert (
+ service.bind_agent_session_by_id(
+ session_id=bound_id,
+ native_session_id="codex-native-2",
+ vibe_agent_id="agent-codex",
+ vibe_agent_name="nightly-codex",
+ vibe_agent_backend="codex",
+ )
+ == bound_id
+ )
+ row = service.get_agent_session_by_id(bound_id)
+ finally:
+ service.close()
+
+ assert row is not None
+ assert row["agent_backend"] == "opencode", (
+ f"an already-bound session was re-labelled to {row['agent_backend']!r}; its "
+ "existing transcript is now attributed to a backend that never produced it"
+ )
+ assert row["agent_variant"] == "opencode"
+ assert row["agent_name"] == "review-opencode", (
+ f"the bind switched the bound row's Agent identity to {row['agent_name']!r}"
+ )
+ assert row["agent_id"] == "agent-opencode"
+ assert row["native_session_id"] == "opencode-native-1", (
+ "the write-once native guard let a second bind overwrite the existing "
+ "native conversation id"
+ )
+
+
+def test_native_bind_by_id_keeps_the_pins_of_a_same_backend_bind(tmp_path: Path) -> None:
+ """HFR-250, negative half — an ordinary same-backend bind clears nothing.
+
+ The clearing branch keys off the backend CHANGING. The overwhelmingly common
+ call is the same-backend first bind (a reserved row gets the native id its own
+ backend just produced), and for it the row's ``model`` / ``reasoning_effort``
+ and their explicit-override marker are the user's committed settings. If the
+ fix cleared those too it would silently reset every Workbench session's model
+ on its first turn, which is a worse regression than the one it fixes.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:same_backend",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ model="gpt-5.5-codex",
+ reasoning_effort="xhigh",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ assert (
+ service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="codex-native-3",
+ vibe_agent_id="agent-codex",
+ vibe_agent_name="nightly-codex",
+ vibe_agent_backend="codex",
+ )
+ == reserved_id
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert row is not None
+ assert row["native_session_id"] == "codex-native-3"
+ assert row["agent_backend"] == "codex"
+ assert row["agent_variant"] == "codex"
+ assert row["model"] == "gpt-5.5-codex", (
+ f"a same-backend bind reset the session's pinned model to {row['model']!r}; "
+ "nothing about the route changed, so the user's settings are still theirs"
+ )
+ assert row["reasoning_effort"] == "xhigh", (
+ f"a same-backend bind reset the session's reasoning effort to "
+ f"{row['reasoning_effort']!r}"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ "a same-backend bind dropped the explicit-override marker, so the next turn "
+ "treats the user's pinned settings as inherited defaults it may overwrite"
+ )
+
+
+# --- HFR-251: bind_agent_session_by_id decides from a snapshot it does not hold ---
+#
+# The statements ``bind_agent_session_by_id`` emits, in order (verified against the
+# engine): the status SELECT, the route-snapshot SELECT, the ``_set_native_once``
+# SELECT, then the UPDATE. SQLite takes the write lock at the UPDATE and pysqlite
+# opens no transaction for a bare SELECT, so every one of those reads is released
+# before the write is attempted. The two constants below name the exact reads whose
+# result the code then acts on; the race is committed immediately AFTER one of them.
+
+#: The snapshot the cross-backend adoption branch is decided from.
+_ROUTE_SNAPSHOT_SELECT = (
+ "SELECT agent_sessions.agent_backend, agent_sessions.native_session_id, "
+ "agent_sessions.metadata_json FROM agent_sessions WHERE agent_sessions.id = ?"
+)
+
+#: The read ``_set_native_once`` enforces write-once from.
+_WRITE_ONCE_SELECT = (
+ "SELECT agent_sessions.native_session_id FROM agent_sessions WHERE agent_sessions.id = ?"
+)
+
+#: The archive fast-path read at the very top of the function. Rendered identically
+#: by the ``winner_status`` re-read inside the lost-adoption branch, so a listener
+#: keyed on it must fire only ONCE (``_commit_competing_bind_after`` does).
+_STATUS_FAST_PATH_SELECT = (
+ "SELECT agent_sessions.status FROM agent_sessions WHERE agent_sessions.id = ?"
+)
+
+
+def _commit_competing_bind_after(
+ engine,
+ db_path: Path,
+ *,
+ read: str,
+ values: dict | None = None,
+ table=agent_sessions,
+ write=None,
+) -> dict:
+ """Commit a competing write from a REAL second connection, mid-flight.
+
+ ``values`` is any competing write, not only a bind: HFR-252 passes the column
+ set ``archive_session`` commits, to land a terminal archive inside the window.
+ ``table`` aims that update at another table — HFR-257 repoints a
+ ``run_definitions`` row, which is the competing write the reclaim helper loses
+ to. ``write`` is the escape hatch for a winner that needs MORE than one
+ statement: HFR-258's winner both moves an anchor aside and inserts its
+ replacement row, and both must land in ONE commit to be the real interleaving.
+ ``values`` and ``write`` compose, in that order, inside a single transaction.
+
+ Hooks ``after_cursor_execute`` on the engine the code under test uses — the
+ ENGINE, never the function under test itself — and when the statement
+ ``read`` completes, opens a genuinely separate engine/connection, writes, and
+ COMMITS. Control then returns to the caller mid-transaction, so its next
+ statement runs against a database another writer has already changed.
+
+ Fires ``after`` and not ``before`` the read on purpose: firing before it would
+ let the caller's own SELECT observe the winner, which is the serial
+ already-bound case HFR-250 covers, not a race. The returned dict records how
+ many times the race fired, so a rendered-SQL drift shows up as "never raced"
+ instead of a silently trivial pass.
+ """
+ state = {"fired": 0}
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != read:
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(db_path)
+ try:
+ with other.begin() as other_conn:
+ if values is not None:
+ other_conn.execute(
+ table.update()
+ .where(table.c.id == values["id"])
+ .values(**{key: value for key, value in values.items() if key != "id"})
+ )
+ if write is not None:
+ write(other_conn)
+ finally:
+ other.dispose()
+
+ return state
+
+
+def test_native_bind_by_id_loses_a_concurrent_cross_backend_adoption(tmp_path: Path) -> None:
+ """HFR-251 — the adoption branch reserves nothing between its read and its write.
+
+ THE DEFECT IS THE WINDOW, not the branch. ``bind_agent_session_by_id`` read a
+ snapshot (``agent_backend`` / ``native_session_id`` / ``metadata_json``),
+ decided from it that this row was UNBOUND and on another backend, and then
+ issued an UPDATE guarded only by ``id`` + ``status != 'archived'``. Those reads
+ reserve nothing: pysqlite opens no transaction for a SELECT and SQLite takes
+ the write lock at the UPDATE, so a second connection can bind the row in
+ between. The stale caller still took the adoption branch and applied it to a
+ row that was no longer unbound — relabelling the winner's backend, clearing the
+ winner's ``model`` / ``reasoning_effort`` and their explicit-override marker,
+ and (with a slightly later interleaving) overwriting its write-once native id.
+
+ A SERIAL PRE-BOUND TEST CANNOT OBSERVE THIS. If the row is already bound when
+ the call starts, the function's own snapshot sees the native and routes to the
+ already-bound branch — that is
+ ``test_native_bind_by_id_keeps_the_backend_of_an_already_bound_row`` (HFR-250),
+ and it stays green over the unguarded UPDATE. The failure only exists while the
+ caller's snapshot is stale, so the competing bind has to land INSIDE the window,
+ committed by a real second connection.
+
+ THE INTERLEAVING CHOSEN: the winner binds under the SAME backend the snapshot
+ saw (opencode) — an ordinary same-backend first bind of this reserved row —
+ while the loser is adopting it for codex. That is the strongest case, because
+ the guard's ``agent_backend`` predicate is then satisfied and only its
+ ``coalesce(native_session_id,'') = ''`` predicate can reject the write: a fix
+ that re-asserted just the backend half would still corrupt the row here.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ # Reserved for the OpenCode Agent with both pinnable settings marked
+ # EXPLICIT, and never bound.
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:race_cross_backend",
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ model="anthropic/claude-sonnet-4",
+ reasoning_effort="medium",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ROUTE_SNAPSHOT_SELECT,
+ # The winner: the reserved row's own OpenCode Agent binds the native id
+ # OpenCode just handed it. Same backend, same identity, pins untouched —
+ # exactly what a same-backend first bind persists.
+ values={
+ "id": reserved_id,
+ "native_session_id": "native-winner",
+ "status": "active",
+ "updated_at": "2026-07-28T00:00:01Z",
+ "last_active_at": "2026-07-28T00:00:01Z",
+ },
+ )
+
+ # Caller X: resolved a Codex Agent for this row and binds the native id it
+ # believes it is the first to write.
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="native-x",
+ vibe_agent_id="agent-codex",
+ vibe_agent_name="nightly-codex",
+ vibe_agent_backend="codex",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing bind never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound == reserved_id
+ assert row is not None
+ assert row["native_session_id"] == "native-winner", (
+ f"the losing caller overwrote the winner's write-once native id with "
+ f"{row['native_session_id']!r}; the row now names a conversation the "
+ "backend that produced the transcript never opened"
+ )
+ assert row["agent_backend"] == "opencode", (
+ f"the losing caller relabelled a row that was bound during its window to "
+ f"{row['agent_backend']!r}; the winner's transcript is now attributed to a "
+ "backend that never produced it"
+ )
+ assert row["agent_variant"] == "opencode"
+ assert row["agent_id"] == "agent-opencode", (
+ "the losing caller applied its own Agent identity on top of the winner"
+ )
+ assert row["agent_name"] == "review-opencode"
+ assert row["model"] == "anthropic/claude-sonnet-4", (
+ f"the losing caller cleared the winner's model to {row['model']!r}; the "
+ "winner bound this row on its own backend, so its pins are still valid"
+ )
+ assert row["reasoning_effort"] == "medium", (
+ f"the losing caller cleared the winner's reasoning effort to "
+ f"{row['reasoning_effort']!r}"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ "the losing caller dropped the winner's explicit-override marker, so the "
+ "next turn treats the winner's pinned settings as defaults it may overwrite"
+ )
+
+
+#: The whole row a first-bind winner owns, asserted column by column by both
+#: same-backend halves below. ``native_session_id`` is only the first entry.
+def _assert_first_bind_winner_row_intact(
+ row: dict,
+ *,
+ case: str,
+ agent_variant: str,
+) -> None:
+ """Assert EVERY column the first-bind winner owns is exactly as it committed it.
+
+ Factored out so the two same-backend halves cannot drift into checking
+ different subsets of the row. ``agent_variant`` is the only expectation that
+ differs between them (the loser that names a backend also rewrites the
+ variant; the one that omits it does not name the column at all).
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ assert row["native_session_id"] == "native-winner", (
+ f"[{case}] the losing caller overwrote an already-committed native id with "
+ f"{row['native_session_id']!r}; write-once was enforced by a SELECT that "
+ "reserved nothing, so the second writer won the column"
+ )
+ assert row["agent_id"] == "agent-winner-codex", (
+ f"[{case}] the losing caller wrote its own Agent id {row['agent_id']!r} over "
+ "the winner's; the row now attributes the winner's transcript to the Agent "
+ "that LOST the race, which is the same corruption as overwriting the native "
+ "id — the native id was never the only thing the winner owns"
+ )
+ assert row["agent_name"] == "winner-codex", (
+ f"[{case}] the losing caller wrote its own Agent name {row['agent_name']!r} "
+ "over the winner's, so every surface that shows which Agent owns this "
+ "session now names the loser"
+ )
+ assert row["agent_backend"] == "codex", (
+ f"[{case}] the winner's backend became {row['agent_backend']!r}"
+ )
+ assert row["agent_variant"] == agent_variant, (
+ f"[{case}] the losing caller reset the winner's Agent variant to "
+ f"{row['agent_variant']!r}; the variant is part of the identity the winner "
+ "resolved, not a backend-derived default this caller may recompute"
+ )
+ assert row["model"] == "gpt-5.5-codex", (
+ f"[{case}] a same-backend bind reset the session's pinned model to "
+ f"{row['model']!r}"
+ )
+ assert row["reasoning_effort"] == "xhigh", (
+ f"[{case}] a same-backend bind reset the session's pinned reasoning effort "
+ f"to {row['reasoning_effort']!r}"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ f"[{case}] the losing caller dropped the winner's explicit-override marker "
+ f"(now {stored_metadata.get(SESSION_SETTINGS_OVERRIDE_KEY)!r}), so the next "
+ "turn treats the winner's pinned settings as defaults it may overwrite"
+ )
+ assert row["status"] == "active", (
+ f"[{case}] the winner's status became {row['status']!r}"
+ )
+ assert row["updated_at"] == "2026-07-28T00:00:01Z", (
+ f"[{case}] the losing caller stamped its own updated_at "
+ f"({row['updated_at']!r}) over the winner's; the row now claims it was last "
+ "written by the call that changed nothing"
+ )
+ assert row["last_active_at"] == "2026-07-28T00:00:01Z", (
+ f"[{case}] the losing caller stamped its own last_active_at "
+ f"({row['last_active_at']!r}) over the winner's, so activity ordering and "
+ "any recency-based sweep now date this session from the losing call"
+ )
+
+
+#: What the winning connection commits in both same-backend halves: a DIFFERENT
+#: Agent identity from the losing caller's, and timestamps far enough from
+#: ``_utc_now_iso()`` (which renders microseconds and ``+00:00``) that a stale
+#: caller's stamp can never be mistaken for the winner's.
+def _same_backend_winner_values(reserved_id: str, *, agent_variant: str) -> dict:
+ return {
+ "id": reserved_id,
+ "native_session_id": "native-winner",
+ "agent_id": "agent-winner-codex",
+ "agent_name": "winner-codex",
+ "agent_variant": agent_variant,
+ "status": "active",
+ "updated_at": "2026-07-28T00:00:01Z",
+ "last_active_at": "2026-07-28T00:00:01Z",
+ }
+
+
+def _reserve_same_backend_race_row(
+ service, tmp_path: Path, *, anchor: str, scope_key: str = "slack::channel::C123"
+) -> str:
+ """A reserved Codex row with NON-NULL pins and the override marker set.
+
+ The pins and the marker are real values on purpose: asserting them survive is
+ vacuous against a fixture that left them ``None`` / empty.
+
+ ``scope_key`` is a parameter because the legacy-scope twin
+ (``bind_agent_session``, HFR-254) resolves its row FROM a scope key and so
+ needs the 2-part form ``slack::C4``: a 3-part key makes
+ ``resolve_scope_from_legacy_key`` upsert the scope, which takes the write lock
+ before the window opens. Resolving it here pre-creates the scope so the call
+ under test only SELECTs it. The by-id callers (HFR-251) never resolve a key at
+ all, so the default is kept for them.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY
+
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, scope_key, now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ return create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-reserved-codex",
+ agent_name="reserved-codex",
+ model="gpt-5.5-codex",
+ reasoning_effort="xhigh",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+
+def test_native_bind_by_id_loses_a_concurrent_same_backend_first_bind(tmp_path: Path) -> None:
+ """HFR-251, write-once half — ``_set_native_once`` is a read, not a reservation.
+
+ Same window, the other branch. The ordinary same-backend first bind enforced
+ write-once by SELECTing ``native_session_id`` and, on finding it empty, adding
+ the native id to an UPDATE guarded only by ``id`` + ``status != 'archived'``.
+ Between that SELECT and that UPDATE the row is unlocked, so a second connection
+ can bind it — and the stale caller then overwrites a native id that was already
+ committed. A rule enforced by a preceding SELECT is not write-once; the write
+ has to be rejected by the statement's own predicate.
+
+ A SERIAL PRE-BOUND TEST CANNOT OBSERVE THIS either: with the native already
+ present when the call starts, ``_set_native_once`` returns False and the native
+ is simply never added to the UPDATE, which is
+ ``test_bind_agent_session_survives_concurrent_insert``'s shape and is green
+ without any predicate. The competing bind must commit after that read.
+
+ THE INVARIANT IS "LOSING THE RACE DESTROYS NOTHING THE WINNER OWNS", NOT "THE
+ NATIVE ID SURVIVES". The earlier version of this test asserted the winner's
+ native id (plus the pins and marker no branch here touches) and stopped —
+ which is exactly why a second defect survived a review round. The first fix
+ added a predicate to the first-bind statement, so the native id was safe, but
+ the rowcount-0 path then FELL THROUGH to the function's final unguarded UPDATE
+ and re-applied the losing caller's stale snapshot: the winner's ``agent_id`` /
+ ``agent_name`` / ``agent_variant`` / ``status`` / ``updated_at`` /
+ ``last_active_at``, overwritten, while the native id was dutifully preserved.
+ A row can be corrupted without its native id moving. So this asserts the WHOLE
+ row the winner owns, column by column.
+
+ THIS HALF: the loser NAMES the same backend the winner is on (both ``codex``),
+ so the guard has nothing but the native predicate to stand on. It is also one
+ of the two routes through the old fall-through conditional, which dropped the
+ identity columns only when ``requested_backend != winner_backend``: equal
+ backends, so it did not fire. The other route — a caller supplying no backend
+ at all, where the comparison cannot fire — is
+ ``test_native_bind_by_id_loses_a_concurrent_first_bind_without_a_requested_backend``.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ reserved_id = _reserve_same_backend_race_row(
+ service, tmp_path, anchor="slack_C123:race_same_backend"
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_WRITE_ONCE_SELECT,
+ # The winner: a DIFFERENT Codex Agent than the loser resolved, with its
+ # own variant and its own timestamps.
+ values=_same_backend_winner_values(reserved_id, agent_variant="codex-reviewer"),
+ )
+
+ # Caller X: resolved its own Codex Agent for this row and names the backend
+ # explicitly — the same one the winner is on.
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="native-x",
+ vibe_agent_id="agent-loser-codex",
+ vibe_agent_name="loser-codex",
+ vibe_agent_backend="codex",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing bind never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound == reserved_id
+ assert row is not None
+ _assert_first_bind_winner_row_intact(
+ row,
+ case="loser names the winner's own backend",
+ # The loser named a backend, so its stale snapshot also carried
+ # agent_variant = requested_backend ("codex") — the winner's variant is what
+ # must still be here.
+ agent_variant="codex-reviewer",
+ )
+
+
+def test_native_bind_by_id_loses_a_concurrent_first_bind_without_a_requested_backend(
+ tmp_path: Path,
+) -> None:
+ """HFR-251, the sharp half — no backend named, so no comparison can save the row.
+
+ Same window and same branch as
+ ``test_native_bind_by_id_loses_a_concurrent_same_backend_first_bind``, with the
+ one difference that makes it the sharpest case: this caller omits
+ ``vibe_agent_backend`` entirely. That is an ordinary call — the parameter is
+ optional, and a caller that only knows "this Agent id/name produced this native
+ id" leaves the row's backend alone.
+
+ WHY IT IS SHARPER. The first fix guarded the first-bind statement with
+ ``coalesce(native_session_id,'') = ''``, so the native id was safe, and then let
+ the rowcount-0 path FALL THROUGH to the function's final unguarded UPDATE,
+ dropping the identity columns only ``if requested_backend and requested_backend
+ != winner_backend``. With no backend supplied ``requested_backend`` is ``None``,
+ so that comparison cannot fire AT ALL — not "compares equal", but never
+ evaluated past the falsy guard — and the losing caller's stale ``agent_id`` /
+ ``agent_name`` / ``status`` / ``updated_at`` / ``last_active_at`` landed on top
+ of the winner, with the winner's native id preserved underneath.
+
+ THE INVARIANT IS "LOSING THE RACE DESTROYS NOTHING THE WINNER OWNS", NOT "THE
+ NATIVE ID SURVIVES". The earlier version of the sibling test asserted only the
+ native id, which is precisely how this survived a round: the row was corrupted
+ with its write-once column intact. So this asserts the WHOLE row the winner
+ owns, column by column, and the columns that move here are the identity and
+ timestamp columns — never the native id.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ reserved_id = _reserve_same_backend_race_row(
+ service, tmp_path, anchor="slack_C123:race_no_backend"
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_WRITE_ONCE_SELECT,
+ # The winner keeps the reserved row's variant here: this loser never
+ # names the column, so a differing variant would prove nothing about
+ # THIS route and would only blur which columns the defect moves.
+ values=_same_backend_winner_values(reserved_id, agent_variant="codex"),
+ )
+
+ # Caller X: its own Agent identity, and NO backend at all.
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="native-x",
+ vibe_agent_id="agent-loser-codex",
+ vibe_agent_name="loser-codex",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing bind never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound == reserved_id
+ assert row is not None
+ _assert_first_bind_winner_row_intact(
+ row,
+ case="loser omits vibe_agent_backend",
+ agent_variant="codex",
+ )
+
+
+# --- HFR-252: the archive fast-path read is a fast path, and the predicate is the guard ---
+#
+# GREEN ON THE CURRENT HEAD, AND THAT IS THE POINT. These two are proofs, not
+# red-green regressions: the third read in ``bind_agent_session_by_id`` (the status
+# SELECT that returns early on ``archived``) has the same read-then-write SHAPE as
+# the two windows HFR-251 closed, but unlike those it never decided a write. Every
+# UPDATE in the function already re-asserts ``status != 'archived'``, so a late
+# archive turns the write into a no-op instead of corrupting the row. What was
+# missing was not a fix but EVIDENCE -- nothing failed if a future edit dropped one
+# of those predicates and left the SELECT to "guard" the write. These tests are that
+# evidence: each was confirmed to fail with the predicate removed from the statement
+# it covers.
+#
+# The competing write is the real one: the exact column set ``archive_session``
+# commits (``status`` + ``agent_status`` + the ``archived:<id>`` anchor vacation),
+# committed by a genuinely separate connection inside the window.
+
+
+def _archive_write(session_id: str) -> dict:
+ """The columns ``archive_session`` commits, as a competing-write payload.
+
+ Mirrors ``storage/workbench_sessions_service.py::archive_session`` step 1 --
+ including the ``archived:<id>`` anchor vacation, so a caller that wrongly wrote
+ over the archive would also be seen re-anchoring the row onto the live thread.
+ """
+ return {
+ "id": session_id,
+ "status": "archived",
+ "agent_status": "idle",
+ "session_anchor": f"archived:{session_id}",
+ "updated_at": "2026-07-28T00:00:01Z",
+ }
+
+
+def test_native_bind_by_id_cannot_resurrect_a_session_archived_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-252 — a late bind loses to an archive that commits after the status read.
+
+ The hazard: ``bind_agent_session_by_id`` refuses archived rows from a SELECT at
+ the top of the function, and that read reserves nothing (pysqlite opens no
+ transaction for a bare SELECT; SQLite takes the write lock at the UPDATE). A
+ turn that was still finishing when the user archived the session — the cancel is
+ best-effort/background — can therefore pass the read and then have the archive
+ commit underneath it. Its ``values`` carry ``status='active'``, so an unguarded
+ write would resurrect a terminal row, bind a native id into it, and leave it
+ re-anchored to the live thread.
+
+ Why it is safe, and why this test is a PROOF rather than a regression: the
+ ``status != 'archived'`` predicate on the statement — not the read — is the
+ guard. The row is still unbound, so this call exits through the FIRST-BIND
+ statement: its ``status != 'archived'`` predicate matches no row, ``rowcount`` is
+ 0, the branch re-reads the status and returns ``None`` without reaching the final
+ UPDATE. Green on the current head; it fails the moment that predicate is dropped
+ from the first-bind statement (verified).
+
+ Same-backend interleaving on purpose, so the write-once predicate on that
+ statement is SATISFIED (the row has no native) and the status predicate is the
+ only thing standing between the caller and the archived row.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:race_archive_status",
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ native_session_id="",
+ workdir=str(tmp_path),
+ )
+
+ # The user archives the session the instant after the fast-path read says
+ # "not archived".
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_STATUS_FAST_PATH_SELECT,
+ values=_archive_write(reserved_id),
+ )
+
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="native-late",
+ workdir=str(tmp_path),
+ vibe_agent_id="agent-opencode",
+ vibe_agent_name="review-opencode",
+ vibe_agent_backend="opencode",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing "
+ "about the read — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound is None, (
+ f"the late bind reported success ({bound!r}) on a session archived during "
+ "its window; the caller will now keep polling a terminal session"
+ )
+ assert row is not None
+ assert row["status"] == "archived", (
+ f"the late bind flipped a terminal session back to {row['status']!r}; the "
+ "archive the user asked for did not stick"
+ )
+ assert not (row["native_session_id"] or ""), (
+ f"the late bind wrote native id {row['native_session_id']!r} into an "
+ "archived row, re-attaching a live backend conversation to a dead session"
+ )
+ assert row["session_anchor"] == f"archived:{reserved_id}", (
+ "the late bind undid the archive's anchor vacation, so the next inbound "
+ "message on that thread resolves to the archived row"
+ )
+ assert row["agent_status"] == "idle", (
+ "the late bind reopened the archived row's running indicator"
+ )
+
+
+def test_native_bind_by_id_cannot_adopt_a_session_archived_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-252, adoption half — the archive also beats the cross-backend adopt.
+
+ Same window one statement later. The adopt branch is decided from the route
+ snapshot (unbound + on another backend) and applies the whole backend identity
+ in ONE statement: new ``agent_backend`` / ``agent_variant``, cleared ``model`` /
+ ``reasoning_effort`` and their explicit-override marker, plus the native id. If
+ the archive commits after that snapshot, an unguarded adopt would relabel and
+ strip the route of a terminal row on top of resurrecting it.
+
+ Also a PROOF, not a regression: the adopt statement carries
+ ``status != 'archived'`` alongside its write-once and backend predicates, so it
+ matches no row; the branch then re-reads the status, sees ``archived``, and
+ returns ``None`` instead of falling through to the unconditional update. Green
+ on the current head; it fails with the status predicate removed from the adopt
+ statement.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:race_archive_adopt",
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ model="anthropic/claude-sonnet-4",
+ reasoning_effort="medium",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ROUTE_SNAPSHOT_SELECT,
+ values=_archive_write(reserved_id),
+ )
+
+ bound = service.bind_agent_session_by_id(
+ session_id=reserved_id,
+ native_session_id="native-late",
+ vibe_agent_id="agent-codex",
+ vibe_agent_name="nightly-codex",
+ vibe_agent_backend="codex",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the adoption window, so this test proved "
+ "nothing — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound is None, (
+ f"the adoption reported success ({bound!r}) on a session archived during "
+ "its window"
+ )
+ assert row is not None
+ assert row["status"] == "archived", (
+ f"the adoption flipped a terminal session back to {row['status']!r}"
+ )
+ assert not (row["native_session_id"] or ""), (
+ f"the adoption wrote native id {row['native_session_id']!r} into an "
+ "archived row"
+ )
+ assert row["agent_backend"] == "opencode", (
+ f"the adoption relabelled an archived row to {row['agent_backend']!r}; the "
+ "archived transcript is now attributed to a backend that never produced it"
+ )
+ assert row["agent_variant"] == "opencode"
+ assert row["agent_id"] == "agent-opencode", (
+ "the adoption applied its own Agent identity to an archived row"
+ )
+ assert row["agent_name"] == "review-opencode"
+ assert row["model"] == "anthropic/claude-sonnet-4", (
+ f"the adoption cleared the archived row's pinned model to {row['model']!r}; "
+ "a fork or restore of this session would lose the settings it ran with"
+ )
+ assert row["reasoning_effort"] == "medium"
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ "the adoption dropped the archived row's explicit-override marker"
+ )
+ assert row["session_anchor"] == f"archived:{reserved_id}", (
+ "the adoption undid the archive's anchor vacation"
+ )
+
+
+def test_native_bind_by_id_idempotent_rebind_cannot_resurrect_an_archived_session(
+ tmp_path: Path,
+) -> None:
+ """HFR-252, final-statement half — the harmless re-bind is the one that resurrects.
+
+ The THIRD statement needs its own case, because the two above never reach it: an
+ unbound row exits through the first-bind statement, and a lost adoption returns
+ early. The final UPDATE is reached when the row already stores the SAME native id
+ the caller is re-binding — an idempotent re-bind, the shape a retried or
+ duplicated turn-start emits — because ``_set_native_once`` then declines and the
+ native is simply left out of the write.
+
+ That is the dangerous shape: with nothing to write-once and no backend change,
+ the statement is a bare ``id`` match carrying ``status='active'``. If the archive
+ commits after the fast-path read, the most innocuous call in the function is the
+ one that resurrects a terminal session. Its ``status != 'archived'`` predicate is
+ what stops it.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ bound_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C123:race_archive_rebind",
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ native_session_id="native-live",
+ workdir=str(tmp_path),
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_STATUS_FAST_PATH_SELECT,
+ values=_archive_write(bound_id),
+ )
+
+ bound = service.bind_agent_session_by_id(
+ session_id=bound_id,
+ native_session_id="native-live",
+ vibe_agent_id="agent-opencode",
+ vibe_agent_name="review-opencode",
+ vibe_agent_backend="opencode",
+ )
+ row = service.get_agent_session_by_id(bound_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing — "
+ "the keyed read is no longer the SQL the code emits"
+ )
+ assert bound is None, (
+ f"the idempotent re-bind reported success ({bound!r}) on a session archived "
+ "during its window"
+ )
+ assert row is not None
+ assert row["status"] == "archived", (
+ f"an idempotent re-bind flipped a terminal session back to {row['status']!r}; "
+ "the archive the user asked for did not stick"
+ )
+ assert row["session_anchor"] == f"archived:{bound_id}", (
+ "the re-bind undid the archive's anchor vacation, so the next inbound "
+ "message on that thread resolves to the archived row"
+ )
+ assert row["agent_status"] == "idle"
+
+
+# --- HFR-253 / HFR-254: the other two read-then-write session writers ---
+#
+# HFR-251 closed the two windows in ``bind_agent_session_by_id``. The two writers
+# below have the SAME shape and were left untouched by that round: ``_claim_anchor_row``
+# (added by the same PR) re-asserted nothing at all, and ``bind_agent_session`` --
+# the legacy-scope twin of ``bind_agent_session_by_id`` -- carried neither the
+# write-once nor the archive predicate while unconditionally setting
+# ``status='active'``.
+#
+# THE SCOPE KEY IS PART OF THE MECHANISM, not incidental. Both entry points start
+# with ``resolve_scope_from_legacy_key``, and for a THREE-part key
+# (``slack::channel::C1``) that helper calls ``upsert_scope``, which WRITES -- so the
+# caller's transaction already holds SQLite's write lock by the time the decision
+# read runs, and a competing connection cannot commit inside the window at all (it
+# gets ``database is locked`` after the busy timeout). The window only exists for the
+# TWO-part form ``slack::C1`` with the scope already present, where the resolve is a
+# pure SELECT. That is the form ``core/message_context.py::build_context_session_key``
+# produces for every ordinary channel / thread turn (the three-part form is reserved
+# for typed user scopes), so it is the production shape, not a contrived one. Both
+# tests below use it, and both were confirmed to raise ``OperationalError: database
+# is locked`` instead of corrupting anything when re-run with a three-part key.
+
+#: The decision read of ``_claim_anchor_row``: ``_row_for_scope_anchor``. Everything
+#: that branch decides -- "unbound, so relabel it and replace its whole route" --
+#: comes from this row.
+_ANCHOR_DECISION_SELECT = (
+ "SELECT agent_sessions.id, agent_sessions.agent_backend, agent_sessions.agent_variant, "
+ "agent_sessions.native_session_id FROM agent_sessions WHERE agent_sessions.scope_id = ? "
+ "AND agent_sessions.session_anchor = ? AND agent_sessions.status != ? "
+ "ORDER BY agent_sessions.last_active_at DESC, agent_sessions.id DESC LIMIT ? OFFSET ?"
+)
+
+
+def test_ensure_agent_session_id_cannot_relabel_a_row_bound_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-253 — ``_claim_anchor_row``'s relabel UPDATE re-asserted nothing.
+
+ THE PRODUCTION STORY. Thread ``slack_C1`` holds row R, reserved for the Codex
+ Agent and not yet bound. The channel's Agent is switched to Claude, so the next
+ turn calls ``ensure_agent_session_id(agent_name="claude", ...)``; the finder
+ filters on backend, misses R, and ``get_or_create_agent_session_row`` resolves it
+ on the CONSTRAINT key instead. ``_claim_anchor_row`` reads R, sees no native id,
+ and takes the unbound branch: relabel to Claude and replace the whole route.
+ Meanwhile the still-finishing Codex turn commits its native id onto R.
+
+ THE DEFECT IS THE WINDOW. The relabel was ``UPDATE ... WHERE id = ?`` and
+ nothing else -- no ``coalesce(native_session_id,'') = ''``, no
+ ``agent_backend = <the backend it decided against>``, no ``status != 'archived'``.
+ Its sibling ``bind_agent_session_by_id`` got all three in HFR-251. So the stale
+ caller relabelled a row that was no longer unbound, and the row came out
+ ``agent_backend='claude'`` while holding the Codex native id -- a Claude-owned
+ session pointing at a Codex conversation, with the Codex Agent's identity, model
+ and reasoning effort wiped and their explicit-override marker cleared.
+
+ A SERIAL TEST CANNOT OBSERVE THIS. Bind R before the call and
+ ``_claim_anchor_row``'s own read sees the native, taking the SUPERSEDE branch
+ instead (``test_agent_session_anchor_supersede_...``), which is green over the
+ unguarded UPDATE. The competing bind has to land INSIDE the window, committed by
+ a real second connection.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ # Two-part scope key, created up front, so the resolve inside the call
+ # under test is a pure SELECT and takes no write lock. See the note above.
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C1", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C1",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ model="gpt-5.5-codex",
+ reasoning_effort="xhigh",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ # The still-finishing Codex turn commits the native id Codex just handed it,
+ # the instant after the relabel decision was read.
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ANCHOR_DECISION_SELECT,
+ values={
+ "id": reserved_id,
+ "native_session_id": "codex-native-uuid",
+ "status": "active",
+ "updated_at": "2026-07-28T00:00:01Z",
+ "last_active_at": "2026-07-28T00:00:01Z",
+ },
+ )
+
+ # The Claude turn on the same thread, working from the stale snapshot.
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::C1",
+ agent_name="claude",
+ session_anchor="slack_C1",
+ workdir=str(tmp_path),
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing bind never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert resolved == reserved_id, (
+ f"the loser answered {resolved!r}; a bound LIVE winner is a usable session, so "
+ "the row's id is still the right answer here — the caller's turn resolves onto "
+ "the winner's row instead of getting no session at all. Only an ARCHIVED "
+ "winner (the other half) has no id to give, because the archive is terminal"
+ )
+ assert row is not None
+ assert row["native_session_id"] == "codex-native-uuid", (
+ f"the relabel overwrote the winner's write-once native id with "
+ f"{row['native_session_id']!r}"
+ )
+ assert row["agent_backend"] == "codex", (
+ f"the relabel moved a row that was bound during its window to "
+ f"{row['agent_backend']!r}; the session now claims a backend that never "
+ f"produced its conversation, while still holding native id "
+ f"{row['native_session_id']!r}"
+ )
+ assert row["agent_variant"] == "codex"
+ assert row["agent_id"] == "agent-codex", (
+ "the relabel replaced the winner's Agent identity"
+ )
+ assert row["agent_name"] == "nightly-codex"
+ assert row["model"] == "gpt-5.5-codex", (
+ f"the relabel cleared the winner's pinned model to {row['model']!r}; the "
+ "winner bound this row on its own backend, so its pins are still valid"
+ )
+ assert row["reasoning_effort"] == "xhigh", (
+ f"the relabel cleared the winner's reasoning effort to "
+ f"{row['reasoning_effort']!r}"
+ )
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ "the relabel dropped the winner's explicit-override marker, so the next turn "
+ "treats the winner's pinned settings as inherited defaults it may overwrite"
+ )
+
+
+def test_ensure_agent_session_id_cannot_relabel_a_row_archived_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-253, archive half — the relabel also has to lose to a terminal archive.
+
+ Same window, the other competing write. ``_row_for_scope_anchor`` deliberately
+ filters ``status != 'archived'`` because an archive VACATES the anchor, so the
+ branch is only ever decided about a live row. The read reserves nothing, though,
+ so the archive can commit right after it — and the relabel then rewrote the whole
+ route of a terminal row, leaving the archived transcript attributed to a backend
+ that never produced it.
+
+ THE ROW IS ONLY HALF THE ANSWER. Guarding the UPDATE stops the relabel, but the
+ lost-race path then still RETURNED the row id — the same id whose anchor the
+ archive just vacated. An archive is terminal, so that is not a usable session,
+ and the return value is what production consumes: nothing re-resolves after this
+ call. ``BaseAgent.ensure_agent_session_id`` pins any non-empty answer straight
+ into ``context.platform_specific['agent_session_id']``
+ (``modules/agents/base.py``, the ``if not agent_session_id: return None`` gate and
+ the ``payload["agent_session_id"] = agent_session_id`` write directly under it),
+ so a returned archived id becomes the row the whole turn reports against. The two
+ sibling bind paths (``bind_agent_session_by_id`` / ``bind_agent_session``) already
+ answer ``None`` for an archived winner; this path must too. The end-to-end proof
+ that the pin then cannot happen is
+ ``test_ensure_agent_session_id_archive_race_never_pins_an_agent_session_id``.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_OVERRIDE_KEY, explicit_override_names
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C2", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C2",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ model="gpt-5.5-codex",
+ reasoning_effort="xhigh",
+ native_session_id="",
+ workdir=str(tmp_path),
+ metadata={SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"]},
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ANCHOR_DECISION_SELECT,
+ values=_archive_write(reserved_id),
+ )
+
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::C2",
+ agent_name="claude",
+ session_anchor="slack_C2",
+ workdir=str(tmp_path),
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ with service.engine.connect() as conn:
+ stored_ids = [str(value) for value in conn.execute(select(agent_sessions.c.id)).scalars()]
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing — "
+ "the keyed read is no longer the SQL the code emits"
+ )
+ assert stored_ids == [reserved_id], (
+ f"the lost relabel minted a second row {stored_ids!r}; 'no usable session' "
+ "is answered with None, not by creating a fresh row from the same stale "
+ "snapshot the relabel was already refused for"
+ )
+ assert resolved is None, (
+ f"the lost relabel returned {resolved!r} for a session that was ARCHIVED "
+ "inside its window; an archive is terminal and vacates the anchor, so there "
+ "is no usable session to hand back. The caller does not re-resolve: "
+ "BaseAgent.ensure_agent_session_id pins any non-empty answer into "
+ "context.platform_specific['agent_session_id'], so this id becomes the row "
+ "the turn reports against — while every read path (including this "
+ "function's own finder) filters the row out as archived. The sibling binds "
+ "bind_agent_session / bind_agent_session_by_id already return None here"
+ )
+ assert resolved != reserved_id, (
+ "the archived row's id must never be the answer, not even as a 'the caller "
+ "will notice' fallback — nothing downstream re-decides"
+ )
+ assert row is not None
+ assert row["status"] == "archived", (
+ f"the relabel flipped a terminal session back to {row['status']!r}"
+ )
+ assert row["agent_backend"] == "codex", (
+ f"the relabel moved an archived row to {row['agent_backend']!r}; the archived "
+ "transcript is now attributed to a backend that never produced it"
+ )
+ assert row["agent_variant"] == "codex"
+ assert row["agent_id"] == "agent-codex"
+ assert row["agent_name"] == "nightly-codex"
+ assert row["model"] == "gpt-5.5-codex", (
+ f"the relabel cleared the archived row's pinned model to {row['model']!r}; a "
+ "fork or restore of this session would lose the settings it ran with"
+ )
+ assert row["reasoning_effort"] == "xhigh"
+ stored_metadata = json.loads(row["metadata_json"] or "{}")
+ assert set(explicit_override_names(stored_metadata)) == {"model", "reasoning_effort"}, (
+ "the relabel dropped the archived row's explicit-override marker"
+ )
+
+
+def test_ensure_agent_session_id_archive_race_never_pins_an_agent_session_id(
+ tmp_path: Path,
+) -> None:
+ """HFR-253, consuming half — the archived id must never reach the turn's context.
+
+ The storage-level assertion (``resolved is None`` in
+ ``test_ensure_agent_session_id_cannot_relabel_a_row_archived_inside_its_window``)
+ only matters because of what the CALLER does with a non-empty answer, so that
+ step is proved here rather than argued: the real production chain
+ ``BaseAgent.ensure_agent_session_id`` -> ``SessionsFacade`` ->
+ ``SessionsStore`` -> ``SQLiteSessionsService`` is driven in-process, with the
+ archive committed by a real second connection inside ``_claim_anchor_row``'s
+ window, and the assertion is on ``context.platform_specific``.
+
+ WHY THE PIN IS THE HAZARD. ``BaseAgent.ensure_agent_session_id`` gates on
+ ``if not agent_session_id: return None`` and, one line later, writes
+ ``payload["agent_session_id"] = agent_session_id`` into the context. There is no
+ later re-resolve anywhere on that path — the pinned id is what every mirrored
+ reply, terminal notify and Show Page write for the rest of the turn is filed
+ under. So "return the winner's id even though the winner archived it" is not a
+ stale answer the caller corrects; it is the caller's final answer, naming a
+ terminal row that every read path already filters out.
+
+ The context keeps a sentinel ``agent_session_id`` from the ordinary build step,
+ so this distinguishes "not pinned" from "pinned to nothing".
+ """
+ from modules.agents.base import BaseAgent
+
+ class _PinningAgent(BaseAgent):
+ """Minimal concrete BaseAgent: real method lookup, no controller."""
+
+ def __init__(self, sessions) -> None:
+ self.sessions = sessions
+ self.name = "claude"
+
+ async def handle_message(self, request): # pragma: no cover - abstract stub
+ return None
+
+ db_path = tmp_path / "vibe.sqlite"
+ store = SessionsStore(tmp_path / "sessions.json")
+ try:
+ service = store._service
+ with service.engine.begin() as conn:
+ # Two-part key, scope pre-created: the resolve inside the call under test
+ # is a pure SELECT, so the window is open. See the note above this block.
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C5", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C5",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ native_session_id="",
+ workdir=str(tmp_path),
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ANCHOR_DECISION_SELECT,
+ values=_archive_write(reserved_id),
+ )
+
+ agent = _PinningAgent(SessionsFacade(store))
+ context = SimpleNamespace(platform_specific={"agent_session_id": "from_build"})
+ request = SimpleNamespace(
+ context=context,
+ session_key="slack::C5",
+ base_session_id="slack_C5",
+ vibe_agent_id=None,
+ vibe_agent_name=None,
+ )
+
+ pinned = agent.ensure_agent_session_id(request)
+ finally:
+ store.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing — "
+ "the keyed read is no longer the SQL the code emits"
+ )
+ assert pinned is None, (
+ f"BaseAgent.ensure_agent_session_id answered {pinned!r} for a session archived "
+ "inside the storage window; the whole turn now runs against a terminal row"
+ )
+ assert context.platform_specific["agent_session_id"] == "from_build", (
+ f"the archived row id was pinned into the turn's context as "
+ f"{context.platform_specific['agent_session_id']!r}; every mirrored reply and "
+ "terminal notify for this turn would be filed under a session that is "
+ "archived, and nothing later re-resolves it"
+ )
+ assert reserved_id not in str(context.platform_specific), (
+ f"the archived id {reserved_id} reached the turn context by another key"
+ )
+
+
+def test_bind_agent_session_keeps_the_native_of_a_row_bound_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-254 — ``bind_agent_session``'s final UPDATE broke write-once.
+
+ The legacy-scope twin of ``bind_agent_session_by_id``, and it was missed by
+ HFR-251/252. ``_set_native_once`` is a preceding SELECT, and the UPDATE that acted
+ on its answer carried neither ``coalesce(native_session_id,'') = ''`` nor
+ ``status != 'archived'`` while unconditionally setting ``status='active'``. So a
+ single competing commit inside that window did TWO things at once: it lost its
+ write-once native id to the stale caller, and it had its terminal archive undone.
+
+ The competing write is the real pair — the native id a concurrent binder commits
+ plus the archive column set (see ``_archive_write``) — because that is what makes
+ both halves observable in one interleaving: the caller reports SUCCESS and leaves
+ ``status='active'`` with ``native_session_id='loser-native'``.
+
+ A SERIAL TEST CANNOT OBSERVE EITHER HALF. Pre-bind the row and
+ ``_set_native_once`` returns False, so the native is never added to the write
+ (``test_bind_agent_session_survives_concurrent_insert``'s shape); pre-archive it
+ and ``_find_agent_session_row_id`` skips the row entirely. Both windows need a
+ real second connection committing after the read.
+
+ THE IDENTITY HALF OF THE SAME WINDOW is
+ ``test_bind_agent_session_loses_a_concurrent_same_backend_first_bind``. This
+ test's winner is ARCHIVED, so the loser's fall-through write is refused
+ wholesale by the final UPDATE's ``status != 'archived'`` predicate — which hides
+ everything that fall-through does to a LIVE winner. Keep the two together.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ # Two-part key with the scope already present: the resolve is a pure
+ # SELECT, so the window is open. See the note above this block.
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C3", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ reserved_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C3",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ native_session_id="",
+ workdir=str(tmp_path),
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_WRITE_ONCE_SELECT,
+ # One commit, both halves: the winner binds its native id AND the session
+ # is archived (the user's ``/archive``, whose cancel is best-effort, so a
+ # still-finishing turn can still be mid-bind here).
+ values={**_archive_write(reserved_id), "native_session_id": "winner-native"},
+ )
+
+ bound = service.bind_agent_session(
+ scope_key="slack::C3",
+ agent_name="codex",
+ session_anchor="slack_C3",
+ native_session_id="loser-native",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing write never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert row is not None
+ assert row["native_session_id"] == "winner-native", (
+ f"the losing caller overwrote an already-committed native id with "
+ f"{row['native_session_id']!r}; write-once was enforced by a SELECT that "
+ "reserved nothing, so the second writer won the column"
+ )
+ assert row["status"] == "archived", (
+ f"the late bind flipped a terminal session back to {row['status']!r}; the "
+ "archive the user asked for did not stick"
+ )
+ assert bound is None, (
+ f"the late bind reported success ({bound!r}) after losing both the native id "
+ "and the row itself; the caller will keep polling a terminal session"
+ )
+ assert row["agent_status"] == "idle", (
+ "the late bind reopened the archived row's running indicator"
+ )
+
+
+def test_bind_agent_session_loses_a_concurrent_same_backend_first_bind(
+ tmp_path: Path,
+) -> None:
+ """HFR-254, identity half — the legacy-scope bind fell through onto a LIVE winner.
+
+ THE INVARIANT IS "LOSING THE RACE DESTROYS NOTHING THE WINNER OWNS", NOT "THE
+ NATIVE ID SURVIVES". The earlier version of HFR-254's coverage
+ (``test_bind_agent_session_keeps_the_native_of_a_row_bound_inside_its_window``)
+ asserted the winner's native id, its archived status and the ``None`` return,
+ and stopped there — which is why a second defect in this same function survived
+ a review round. THIS IS THE SAME CORRECTION THE TWIN ``bind_agent_session_by_id``
+ NEEDED (see the note in
+ ``test_native_bind_by_id_loses_a_concurrent_same_backend_first_bind``); the hole
+ was reintroduced here by HFR-254's own fix and had to be closed twice, once per
+ sibling.
+
+ WHAT THE ARCHIVED CASE HIDES. HFR-254 added ``coalesce(native_session_id,'')
+ = ''`` to the first-bind statement, so the native id became safe — and then let
+ the rowcount-0 path FALL THROUGH to the function's final UPDATE. That UPDATE
+ shares the same ``values`` dict, which carries ``status='active'``, both
+ timestamps, and this caller's ``agent_id`` / ``agent_name``. With an archived
+ winner the whole write is rejected by ``status != 'archived'``, so nothing moves
+ and the test stays green. With a LIVE winner — the ordinary case, two callers
+ binding the same reserved row — the predicate is satisfied and the loser stamps
+ its own Agent identity and its own timestamps over the winner's, with the
+ winner's native id dutifully preserved underneath. A row can be corrupted
+ without its native id moving.
+
+ THE WINDOW IS THE SAME ONE, and the scope key is part of the mechanism: the
+ 2-part form ``slack::C4`` makes ``resolve_scope_from_legacy_key`` a pure SELECT,
+ while a 3-part key would upsert the scope and take the write lock before the
+ window opens. The loser also omits ``workdir`` — ``bind_agent_session`` takes no
+ ``vibe_agent_backend`` at all, unlike its twin, so its whole stale snapshot is
+ the Agent id / name pair asserted here.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ reserved_id = _reserve_same_backend_race_row(
+ service,
+ tmp_path,
+ anchor="slack_C4",
+ scope_key="slack::C4",
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_WRITE_ONCE_SELECT,
+ # The winner: a DIFFERENT Codex Agent than the loser resolved, with
+ # timestamps ``_utc_now_iso()`` cannot render. It stays ACTIVE — no
+ # archive — so the final UPDATE's status predicate cannot stand in for
+ # the guard that is actually missing.
+ values=_same_backend_winner_values(reserved_id, agent_variant="codex"),
+ )
+
+ # Caller X: resolved its own Codex Agent for this row and believes it is the
+ # first to bind. Same (scope_key, agent_name, session_anchor) triple the
+ # winner's row is found by.
+ bound = service.bind_agent_session(
+ scope_key="slack::C4",
+ agent_name="codex",
+ session_anchor="slack_C4",
+ native_session_id="native-x",
+ vibe_agent_id="agent-loser-codex",
+ vibe_agent_name="loser-codex",
+ )
+ row = service.get_agent_session_by_id(reserved_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing bind never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert bound == reserved_id, (
+ f"the row is live and bound, so the loser's answer is still the session id, "
+ f"not {bound!r}"
+ )
+ assert row is not None
+ _assert_first_bind_winner_row_intact(
+ row,
+ case="legacy-scope bind loses to a live same-backend winner",
+ # ``bind_agent_session`` never names ``agent_variant``, so the winner keeps
+ # the reserved variant; a differing one would only blur which columns the
+ # defect moves.
+ agent_variant="codex",
+ )
+
+
+# --- HFR-257..260: the same shape in the TEARDOWN writers ---
+#
+# HFR-251..254 closed the four read-then-write windows in the BIND writers. The four
+# below are the rest of the set, found by enumerating every statement in
+# ``storage/session_reclaim.py`` / ``storage/agent_session_rows.py`` and on their call
+# path that acts on a decision a preceding SELECT made:
+#
+# * HFR-257 ``reclaim_bound_definitions`` -- matched the definition by id alone.
+# * HFR-258 ``_claim_anchor_row``'s SUPERSEDE branch -- matched the session by id
+# alone; HFR-253 guarded only its relabel sibling.
+# * HFR-259 ``_find_agent_session_row_id``'s placeholder relabel -- matched by id
+# alone AND returned the id it had just relabelled.
+# * HFR-260 ``_delete_agent_session_rows`` -- applied the whole teardown query's
+# predicates in the id READ and then hard-deleted by id list.
+#
+# The window is the same one throughout, and the 2-part scope key is again part of
+# the mechanism (see the HFR-253/254 note above): the teardown paths reach these
+# statements after nothing but SELECTs, so SQLite's write lock is still free.
+
+
+def _bind_definition(
+ conn, # noqa: ANN001
+ *,
+ definition_id: str,
+ session_id: str,
+ metadata: dict | None = None,
+) -> None:
+ """A scheduled task pinned to ``session_id``, in the shape reclaim reads."""
+ conn.execute(
+ run_definitions.insert().values(
+ id=definition_id,
+ definition_type="scheduled",
+ name="nightly",
+ agent_name=None,
+ session_policy="existing",
+ session_id=session_id,
+ mode="create_once",
+ message="run the nightly check",
+ prompt="run the nightly check",
+ schedule_type="cron",
+ cron="0 3 * * *",
+ enabled=1,
+ created_at="2026-07-28T00:00:00Z",
+ updated_at="2026-07-28T00:00:00Z",
+ metadata_json=json.dumps(metadata or {"origin": "cli"}),
+ )
+ )
+
+
+#: The decision read of ``reclaim_bound_definitions``: every live definition bound to
+#: the session going away. Everything the loop then writes -- pause / soft-delete, the
+#: settings snapshot, the summary counters and the teardown ledger -- is decided from
+#: this one row set.
+_RECLAIM_DECISION_SELECT = (
+ "SELECT run_definitions.id, run_definitions.definition_type, run_definitions.enabled, "
+ "run_definitions.metadata_json FROM run_definitions WHERE run_definitions.session_id = ? "
+ "AND run_definitions.deleted_at IS NULL"
+)
+
+
+def test_reclaim_leaves_a_definition_repointed_inside_its_window_alone(tmp_path: Path) -> None:
+ """HFR-257 — the reclaim UPDATE matched the definition by id and nothing else.
+
+ THE PRODUCTION STORY. A ``create_once`` task is pinned to session S. The user
+ repoints it to session S2 (``vibe task update --session``, an
+ ``upsert_scheduled_task`` full-row write) at the moment another surface tears S
+ down -- ``/new`` in the same thread, or the archive dialog. The teardown reads the
+ definitions bound to S, finds this one, and decides to pause it.
+
+ THE DEFECT IS THE WINDOW. That read reserves nothing: pysqlite emits no ``BEGIN``
+ for a bare SELECT, and the hard-delete path reaches the reclaim helper after only
+ reads, so SQLite's write lock is still free. The UPDATE was
+ ``WHERE run_definitions.id = ?`` alone, so it landed on the definition's NEW,
+ LIVE binding: the task was disabled with a pause reason naming a session it no
+ longer belongs to, and its ``session_settings_snapshot`` was overwritten with the
+ dead session's model / agent -- which is what a later ``create_once`` rebind reads,
+ so the repointed task would come back on the wrong route.
+
+ AND THE ACCOUNTING IS PART OF THE INVARIANT. Refusing the write is not enough
+ while the counters and the ledger still credit it: ``summary`` is what the archive
+ confirm dialog reports, and the ledger is what ``/new`` counts in its reply. A
+ lost write reported as "1 task paused" is the same lie as the write itself, just
+ told to the user instead of the database. All three are asserted below.
+
+ A SERIAL TEST CANNOT OBSERVE THIS. Repoint the definition BEFORE the call and the
+ reclaim's own SELECT (``session_id = S``) never returns it. The repoint has to land
+ INSIDE the window, committed by a real second connection.
+ """
+ from storage.session_reclaim import (
+ RECLAIM_PAUSE,
+ SESSION_SETTINGS_SNAPSHOT_KEY,
+ reclaim_bound_definitions,
+ session_teardown_context,
+ )
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C7", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ dying_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C7",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ model="gpt-5.5-codex",
+ native_session_id="codex-native",
+ workdir=str(tmp_path),
+ )
+ keeper_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C7:keeper",
+ agent_backend="claude",
+ agent_variant="claude",
+ agent_id="agent-claude",
+ agent_name="review-claude",
+ model="claude-opus-4",
+ native_session_id="claude-native",
+ workdir=str(tmp_path),
+ )
+ _bind_definition(conn, definition_id="def-repointed", session_id=dying_id)
+
+ # The user's repoint, committed the instant after the teardown read the
+ # bindings: same statement shape ``upsert_scheduled_task`` emits (a full-row
+ # UPDATE keyed on the definition id) and it moves the definition to a LIVE
+ # session.
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_RECLAIM_DECISION_SELECT,
+ table=run_definitions,
+ values={
+ "id": "def-repointed",
+ "session_id": keeper_id,
+ "updated_at": "2026-07-28T00:00:01Z",
+ },
+ )
+
+ # The teardown, working from the stale snapshot. ``engine.begin()`` with no
+ # write before the call is exactly how ``_delete_agent_session_rows`` reaches
+ # this helper: a resolved 2-part scope key and an id SELECT, both reads.
+ with session_teardown_context(reason="the bound agent session was cleared") as ledger:
+ with service.engine.begin() as conn:
+ summary = reclaim_bound_definitions(conn, dying_id, mode=RECLAIM_PAUSE)
+ ledger_entries = list(ledger)
+
+ with service.engine.begin() as conn:
+ definition = (
+ conn.execute(
+ select(run_definitions).where(run_definitions.c.id == "def-repointed")
+ )
+ .mappings()
+ .first()
+ )
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing repoint never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert definition is not None
+ assert definition["session_id"] == keeper_id, (
+ "the repoint itself did not survive, so the rest of this test is meaningless"
+ )
+ assert definition["enabled"] == 1, (
+ "the teardown paused a definition that had been repointed to a LIVE session "
+ "inside its window; the user's task is disabled and the session it now names "
+ "is perfectly usable"
+ )
+ assert definition["deleted_at"] is None
+ assert definition["last_error"] is None, (
+ f"the teardown stamped {definition['last_error']!r} on a definition bound to "
+ "another session, so the task now explains its state by a teardown that never "
+ "touched it"
+ )
+ stored_metadata = json.loads(definition["metadata_json"] or "{}")
+ assert SESSION_SETTINGS_SNAPSHOT_KEY not in stored_metadata, (
+ "the teardown overwrote the repointed definition's metadata with the DYING "
+ "session's settings snapshot; a later create_once rebind reads that snapshot, "
+ "so the task would silently come back on the dead session's model and agent"
+ )
+ assert stored_metadata == {"origin": "cli"}, (
+ f"the definition's metadata was rewritten to {stored_metadata!r}"
+ )
+
+ # What the function RETURNS is half the invariant: a lost write must be reported
+ # to nobody.
+ assert summary == {"paused": 0, "deleted": 0, "snapshotted": 0}, (
+ f"the returned summary {summary!r} credits a reclaim that did not happen; this "
+ "is the count the archive confirm dialog shows the user"
+ )
+ assert ledger_entries == [], (
+ f"the teardown ledger records {ledger_entries!r}; the ledger is what /new "
+ "counts in its reply, so the user is told a task was paused while it is still "
+ "enabled and pointing at a live session"
+ )
+
+
+def test_new_teardown_path_reports_only_the_definitions_it_reclaimed(tmp_path: Path) -> None:
+ """HFR-257, ``/new`` half — the same window, reached the way production reaches it.
+
+ The primary test calls the shared helper directly to assert its returned summary.
+ This one drives the real IM ``/new`` teardown: ``delete_agent_sessions`` ->
+ ``_delete_agent_session_rows`` -> ``reclaim_bound_definitions``, inside the
+ ``session_teardown_context`` the command handler opens, so the ledger the reply
+ counts is the production one. Both definitions are bound to the dying session; one
+ is repointed inside the window and one is not, so the ledger has to name exactly
+ the second.
+ """
+ from storage.session_reclaim import session_teardown_context
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C5", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ dying_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C5",
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="codex-native",
+ workdir=str(tmp_path),
+ )
+ keeper_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C5:keeper",
+ agent_backend="claude",
+ agent_variant="claude",
+ native_session_id="claude-native",
+ workdir=str(tmp_path),
+ )
+ _bind_definition(conn, definition_id="def-repointed", session_id=dying_id)
+ _bind_definition(conn, definition_id="def-staying", session_id=dying_id)
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_RECLAIM_DECISION_SELECT,
+ table=run_definitions,
+ values={
+ "id": "def-repointed",
+ "session_id": keeper_id,
+ "updated_at": "2026-07-28T00:00:01Z",
+ },
+ )
+
+ with session_teardown_context(reason="the bound agent session was cleared") as ledger:
+ removed = service.delete_agent_sessions(scope_key="slack::C5", agent_name="codex")
+ ledger_entries = list(ledger)
+
+ with service.engine.begin() as conn:
+ states = {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(run_definitions.c.id, run_definitions.c.enabled, run_definitions.c.session_id)
+ ).mappings()
+ }
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing repoint never landed inside the window, so this test proved "
+ "nothing about the race"
+ )
+ assert removed == 1, f"the dying session should still be hard-deleted, got {removed!r}"
+ assert states["def-repointed"]["enabled"] == 1, (
+ "/new paused a task that had just been repointed to another live session"
+ )
+ assert states["def-staying"]["enabled"] == 0, (
+ "the definition still bound to the dying session was NOT paused; the guard "
+ "must refuse only the write that lost, never the ordinary reclaim"
+ )
+ assert [entry["definition_id"] for entry in ledger_entries] == ["def-staying"], (
+ f"the /new reply counts {ledger_entries!r}; it must name exactly the tasks it "
+ "actually paused"
+ )
+
+
+def test_anchor_supersede_returns_the_winner_of_a_concurrent_supersede(tmp_path: Path) -> None:
+ """HFR-258 — the supersede branch matched the session by id and then INSERTed.
+
+ THE PRODUCTION STORY. Thread ``slack_C8`` holds row R: bound, with a Codex native
+ id. The channel's Agent is switched to Claude and TWO turns arrive on that thread
+ at once. Both call ``ensure_agent_session_id(agent_name="claude", ...)``, both miss
+ R in the backend-filtered finder, and both resolve it on the constraint key, where
+ ``_claim_anchor_row`` sees a bound row on another backend and takes the SUPERSEDE
+ branch: move R's anchor aside, then create a fresh row on the freed slot.
+
+ THE DEFECT IS THE WINDOW. ``_row_for_scope_anchor`` reserves nothing, so the winner
+ can move the anchor and insert its replacement before the loser's UPDATE. That
+ UPDATE was ``WHERE id = ?`` alone: it "succeeded" (rowcount 1) re-superseding an
+ already-superseded row, reported that as freeing the slot, and fell straight into
+ ``create_agent_session_row`` -- whose INSERT collided with the winner's replacement
+ on the UNIQUE ``(scope_id, session_anchor)`` index. So the loser got an
+ ``IntegrityError`` out of ``get_or_create_agent_session_row``, a function whose
+ entire contract is "resolve the one session row for this anchor, creating it once",
+ and the turn died where it should have joined the winner's session.
+
+ A SERIAL TEST CANNOT OBSERVE THIS. Supersede R first and the second caller's read
+ finds the winner's replacement row on the anchor, takes the same-backend fast path
+ and returns its id -- green over the unguarded UPDATE. The competing supersede has
+ to land INSIDE the window, and as ONE commit (anchor move + replacement insert),
+ which is what the winner's transaction really is.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ winner_replacement_id = "seswinner001"
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C8", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ superseded_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C8",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ native_session_id="codex-native-uuid",
+ workdir=str(tmp_path),
+ )
+
+ def _winner_supersedes(other_conn) -> None: # noqa: ANN001
+ """Exactly what ``_claim_anchor_row``'s supersede branch commits."""
+ other_conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == superseded_id)
+ .values(
+ session_anchor=f"slack_C8:superseded:{superseded_id}",
+ updated_at="2026-07-28T00:00:01Z",
+ )
+ )
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id=winner_replacement_id,
+ session_anchor="slack_C8",
+ agent_backend="claude",
+ agent_variant="claude",
+ agent_id="agent-claude",
+ agent_name="review-claude",
+ native_session_id="",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:01Z",
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ANCHOR_DECISION_SELECT,
+ write=_winner_supersedes,
+ )
+
+ # The losing turn, working from the stale snapshot. No IntegrityError may
+ # escape: an exception here fails the test on its own.
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::C8",
+ agent_name="claude",
+ session_anchor="slack_C8",
+ workdir=str(tmp_path),
+ )
+
+ with service.engine.begin() as conn:
+ anchor_rows = [
+ dict(row)
+ for row in conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.agent_backend)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(agent_sessions.c.session_anchor == "slack_C8")
+ ).mappings()
+ ]
+ loser_row = service.get_agent_session_by_id(superseded_id)
+ total_rows = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id)
+ ).scalars().all()
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing supersede never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert len(anchor_rows) == 1, (
+ f"the anchor slack_C8 is held by {anchor_rows!r}; exactly ONE replacement row "
+ "may exist for it — the UNIQUE (scope_id, session_anchor) index is the only "
+ "reason a second one is an IntegrityError instead of a silent duplicate"
+ )
+ assert anchor_rows[0]["id"] == winner_replacement_id, (
+ f"the anchor is held by {anchor_rows[0]['id']!r} rather than the winner's "
+ "replacement row"
+ )
+ assert resolved == winner_replacement_id, (
+ f"the loser answered {resolved!r}; a lost supersede must hand back the session "
+ "that HOLDS the anchor now, so the turn joins the winner's session instead of "
+ "inserting a second row on a slot it did not free"
+ )
+ assert loser_row is not None
+ assert loser_row["session_anchor"] == f"slack_C8:superseded:{superseded_id}", (
+ f"the loser re-superseded an already-superseded row to "
+ f"{loser_row['session_anchor']!r}; the marker is appended once, and a second "
+ "pass breaks the thread id every definition pinned to this row derives from it"
+ )
+ assert loser_row["native_session_id"] == "codex-native-uuid"
+ assert loser_row["agent_backend"] == "codex"
+ assert len(total_rows) == 2, (
+ f"the scope holds {len(total_rows)} session rows; the loser must not create a "
+ "third — the original, plus the winner's one replacement"
+ )
+
+
+#: The decision read of ``_find_agent_session_row_id``'s legacy branch: the newest
+#: live row at this (scope, anchor) whose backend / variant are still the blank or
+#: ``"default"`` placeholder. "It is a placeholder, so relabelling it in place is
+#: free" is decided entirely from this row.
+_PLACEHOLDER_DECISION_SELECT = (
+ "SELECT agent_sessions.id FROM agent_sessions WHERE agent_sessions.scope_id = ? "
+ "AND agent_sessions.session_anchor = ? AND agent_sessions.status != ? "
+ "AND agent_sessions.agent_backend IN (?, ?) AND agent_sessions.agent_variant IN (?, ?) "
+ "ORDER BY agent_sessions.last_active_at DESC, agent_sessions.id DESC LIMIT ? OFFSET ?"
+)
+
+
+def test_ensure_agent_session_id_never_returns_a_placeholder_archived_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-259 — the placeholder relabel matched by id and returned what it relabelled.
+
+ THE FOURTH writer with the HFR-251 shape, and the one the earlier rounds walked
+ past twice: ``_find_agent_session_row_id`` runs BEFORE
+ ``get_or_create_agent_session_row`` on both bind entry points, and its legacy
+ branch is itself a read-then-write. It selects a row whose ``agent_backend`` /
+ ``agent_variant`` are still the blank / ``"default"`` placeholder (and, via
+ ``base_query``, not archived), then relabels it to the concrete backend with
+ ``UPDATE ... WHERE id = ?`` and RETURNS that id.
+
+ THE RETURN VALUE IS THE DAMAGE HERE, which is HFR-253's lesson applied to a
+ different function. ``ensure_agent_session_id`` passes this id straight back to its
+ caller, and ``BaseAgent.ensure_agent_session_id`` pins any non-empty answer into
+ ``context.platform_specific['agent_session_id']`` without ever re-resolving. So an
+ archive committed inside the window -- terminal, and filtered out by every read on
+ this path, ``base_query`` included -- was relabelled and then handed to the turn as
+ its session.
+
+ THE ANSWER IS "NO ROW", not the archived id and not a second decision from the
+ refused snapshot: ``None`` is what this finder returns when it sees nothing usable,
+ and the caller then resolves the anchor through ``get_or_create_agent_session_row``,
+ whose reads exclude archived rows and whose writes are individually guarded. The
+ outcome converges with the serial order (archive first, then the turn): the thread
+ gets a FRESH session, because the archive vacated the anchor.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ # Two-part scope key, created up front: the resolve inside the call under
+ # test is then a pure SELECT and takes no write lock.
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C9", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ placeholder_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C9",
+ # The legacy placeholder shape: a row that reserved the thread's
+ # identity before backends were recorded on it.
+ agent_backend="",
+ agent_variant="default",
+ native_session_id="",
+ workdir=str(tmp_path),
+ require_workdir=False,
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_PLACEHOLDER_DECISION_SELECT,
+ values=_archive_write(placeholder_id),
+ )
+
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::C9",
+ agent_name="claude",
+ session_anchor="slack_C9",
+ workdir=str(tmp_path),
+ )
+ placeholder_row = service.get_agent_session_by_id(placeholder_id)
+ resolved_row = service.get_agent_session_by_id(resolved) if resolved else None
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing about "
+ "the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert resolved != placeholder_id, (
+ f"the finder relabelled and returned {resolved!r}, a session archived during "
+ "its window; an archive is terminal and vacates the anchor, and nothing "
+ "re-resolves after this call — BaseAgent pins the answer into the turn context "
+ "as-is, so the whole turn would report against an archived row"
+ )
+ assert placeholder_row is not None
+ assert placeholder_row["status"] == "archived", (
+ f"the relabel undid the archive; status is {placeholder_row['status']!r}"
+ )
+ assert placeholder_row["agent_backend"] == "", (
+ f"the relabel rewrote the route of a terminal row to "
+ f"{placeholder_row['agent_backend']!r}, leaving the archived session labelled "
+ "with a backend it never ran"
+ )
+ assert placeholder_row["agent_variant"] == "default"
+ assert placeholder_row["session_anchor"] == f"archived:{placeholder_id}", (
+ "the relabel undid the archive's anchor vacation"
+ )
+ # The thread keeps working: a fresh session on the vacated anchor, which is
+ # exactly what the serial order (archive, then turn) produces.
+ assert resolved_row is not None, "the turn was left with no session at all"
+ assert resolved_row["status"] == "active"
+ assert resolved_row["agent_backend"] == "claude"
+ assert resolved_row["session_anchor"] == "slack_C9"
+
+
+def test_placeholder_relabel_cannot_overwrite_a_backend_claimed_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-259, identity half — the other competing write for the same window.
+
+ Same statement, a live winner instead of an archive: another turn fills the
+ placeholder's blank backend with a CONCRETE one and binds its native id. The
+ relabel's whole justification is that a blank / ``"default"`` label names no
+ previous backend, so nothing on the row can belong to a different one -- once the
+ winner has filled it, that justification is gone, and a bare ``id`` match relabelled
+ a Codex-owned, Codex-bound row to ``claude`` while its native id stood.
+
+ Losing sends the caller back through ``get_or_create_agent_session_row``, which
+ reads the row fresh, sees a bound row on another backend, and supersedes it -- the
+ branch that exists for exactly this state. So the winner keeps its route and its
+ transcript, and the caller still gets a usable Claude session.
+ """
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::CA", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ placeholder_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_CA",
+ agent_backend="",
+ agent_variant="default",
+ native_session_id="",
+ workdir=str(tmp_path),
+ require_workdir=False,
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_PLACEHOLDER_DECISION_SELECT,
+ values={
+ "id": placeholder_id,
+ "agent_backend": "codex",
+ "agent_variant": "codex",
+ "agent_id": "agent-codex",
+ "agent_name": "nightly-codex",
+ "native_session_id": "codex-native-uuid",
+ "status": "active",
+ "updated_at": "2026-07-28T00:00:01Z",
+ "last_active_at": "2026-07-28T00:00:01Z",
+ },
+ )
+
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::CA",
+ agent_name="claude",
+ session_anchor="slack_CA",
+ workdir=str(tmp_path),
+ )
+ winner_row = service.get_agent_session_by_id(placeholder_id)
+ resolved_row = service.get_agent_session_by_id(resolved) if resolved else None
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing claim never landed inside the window, so this test proved "
+ "nothing about the race"
+ )
+ assert resolved != placeholder_id, (
+ f"the finder relabelled and handed back {resolved!r}, a row another backend "
+ "had just claimed and bound"
+ )
+ assert winner_row is not None
+ assert winner_row["agent_backend"] == "codex", (
+ f"the placeholder relabel moved a row claimed during its window to "
+ f"{winner_row['agent_backend']!r}; it now claims a backend that never produced "
+ f"its conversation while holding native id {winner_row['native_session_id']!r}"
+ )
+ assert winner_row["agent_variant"] == "codex"
+ assert winner_row["agent_name"] == "nightly-codex"
+ assert winner_row["native_session_id"] == "codex-native-uuid"
+ assert resolved_row is not None, "the Claude turn was left with no session at all"
+ assert resolved_row["agent_backend"] == "claude"
+ assert resolved_row["session_anchor"] == "slack_CA"
+
+
+#: The id read of ``_delete_agent_session_rows`` for the ``/new`` clear shape
+#: (``agent_name``, no anchor prefix). Every predicate the teardown decides from --
+#: the scope, the agent-name match, and the ``include_superseded=False`` guard -- is
+#: evaluated HERE, before any write lock exists.
+_TEARDOWN_ID_SELECT = (
+ "SELECT agent_sessions.id FROM agent_sessions WHERE agent_sessions.scope_id = ? "
+ "AND (agent_sessions.agent_backend = ? OR agent_sessions.agent_variant = ?) "
+ "AND (agent_sessions.session_anchor IS NULL OR agent_sessions.session_anchor "
+ "NOT LIKE ? ESCAPE '\\')"
+)
+
+
+def test_new_teardown_keeps_a_session_superseded_inside_its_window(tmp_path: Path) -> None:
+ """HFR-260 — the hard delete applied the teardown query in the READ only.
+
+ THE PRODUCTION STORY. ``/new`` in a thread runs ``clear_sessions()`` through every
+ backend adapter, which reach ``delete_agent_sessions(scope_key, agent_name=...)``.
+ At the same moment a claim for another backend supersedes the thread's session R:
+ R's anchor is moved aside and a replacement row takes the slot.
+
+ THE DEFECT IS THE WINDOW. ``delete_agent_sessions`` excludes superseded rows from
+ EVERY deletion path on purpose -- superseding PROMISES the row is kept, because its
+ native id is write-once and its transcript is not recoverable -- but that guard
+ lived only in the id SELECT, which runs before any write lock exists. R's id was
+ read while its anchor was still bare, so the ``DELETE ... WHERE id IN (...)`` that
+ followed hard-deleted exactly the row the guard exists to protect, and returned it
+ in the count.
+
+ The fix re-asserts the WHOLE teardown query inside the DELETE, so every predicate is
+ re-evaluated with the write lock held, whichever caller built them.
+
+ WHAT THIS TEST DELIBERATELY DOES NOT ASSERT: that the reclaim is undone. The reclaim
+ must run before the delete (it needs both rows visible for the settings snapshot), and
+ rolling it back needs a SAVEPOINT around both -- which under WAL pins a read snapshot
+ at the reclaim's own SELECT and makes its UPDATE fail with ``SQLITE_BUSY_SNAPSHOT``
+ on this very interleaving (measured while writing this test). So the pause stands and
+ is honestly reported; the kept row is a superseded one the thread has moved off, and
+ ``pause`` is the recoverable mode.
+ """
+ from storage.session_reclaim import session_teardown_context
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C6", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ superseded_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_C6",
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="codex-native-uuid",
+ workdir=str(tmp_path),
+ )
+ _bind_definition(conn, definition_id="def-pinned", session_id=superseded_id)
+
+ def _winner_supersedes(other_conn) -> None: # noqa: ANN001
+ other_conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == superseded_id)
+ .values(
+ session_anchor=f"slack_C6:superseded:{superseded_id}",
+ updated_at="2026-07-28T00:00:01Z",
+ )
+ )
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id="seswinner002",
+ session_anchor="slack_C6",
+ agent_backend="claude",
+ agent_variant="claude",
+ native_session_id="",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:01Z",
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_TEARDOWN_ID_SELECT,
+ write=_winner_supersedes,
+ )
+
+ with session_teardown_context(reason="the bound agent session was cleared") as ledger:
+ removed = service.delete_agent_sessions(scope_key="slack::C6", agent_name="codex")
+ ledger_entries = list(ledger)
+
+ kept_row = service.get_agent_session_by_id(superseded_id)
+ with service.engine.begin() as conn:
+ definition = (
+ conn.execute(select(run_definitions).where(run_definitions.c.id == "def-pinned"))
+ .mappings()
+ .first()
+ )
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing supersede never landed inside the window, so this test proved "
+ "nothing about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert removed == 0, (
+ f"the teardown reported {removed!r} sessions deleted; the only candidate it "
+ "read had become a SUPERSEDED row by the time the delete ran, and the "
+ "include_superseded=False guard exists to keep exactly that row"
+ )
+ assert kept_row is not None, (
+ "the /new teardown hard-deleted a row that was superseded inside its window; "
+ "superseding promises the row is kept, its native id is write-once and its "
+ "transcript is not recoverable"
+ )
+ assert kept_row["session_anchor"] == f"slack_C6:superseded:{superseded_id}"
+ assert kept_row["native_session_id"] == "codex-native-uuid"
+ # The reclaim stands (see the docstring) and the ledger says exactly that, so the
+ # user's reply is still true about what happened to their tasks.
+ assert definition is not None
+ assert definition["enabled"] == 0
+ assert [entry["definition_id"] for entry in ledger_entries] == ["def-pinned"], (
+ f"the /new reply counts {ledger_entries!r}, which is not what the teardown did"
+ )
+
+
+# --- Meta-guard: every writer of the session ROUTE must stay marker-aware ---
+#
+# Deliberately NOT catalogued as a product scenario: it asserts nothing a user can
+# observe, it converts "the next writer must remember the override marker" from a
+# review habit into a CI failure. The user-visible regressions it backs are
+# HFR-245/246/247/250.
+
+#: Modules allowed to write the backend-owned session route -- ``model`` /
+#: ``reasoning_effort`` (the pinnable settings) or ``agent_backend`` /
+#: ``agent_variant`` (what makes those settings stale). Each one must ALSO
+#: reconcile the row's ``explicit_setting_overrides`` marker, which is re-checked
+#: below -- a stale marker keeps forcing dispatch to honour a value the writer
+#: just invalidated.
+_MARKER_AWARE_SESSION_ROUTE_WRITERS = {
+ # create_agent_session_row (insert: the caller hands in its own metadata) and
+ # _claim_anchor_row, which resets the whole route of an unbound row on a
+ # cross-backend adoption and clears the marker with it.
+ "storage/agent_session_rows.py",
+ # update_session: a PRESENT model / reasoning_effort (including null, the Chat
+ # header's "Default") drops that field's marker entry.
+ "storage/workbench_sessions_service.py",
+ # materialize_agent_session_route skips any field the row pins explicitly, and
+ # bind_agent_session_by_id clears both pinnable columns (marker included) when
+ # its bind moves an unbound row to another backend; the remaining sites here
+ # write the route only as part of creating / importing / relabelling a row.
+ "storage/sessions_service.py",
+}
+
+#: The reconciliation API a marker-aware writer has to reach for.
+_MARKER_RECONCILERS = ("reconcile_explicit_overrides", "explicit_override_names")
+
+#: Per-write-site escape hatch: ``module -> {enclosing function name: why}``.
+#:
+#: The module-level check below is satisfied by a module that reconciles the marker
+#: ANYWHERE in the file, so a brand-new direct writer dropped into an already
+#: allowlisted module passes it for free. The per-function check closes that: the
+#: function containing each write site must reach the reconciliation API ITSELF,
+#: unless it is listed here. Keep this small -- every entry is a function that
+#: provably does not need to reconcile, not a function that has not got round to it.
+_MARKER_EXEMPT_ROUTE_WRITE_SITES = {
+ "storage/agent_session_rows.py": {
+ # INSERT path: the row does not exist yet, so there is no prior marker to
+ # reconcile against. ``metadata`` (marker included) is supplied by the
+ # caller, which is the layer that knows whether the new row PINS its
+ # model / effort or merely inherits them.
+ "create_agent_session_row": "INSERT path: metadata comes from the caller",
+ },
+ "storage/sessions_service.py": {
+ # Native-bind UPDATEs -- TWO detected sites since HFR-254 split the write
+ # into a write-once-guarded first bind and the remaining update. Both share
+ # one ``values`` dict, which carries status / timestamps /
+ # native_session_id / agent identity and NONE of the four route columns --
+ # not model / reasoning_effort, and not agent_backend / agent_variant
+ # either (any backend relabel on this path happens inside
+ # ``_find_agent_session_row_id``, which is detected separately). The
+ # ``model=None`` it passes goes to ``get_or_create_agent_session_row``,
+ # i.e. the INSERT path above. Detected only by the ``**values`` heuristic.
+ "bind_agent_session": "native bind: neither UPDATE sets a route column",
+ # Legacy-placeholder relabel: the only route column write here fills an
+ # agent_backend / agent_variant that is BLANK or ``"default"`` (the branch is
+ # guarded on both being in ``("", "default")``, and is reached only after the
+ # concrete-backend lookup for the same (scope, anchor) found nothing) with
+ # the concrete backend. A placeholder label names no previous backend, so no
+ # setting on that row can be a *different* backend's -- there is nothing for
+ # the marker to have gone stale about -- and the statement writes neither
+ # pinnable column. Contrast HFR-250, which moved a row between two CONCRETE
+ # backends.
+ "_find_agent_session_row_id": (
+ "fills a blank / 'default' placeholder backend label with the concrete "
+ "backend; not a move between backends, and writes neither pinnable column"
+ ),
+ # Legacy sessions.json import. The DETECTED site is the INSERT ``.values()``,
+ # with metadata built from the legacy state being imported, so there is no
+ # prior marker to reconcile. Its ``ON CONFLICT DO UPDATE`` ``set_`` excludes
+ # model / reasoning_effort, so an existing row's pinnable columns and its
+ # marker are left exactly as they were. NOTE: that ``set_`` DOES list
+ # agent_backend / agent_variant, and the conflict row is resolved by
+ # ``(scope, anchor)`` regardless of backend -- so an import CAN relabel an
+ # existing row's backend without reconciling. Recorded here rather than
+ # silently exempted; the detector cannot express it either way, because it
+ # matches the ``.values()`` and not the ``set_``.
+ "save_state": (
+ "legacy import: the detected site is the INSERT path, and the upsert's "
+ "set_ excludes both pinnable columns (see the note on its backend relabel)"
+ ),
+ },
+}
+
+
+#: The columns whose write makes a statement a ROUTE write.
+#:
+#: ``model`` / ``reasoning_effort`` are the pinnable settings the marker names.
+#: ``agent_backend`` / ``agent_variant`` are here because they are what makes
+#: those settings STALE: a statement that moves the row to another backend and
+#: touches neither pinnable column still invalidates both, and the marker it
+#: leaves behind keeps telling dispatch the old backend's model is a deliberate
+#: pin. That exact shape is HFR-250, and the old detector could not see it.
+_ROUTE_COLUMNS = ("model", "reasoning_effort", "agent_backend", "agent_variant")
+
+
+def _agent_session_route_writers() -> dict[str, list[int]]:
+ """Repo-relative module -> line numbers writing any ``_ROUTE_COLUMNS`` column.
+
+ Matches both the ORM shape (``agent_sessions.update()`` /
+ ``update(agent_sessions)`` followed by ``.values(...)``) and raw
+ ``UPDATE agent_sessions`` SQL. A ``**kwargs`` values dict counts: that is how
+ every dynamic writer in this repo sets these columns.
+ """
+ import re
+
+ root = Path(__file__).resolve().parents[1]
+ skip_parts = {".git", "tests", "ui", "node_modules", ".venv", "__pycache__", ".runtime", "docs"}
+ orm_stmt = re.compile(r"agent_sessions\.(?:update|insert)\(\)|(?:update|insert)\(\s*agent_sessions\s*\)")
+ raw_stmt = re.compile(r"(?:UPDATE|INSERT\s+INTO)\s+agent_sessions", re.IGNORECASE)
+ settings = re.compile(
+ "|".join(rf"\b{name}\s*=" for name in _ROUTE_COLUMNS) + r"|\*\*"
+ )
+
+ def balanced(text: str, start: int) -> str:
+ depth = 0
+ for index in range(start, len(text)):
+ if text[index] == "(":
+ depth += 1
+ elif text[index] == ")":
+ depth -= 1
+ if depth == 0:
+ return text[start : index + 1]
+ return text[start:]
+
+ found: dict[str, list[int]] = {}
+ for path in sorted(root.rglob("*.py")):
+ if any(part in skip_parts for part in path.relative_to(root).parts):
+ continue
+ text = path.read_text(encoding="utf-8")
+ rel = path.relative_to(root).as_posix()
+ for match in orm_stmt.finditer(text):
+ values_at = text.find(".values(", match.end())
+ if values_at < 0:
+ continue
+ if settings.search(balanced(text, values_at + len(".values"))):
+ found.setdefault(rel, []).append(text[:values_at].count("\n") + 1)
+ raw_columns = re.compile("|".join(rf"\b{name}\b" for name in _ROUTE_COLUMNS))
+ for match in raw_stmt.finditer(text):
+ statement = text[match.start() : match.start() + 800]
+ if raw_columns.search(statement):
+ found.setdefault(rel, []).append(text[: match.start()].count("\n") + 1)
+ return found
+
+
+def _enclosing_functions(
+ source: str, lines: list[int]
+) -> dict[int, ast.FunctionDef | ast.AsyncFunctionDef | None]:
+ """line number -> the INNERMOST function definition containing it, or None.
+
+ Parsed with ``ast`` rather than matched textually so "which function owns this
+ write" is decided by the same structure Python sees; a nested helper wins over
+ the method it lives in.
+ """
+ tree = ast.parse(source)
+ definitions = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ ]
+ owners: dict[int, ast.FunctionDef | ast.AsyncFunctionDef | None] = {}
+ for line in lines:
+ containing = [
+ node
+ for node in definitions
+ if node.lineno <= line <= (node.end_lineno or node.lineno)
+ ]
+ # Innermost = the one that starts last among those that contain the line.
+ owners[line] = max(containing, key=lambda node: node.lineno) if containing else None
+ return owners
+
+
+def test_only_marker_aware_modules_write_the_pinnable_session_columns() -> None:
+ """A new writer of the session ROUTE must reconcile the override marker.
+
+ ``agent_sessions.metadata_json.explicit_setting_overrides`` is a claim about
+ what the ROW currently pins, so it is only correct while every writer that can
+ invalidate that claim maintains it. It shipped maintained by exactly one
+ writer, and three of the others were already stale (HFR-245/246/247). This test
+ is the standing reminder: add the writer to an allowlist only after it
+ reconciles the marker.
+
+ THE QUESTION IT ASKS, widened by HFR-250. It used to be "does this statement
+ write ``model`` / ``reasoning_effort``, and if so does its function reconcile?"
+ -- which has a blind spot exactly the shape of the defect HFR-250 fixes: a
+ statement that rewrites the BACKEND-OWNED ROUTE (``agent_backend`` /
+ ``agent_variant``) while touching NEITHER pinnable column is invisible to it,
+ even though moving a row to another backend invalidates both of those columns
+ and the marker that pins them. The old allowlist even EXEMPTED
+ ``bind_agent_session_by_id`` on the grounds that its UPDATE "never sets model /
+ reasoning_effort" -- true, and precisely why the bug survived. So the question
+ is now: does this statement write ANY of ``_ROUTE_COLUMNS``?
+
+ WHAT IT PROVES, exactly:
+
+ 1. every file outside ``_MARKER_AWARE_SESSION_ROUTE_WRITERS`` is free of
+ detectable ``INSERT``/``UPDATE`` statements on ``agent_sessions`` that set
+ any of ``_ROUTE_COLUMNS``;
+ 2. each allowlisted module mentions the reconciliation API somewhere;
+ 3. for each DETECTED write site in an allowlisted module, the function that
+ lexically encloses it mentions the reconciliation API in its OWN body, or
+ that function is named in ``_MARKER_EXEMPT_ROUTE_WRITE_SITES`` with a
+ reason;
+ 4. both allowlists are free of stale entries.
+
+ (3) is the point of the AST pass. The module-level check (2) is satisfied by a
+ reconciliation ANYWHERE in the file, so a brand-new direct writer added to an
+ already allowlisted module used to pass for free -- that specific hole is what
+ the per-function check closes.
+
+ WHAT IT DOES NOT PROVE. This is a static text/AST inspection over a hand-kept
+ allowlist, not enforcement by construction. It cannot see:
+
+ - a write that reaches the columns through an ALIAS or a dynamically built
+ table reference (``t = agent_sessions``, ``metadata.tables["agent_sessions"]``,
+ an f-string / ``text()`` SQL string, an ORM mapper, a raw ``cursor.execute``
+ with the table name assembled at runtime);
+ - a write whose column names are computed rather than written literally, since
+ the detector's own column test is a regex over the statement text;
+ - migrations, fixtures, or any path under the skipped directories
+ (``tests/``, ``ui/``, ``docs/``, ...);
+ - route columns written by an ``ON CONFLICT DO UPDATE`` ``set_=`` clause rather
+ than the statement's own ``.values(...)``. The ORM branch matches the FIRST
+ ``.values(`` after the statement and stops there, so an upsert can relabel an
+ existing row's backend from ``set_`` and be judged on its INSERT values
+ instead -- ``save_state`` is exactly that case, recorded in its exemption
+ reason;
+ - WHETHER the reconciliation a function performs is CORRECT, or even reached on
+ the branch that does the write. Presence of the call is all that is checked --
+ HFR-248 is a case where the call was present and reconciled exactly backwards,
+ and this test was green throughout that inversion.
+
+ So it is a tripwire for the ordinary case (someone adds a normal UPDATE), not a
+ guarantee. The behavioural guarantees live in HFR-244/245/246/247/248/249/250.
+ """
+ writers = _agent_session_route_writers()
+ unexpected = {
+ module: lines
+ for module, lines in writers.items()
+ if module not in _MARKER_AWARE_SESSION_ROUTE_WRITERS
+ }
+ assert not unexpected, (
+ "these modules write the agent_sessions route ("
+ + " / ".join(_ROUTE_COLUMNS)
+ + ") without being listed as marker-aware: "
+ + "; ".join(f"{module}:{lines}" for module, lines in sorted(unexpected.items()))
+ + " -- reconcile the row's explicit_setting_overrides marker in the same "
+ "statement (storage.session_reclaim.reconcile_explicit_overrides), then add "
+ "the module to _MARKER_AWARE_SESSION_ROUTE_WRITERS with the reason"
+ )
+
+ root = Path(__file__).resolve().parents[1]
+ for module in sorted(_MARKER_AWARE_SESSION_ROUTE_WRITERS):
+ assert module in writers, (
+ f"stale allowlist entry: {module} no longer writes any route column"
+ )
+ source = (root / module).read_text(encoding="utf-8")
+ # Module level: kept as the outer ring. Cheap, and it catches an allowlist
+ # entry whose reconciliation was deleted wholesale.
+ assert any(name in source for name in _MARKER_RECONCILERS), (
+ f"{module} is allowlisted as marker-aware but never reaches the "
+ f"reconciliation API ({' / '.join(_MARKER_RECONCILERS)})"
+ )
+
+ # Per-write-site: the function doing the write must reconcile, itself.
+ exempt = _MARKER_EXEMPT_ROUTE_WRITE_SITES.get(module, {})
+ owners = _enclosing_functions(source, writers[module])
+ seen_exempt: set[str] = set()
+ for line, owner in sorted(owners.items()):
+ assert owner is not None, (
+ f"{module}:{line} writes an agent_sessions route column at module "
+ "level, outside any function -- there is nowhere to reconcile the "
+ "explicit_setting_overrides marker from"
+ )
+ name = owner.name
+ if name in exempt:
+ seen_exempt.add(name)
+ continue
+ body = ast.get_source_segment(source, owner) or ""
+ assert any(reconciler in body for reconciler in _MARKER_RECONCILERS), (
+ f"{module}:{line} writes an agent_sessions route column ("
+ + " / ".join(_ROUTE_COLUMNS)
+ + f") inside {name}(), which never reaches the reconciliation API "
+ f"({' / '.join(_MARKER_RECONCILERS)}). Its module is allowlisted, but "
+ "the allowlist is per module -- a stale marker keeps forcing dispatch "
+ "to honour the value this write just changed. Reconcile it in the same "
+ "statement (storage.session_reclaim.reconcile_explicit_overrides), or, "
+ "if this write provably needs no reconciliation, add "
+ f"{name!r} to _MARKER_EXEMPT_ROUTE_WRITE_SITES[{module!r}] with the reason"
+ )
+ stale_exempt = sorted(set(exempt) - seen_exempt)
+ assert not stale_exempt, (
+ f"stale per-function exemptions in {module}: {stale_exempt} no longer "
+ "enclose a detected route-column write"
+ )
+
+ stale_modules = sorted(set(_MARKER_EXEMPT_ROUTE_WRITE_SITES) - _MARKER_AWARE_SESSION_ROUTE_WRITERS)
+ assert not stale_modules, (
+ f"per-function exemptions for modules that are not allowlisted writers: {stale_modules}"
+ )
+
+
+
+#: The LAST read the first-turn INSERT decides from: ``new_session_id``'s scan of every
+#: existing session id. Proving the write lock is already held when this statement
+#: completes proves it was taken before every read the create rests on, because it is the
+#: read closest to the INSERT.
+_SESSION_ID_SCAN_SELECT = "SELECT agent_sessions.id FROM agent_sessions"
+
+#: The two spellings ``reserve_write_lock`` uses to become the writer: ``BEGIN IMMEDIATE``
+#: when the connection is in autocommit, and a never-matching UPDATE when a transaction is
+#: already open and ``BEGIN IMMEDIATE`` would be illegal. Asserting on the SEQUENCE keeps
+#: the guarantee observable even where a competing writer is hard to schedule.
+_WRITE_LOCK_RESERVATIONS = ("BEGIN IMMEDIATE", "UPDATE agent_sessions SET id = id WHERE 1 = 0")
+
+
+def _refuse_a_competing_writer_at(engine, db_path: Path, *, read: str, write) -> dict:
+ """Prove the code under test HOLDS SQLite's write lock when ``read`` completes.
+
+ The mirror image of ``_commit_competing_bind_after``: that helper lands a competing
+ commit inside an UNLOCKED window, and this one proves there is no window left for one
+ to land in. The competing connection is given ``busy_timeout = 0``, so rather than
+ waiting out the engine's 5s pragma it is refused the instant the writer slot is taken
+ -- positive, deterministic evidence that another transaction owns it, with no sleeping,
+ no second thread, and no dependence on ``sqlite3.Error.sqlite_errorcode`` (Python
+ 3.11+), so the observation is identical on every interpreter this project supports.
+
+ Records all three outcomes separately, because they mean different things: ``fired``
+ at 0 says the keyed read is no longer the SQL the code emits and the test proved
+ nothing; ``committed`` says the lock was NOT held, which is the defect; ``refused`` is
+ the pass.
+ """
+
+ state: dict = {"fired": 0, "refused": [], "committed": 0}
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != read:
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(db_path)
+ try:
+ with other.connect() as other_conn:
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 0")
+ try:
+ write(other_conn)
+ other_conn.commit()
+ except OperationalError as exc:
+ state["refused"].append(str(exc))
+ else:
+ state["committed"] += 1
+ finally:
+ other.dispose()
+
+ return state
+
+
+def _record_statements(engine) -> list[str]:
+ """Collect the normalised SQL the engine emits, in order."""
+
+ seen: list[str] = []
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _collect(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ seen.append(" ".join(statement.split()))
+
+ return seen
+
+
+def test_first_turn_insert_reserves_the_write_lock_before_the_reads_it_decides_from(
+ tmp_path: Path,
+) -> None:
+ """HFR-262 — the first-turn INSERT decided from a snapshot it could not write from.
+
+ THE PRODUCTION STORY. Two turns arrive on a brand-new thread at once. Neither finds a
+ session row, so both fall into ``get_or_create_agent_session_row`` and try to INSERT
+ the first one.
+
+ THE DEFECT WAS *WHEN* THE WINNER COMMITS. SQLite takes the write lock at a
+ transaction's first WRITE, never at its reads. The old code opened a ``SAVEPOINT`` and
+ then READ -- ``new_session_id``'s scan of every session id -- which under WAL pins a
+ read snapshot with no lock behind it. A winner committing between that scan and the
+ INSERT left the loser unable to become a writer AT ALL: SQLite answers
+ ``SQLITE_BUSY_SNAPSHOT``, ``busy_timeout`` never retries it because waiting cannot make
+ a snapshot newer, and it arrives as a PLAIN ``OperationalError`` carrying the same
+ "database is locked" text every unrelated busy error carries. The ``IntegrityError``
+ catch did not cover it, so ``ensure_agent_session_id`` -- and every other caller of
+ this shared get-or-create -- surfaced a database error out of an ordinary first turn.
+
+ WHY THIS TEST DOES NOT WATCH FOR THAT ERROR. RECOGNISING it needs
+ ``sqlite3.Error.sqlite_errorcode``, which exists from Python 3.11, while this project
+ supports 3.10 (``requires-python >= 3.10``): a fix built on detection is not a fix on a
+ supported runtime. ``reserve_write_lock`` removes the window instead -- the create path
+ becomes the writer BEFORE its reads -- so the interleaving cannot occur and there is no
+ error left to classify on any interpreter.
+
+ SO THE ASSERTION IS THE MECHANISM, NOT THE SYMPTOM: a competing writer given zero
+ patience must be REFUSED at the last read before the INSERT. That observation is the
+ same on 3.10 and on 3.13, and it fails against the pre-fix code, where the competitor
+ commits inside the savepoint instead.
+ """
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ competitor_id = "seswinner001"
+ raised: list[BaseException] = []
+ try:
+ with service.engine.begin() as conn:
+ # A TWO-part scope key with the scope already present: the resolve is then a
+ # pure SELECT, so the caller's transaction holds NO write lock of its own when
+ # the create path is entered. A three-part key upserts the scope and would
+ # close the window by accident, which is why the sibling test below covers
+ # both shapes rather than only this one.
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C9", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+
+ def _competitor_creates_the_first_row(other_conn) -> None: # noqa: ANN001
+ """The other turn trying to win the same brand-new anchor."""
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id=competitor_id,
+ session_anchor="slack_C9",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ native_session_id="",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:01Z",
+ )
+
+ race = _refuse_a_competing_writer_at(
+ service.engine,
+ db_path,
+ read=_SESSION_ID_SCAN_SELECT,
+ write=_competitor_creates_the_first_row,
+ )
+
+ try:
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::C9",
+ agent_name="claude",
+ session_anchor="slack_C9",
+ workdir=str(tmp_path),
+ vibe_agent_id="agent-claude",
+ vibe_agent_name="review-claude",
+ )
+ except Exception as exc: # noqa: BLE001 - the original defect IS the escape
+ raised.append(exc)
+ resolved = None
+ finally:
+ service.close()
+
+ # Read the committed state through a FRESH engine: only a real commit puts it here.
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ anchor_rows = [
+ dict(row)
+ for row in conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.agent_backend)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(agent_sessions.c.session_anchor == "slack_C9")
+ ).mappings()
+ ]
+ all_ids = list(
+ conn.execute(select(agent_sessions.c.id).where(agent_sessions.c.scope_id == scope_id))
+ .scalars()
+ .all()
+ )
+ finally:
+ engine.dispose()
+
+ assert race["fired"] == 1, (
+ "the competing insert never ran inside the window, so this test proved nothing "
+ "about the race — the keyed read is no longer the SQL the code emits"
+ )
+ assert race["committed"] == 0, (
+ "a competing connection took the write lock while the first-turn create was "
+ "reading the state its INSERT decides from; that window is exactly what produces "
+ "SQLITE_BUSY_SNAPSHOT, and no interleaving may be able to enter it"
+ )
+ assert len(race["refused"]) == 1, (
+ f"the competing writer neither committed nor was refused: {race!r}"
+ )
+ assert not raised, (
+ f"a first turn raised {raised[0]!r} out of get_or_create_agent_session_row; the "
+ "create path must hold the write lock across the reads its INSERT decides from, "
+ "so a competing turn cannot make its snapshot stale"
+ )
+ assert [row["id"] for row in anchor_rows] == [resolved], (
+ f"the anchor slack_C9 is held by {anchor_rows!r}, not by the session {resolved!r} "
+ "this turn was handed"
+ )
+ assert anchor_rows[0]["agent_backend"] == "claude"
+ assert all_ids == [resolved], (
+ f"scope {scope_id} holds {all_ids!r}; exactly ONE session row may exist for a "
+ "thread whose first turn was contested"
+ )
+ assert competitor_id not in all_ids, (
+ f"the refused competitor's row {competitor_id!r} was committed anyway"
+ )
+
+
+def test_first_turn_insert_joins_a_winner_that_committed_before_the_reservation(
+ tmp_path: Path,
+) -> None:
+ """HFR-262 — the UNLOCKED first read is a hint, and the reserved re-read is the answer.
+
+ THE WINDOW THAT REMAINS, and must not matter. ``get_or_create_agent_session_row``
+ deliberately keeps its FIRST anchor read unlocked: it is the hot path every inbound
+ message takes and a session row almost always already exists, so serialising it would
+ queue unrelated threads behind each other for no gain. The consequence is that a
+ winner can still commit between that read and the reservation -- which under the old
+ code was the ``IntegrityError`` half of this race, and is why the create path must
+ take its decision AGAIN once the write lock is held.
+
+ THE DEFECT THIS PINS is a create that trusts the unlocked read: it would INSERT a
+ second row for a thread that already has one, and the UNIQUE ``(scope_id,
+ session_anchor)`` index is the only reason that surfaces as an error rather than a
+ silent duplicate. With the reserved re-read the loser sees the winner and joins it
+ through ``_claim_anchor_row`` instead, which is the answer the contract promises.
+
+ A SERIAL TEST CANNOT OBSERVE THIS: commit the winner first and the unlocked read finds
+ it, which is the ordinary already-exists path. The commit has to land between the two
+ reads.
+ """
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ winner_id = "seswinner001"
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::CB", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+
+ def _winner_creates_the_first_row(other_conn) -> None: # noqa: ANN001
+ """On the OTHER backend, so the loser must reconcile through the relabel.
+
+ That relabel is a WRITE, and it runs after the reservation, so a green test
+ also proves the reserved transaction stays usable and commits.
+ """
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id=winner_id,
+ session_anchor="slack_CB",
+ agent_backend="codex",
+ agent_variant="codex",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ native_session_id="",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:01Z",
+ )
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_ANCHOR_DECISION_SELECT,
+ write=_winner_creates_the_first_row,
+ )
+
+ resolved = service.ensure_agent_session_id(
+ scope_key="slack::CB",
+ agent_name="claude",
+ session_anchor="slack_CB",
+ workdir=str(tmp_path),
+ vibe_agent_id="agent-claude",
+ vibe_agent_name="review-claude",
+ )
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ anchor_rows = [
+ dict(row)
+ for row in conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.agent_backend)
+ .where(agent_sessions.c.scope_id == scope_id)
+ .where(agent_sessions.c.session_anchor == "slack_CB")
+ ).mappings()
+ ]
+ finally:
+ engine.dispose()
+
+ assert race["fired"] == 1, (
+ "the competing insert never landed between the unlocked read and the reservation, "
+ "so this test proved nothing about the race"
+ )
+ assert [row["id"] for row in anchor_rows] == [winner_id], (
+ f"the anchor slack_CB is held by {anchor_rows!r}; a create that trusted its "
+ "unlocked read inserted a second row for a thread that already had one"
+ )
+ assert resolved == winner_id, (
+ f"the loser answered {resolved!r}; it must hand back the session that holds the "
+ "anchor now, so the turn runs in the session the thread actually has"
+ )
+ assert anchor_rows[0]["agent_backend"] == "claude", (
+ f"the loser joined the winner's row but its relabel did not survive (backend is "
+ f"{anchor_rows[0]['agent_backend']!r}): the reserved transaction must stay usable, "
+ "so the writes it makes afterwards still commit"
+ )
+
+
+def _ensure_first_turn(service: SQLiteSessionsService, *, scope_key: str, anchor: str, workdir: str) -> str | None:
+ return service.ensure_agent_session_id(
+ scope_key=scope_key,
+ agent_name="claude",
+ session_anchor=anchor,
+ workdir=workdir,
+ )
+
+
+def _bind_first_turn(service: SQLiteSessionsService, *, scope_key: str, anchor: str, workdir: str) -> str | None:
+ return service.bind_agent_session(
+ scope_key=scope_key,
+ agent_name="claude",
+ session_anchor=anchor,
+ native_session_id="claude-native-uuid",
+ workdir=workdir,
+ )
+
+
+ ("scope_key", "anchor", "call"),
+ [
+ # Two-part key: the scope resolve is a pure SELECT, so the create path enters in
+ # autocommit and the reservation is ``BEGIN IMMEDIATE``.
+ ("slack::CC1", "slack_CC1", _ensure_first_turn),
+ # Three-part key: ``resolve_scope_from_legacy_key`` upserts the scope, so a
+ # transaction is already open and the reservation is the never-matching UPDATE.
+ ("slack::channel::CC2", "slack_CC2", _ensure_first_turn),
+ # The second writer that reaches the same get-or-create on a first turn.
+ ("slack::CC3", "slack_CC3", _bind_first_turn),
+ ],
+ ids=["ensure_two_part_scope_key", "ensure_three_part_scope_key", "bind_two_part_scope_key"],
+)
+def test_every_first_turn_entry_point_reserves_the_write_lock(
+ tmp_path: Path,
+ scope_key: str,
+ anchor: str,
+ call,
+) -> None:
+ """HFR-262 — the guarantee has to hold for EVERY path into the contested INSERT.
+
+ One path holding the write lock is not the fix; the INSERT is shared, so a caller that
+ reaches it without the lock reopens the window on its own. These are the production
+ entry points into the create branch of ``get_or_create_agent_session_row`` that start
+ from a ``SQLiteSessionsService`` method, and they differ in the ONE way that matters:
+ whether the caller's transaction has already written by the time the create path is
+ entered. A three-part scope key upserts the scope (so a transaction is open and
+ ``BEGIN IMMEDIATE`` is illegal); a two-part key resolves with a pure SELECT (so it is
+ not). ``reserve_write_lock`` has a spelling for each, and both must end with the lock
+ actually held.
+
+ ``resolve_agent_run_target`` is the third entry point and is pinned the same way in
+ ``tests/test_agent_run_target.py``.
+
+ Checked TWO ways, because each catches what the other cannot: the statement sequence
+ shows a reservation ahead of the last read (so the mechanism is present and ordered),
+ and a competing writer with zero patience is refused at that read (so the reservation
+ really took the lock, rather than merely being emitted).
+ """
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ competitor_id = "seswinner001"
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, scope_key, now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+
+ def _competitor_creates_the_first_row(other_conn) -> None: # noqa: ANN001
+ create_agent_session_row(
+ other_conn,
+ scope_id=scope_id,
+ session_id=competitor_id,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:01Z",
+ )
+
+ statements = _record_statements(service.engine)
+ race = _refuse_a_competing_writer_at(
+ service.engine,
+ db_path,
+ read=_SESSION_ID_SCAN_SELECT,
+ write=_competitor_creates_the_first_row,
+ )
+
+ resolved = call(service, scope_key=scope_key, anchor=anchor, workdir=str(tmp_path))
+ finally:
+ service.close()
+
+ assert resolved, f"{scope_key} produced no session at all"
+ assert _SESSION_ID_SCAN_SELECT in statements, (
+ "the id scan the INSERT decides from is no longer emitted, so neither check below "
+ "means anything"
+ )
+ scan_at = statements.index(_SESSION_ID_SCAN_SELECT)
+ reserved_at = [index for index, sql in enumerate(statements) if sql in _WRITE_LOCK_RESERVATIONS]
+ assert reserved_at and min(reserved_at) < scan_at, (
+ f"no write-lock reservation precedes the id scan for {scope_key}: {statements!r}"
+ )
+ assert race["fired"] == 1, (
+ "the competing insert never ran inside the window, so this test proved nothing"
+ )
+ assert race["committed"] == 0, (
+ f"for {scope_key} a competing connection took the write lock while the create path "
+ f"was reading the state its INSERT decides from: {race!r}"
+ )
+
+
+def test_write_lock_reservation_takes_the_lock_without_touching_a_row(tmp_path: Path) -> None:
+ """HFR-262 — the reservation used when a transaction is ALREADY open.
+
+ ``BEGIN IMMEDIATE`` is illegal inside an open transaction, so ``reserve_write_lock``
+ falls back to a write that changes nothing. That works because SQLite takes the write
+ lock at the START of an UPDATE program, before its WHERE loop runs -- an implementation
+ property rather than a documented promise, and the only reason this statement is here,
+ so it is pinned rather than trusted. Both halves matter: it must take the lock, and it
+ must leave the data alone.
+ """
+
+ from storage.agent_session_rows import reserve_write_lock
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ refused: list[str] = []
+ committed: list[str] = []
+ try:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::CD", now="2026-07-28T00:00:00Z")
+ assert scope_id is not None
+ existing_id = create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor="slack_CD",
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="codex-native-uuid",
+ workdir=str(tmp_path),
+ now="2026-07-28T00:00:00Z",
+ )
+
+ with service.engine.begin() as conn:
+ # Force the "transaction already open" state WITHOUT writing: pysqlite emits no
+ # BEGIN for a bare SELECT, so a raw one is the only way to reach the branch.
+ conn.exec_driver_sql("BEGIN")
+ assert conn.connection.dbapi_connection.in_transaction is True
+ reserve_write_lock(conn)
+
+ other = create_sqlite_engine(db_path)
+ try:
+ with other.connect() as other_conn:
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 0")
+ try:
+ other_conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == existing_id)
+ .values(agent_backend="claude")
+ )
+ other_conn.commit()
+ except OperationalError as exc:
+ refused.append(str(exc))
+ else:
+ committed.append("wrote")
+ finally:
+ other.dispose()
+ finally:
+ service.close()
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ rows = [
+ dict(row)
+ for row in conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.agent_backend, agent_sessions.c.updated_at)
+ ).mappings()
+ ]
+ finally:
+ engine.dispose()
+
+ assert not committed, (
+ "a competing writer took the write lock after the reservation ran, so the "
+ "never-matching UPDATE did not reserve the writer slot and the create path it "
+ "guards is still racing"
+ )
+ assert len(refused) == 1, f"the competing writer was neither refused nor committed: {refused!r}"
+ assert rows == [
+ {"id": existing_id, "agent_backend": "codex", "updated_at": "2026-07-28T00:00:00Z"}
+ ], (
+ f"the reservation changed data: {rows!r}. It exists only to become the writer, so "
+ "it must never match a row"
+ )
+
+
+#: The read ``release_reserved_agent_session`` decides from: the reserved row, still
+#: unbound and still referenced by nothing (``_delete_agent_session_rows``'s ``id_query``).
+#: Everything the release then does -- the reclaim, the DELETE, the workspace removal --
+#: rests on this one row set.
+_RESERVED_RELEASE_DECISION_SELECT = (
+ "SELECT agent_sessions.id FROM agent_sessions WHERE agent_sessions.id = ? AND "
+ "(agent_sessions.native_session_id IS NULL OR agent_sessions.native_session_id = ?) "
+ "AND NOT (EXISTS (SELECT run_definitions.id FROM run_definitions "
+ "WHERE run_definitions.session_id = ?))"
+)
+
+
+def _adopt_the_reservation_at_the_last_unlocked_instant(
+ engine,
+ db_path: Path,
+ *,
+ definition_id: str,
+ session_id: str,
+ updated_at: str,
+) -> dict:
+ """Commit a competing ADOPTION of the reserved session, from a real second connection.
+
+ Fires at the last instant another transaction is ABLE to commit before the release
+ treats the reserved row as unreferenced, which is a different statement in each
+ version of the code and is the whole point of the fix:
+
+ * BEFORE ``reserve_write_lock``'s reservation (the fixed order). The lock is not held
+ yet, so the adoption commits, and the decision read that follows it SEES the
+ adoption -- there is no window left between the read and the reclaim.
+ * AFTER the decision read (the unfixed order, which emits no reservation at all). The
+ read has already happened and reserved nothing, so this is the window: the reclaim
+ that follows looks at the winner's definition.
+
+ Fires ONCE either way, so the fixed order never reaches the second hook. The competing
+ connection uses ``busy_timeout = 0`` and records its outcome instead of waiting, so a
+ hook that ever lands after the write lock is taken shows up as ``refused`` rather than
+ as a five-second stall -- and ``committed`` at 1 is what makes the interleaving real in
+ BOTH versions, so the winner-untouched assertions mean the same thing in each.
+ """
+
+ state: dict = {"fired": 0, "committed": 0, "refused": [], "at": None}
+
+ def _adopt(where: str) -> None:
+ state["fired"] += 1
+ state["at"] = where
+ other = create_sqlite_engine(db_path)
+ try:
+ with other.connect() as other_conn:
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 0")
+ try:
+ other_conn.execute(
+ run_definitions.update()
+ .where(run_definitions.c.id == definition_id)
+ .values(session_id=session_id, updated_at=updated_at)
+ )
+ other_conn.commit()
+ except OperationalError as exc:
+ state["refused"].append(str(exc))
+ else:
+ state["committed"] += 1
+ finally:
+ other.dispose()
+
+ @event.listens_for(engine, "before_cursor_execute")
+ def _before(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) not in _WRITE_LOCK_RESERVATIONS:
+ return
+ _adopt("before the write-lock reservation")
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _after(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != _RESERVED_RELEASE_DECISION_SELECT:
+ return
+ _adopt("after the decision read")
+
+ return state
+
+
+def test_releasing_a_reservation_cannot_damage_a_definition_that_adopted_it(
+ tmp_path: Path,
+) -> None:
+ """HFR-278 — the reservation cleanup damaged the winner before deciding it may not delete.
+
+ THE PRODUCTION STORY, one layer inside our own HFR-270 fix. A fire reserves a session,
+ its guarded rebind is refused because another surface won the race, and HFR-270 gives
+ the reservation back. Meanwhile the WINNER -- another fire, another process -- adopts
+ that same reserved session id.
+
+ THE DEFECT IS THE WINDOW, and the final DELETE is exactly why it went unnoticed.
+ ``_delete_agent_session_rows`` runs its ``id_query`` first and
+ ``reclaim_bound_definitions`` second, and that read reserves nothing (pysqlite opens no
+ transaction for a bare SELECT). An adoption committing between the two left the reclaim
+ reading the WINNER's definition: it PAUSED it, stamped its ``last_error`` with the
+ release's reason, and overwrote its ``session_settings_snapshot``. The DELETE then
+ re-evaluated ``NOT EXISTS``, correctly refused, and the function returned ``False`` --
+ so the session row survived, the log said "not releasing", and the definition that had
+ just adopted it was disabled anyway, with a pause reason naming a release that had
+ decided to keep its session. The reclaim is deliberately never rolled back
+ (``_delete_agent_session_rows`` documents why), so nothing corrected it.
+
+ THE FIX IS ORDER, NOT DETECTION: ``reserve_write_lock`` before the read the decision
+ rests on. The adoption can then only land BEFORE the release looks -- where the
+ predicates see it and the release backs off untouched -- or after the release has
+ committed. Re-asserting the predicates in the DELETE was never enough: it protects the
+ ROW, and the damage was to a definition.
+
+ ASSERTED ON THE WHOLE ROW THE WINNER OWNS, the HFR-251 lesson: not merely "the session
+ survived" but its Session row, its workspace, its route/anchor, its pins and explicit
+ override markers, its definition's enabled state, pause reason, settings snapshot AND
+ every timestamp. A test that checked only ``enabled`` would have gone green over a
+ reclaim that still rewrote the snapshot a later ``create_once`` rebind reads.
+ """
+ from storage.session_reclaim import (
+ SESSION_SETTINGS_OVERRIDE_KEY,
+ SESSION_SETTINGS_SNAPSHOT_KEY,
+ session_teardown_context,
+ )
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ # A standalone reservation: no Scope, and its own lazy Show workspace, which is
+ # the one workdir ``_remove_reserved_workspace`` is entitled to delete -- so the
+ # release really can destroy something on disk here.
+ reserved_id = service.reserve_standalone_agent_session(
+ agent_backend="codex",
+ session_anchor="slack_C9:reserved",
+ agent_id="agent-codex",
+ agent_name="nightly-codex",
+ model="gpt-5.5-codex",
+ reasoning_effort="high",
+ metadata={
+ # The route the reservation carries, and the pins the winner inherits
+ # with it.
+ "legacy_scope_key": "slack::channel::C9",
+ SESSION_SETTINGS_OVERRIDE_KEY: ["model", "reasoning_effort"],
+ },
+ )
+ workspace = paths.get_show_page_dir(reserved_id)
+ assert workspace.is_dir(), "the reservation did not create the workspace it owns"
+
+ with service.engine.begin() as conn:
+ # The winner's definition, not yet bound to anything: a create_once task
+ # between reserving its session and committing the binding.
+ _bind_definition(conn, definition_id="def-winner", session_id=None)
+ definition_before = dict(
+ conn.execute(
+ select(run_definitions).where(run_definitions.c.id == "def-winner")
+ )
+ .mappings()
+ .one()
+ )
+ session_before = dict(
+ conn.execute(select(agent_sessions).where(agent_sessions.c.id == reserved_id))
+ .mappings()
+ .one()
+ )
+
+ race = _adopt_the_reservation_at_the_last_unlocked_instant(
+ service.engine,
+ db_path,
+ definition_id="def-winner",
+ session_id=reserved_id,
+ updated_at="2026-07-28T00:00:05Z",
+ )
+
+ with session_teardown_context(reason="reserved session released") as ledger:
+ released = service.release_reserved_agent_session(
+ reserved_id, reason="the rebind was refused"
+ )
+ ledger_entries = list(ledger)
+
+ with service.engine.begin() as conn:
+ definition_after = (
+ conn.execute(
+ select(run_definitions).where(run_definitions.c.id == "def-winner")
+ )
+ .mappings()
+ .first()
+ )
+ session_after = (
+ conn.execute(select(agent_sessions).where(agent_sessions.c.id == reserved_id))
+ .mappings()
+ .first()
+ )
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the competing adoption never ran, so this test proved nothing about the race -- "
+ "neither keyed statement is the SQL the code emits any more"
+ )
+ assert race["committed"] == 1, (
+ f"the adoption could not commit at all ({race!r}), so there is no winner and the "
+ "assertions below would hold for a reservation nobody wanted"
+ )
+
+ assert released is False, (
+ "the release reported that it gave the reservation back, while another "
+ "definition had adopted it: that is the dangling binding the whole reclaim "
+ "machinery exists to prevent"
+ )
+ assert session_after is not None, (
+ f"the release DELETED session {reserved_id} after a definition adopted it"
+ )
+ assert dict(session_after) == session_before, (
+ "the release rewrote the Session the winner adopted. Differing fields: "
+ + repr(
+ {
+ key: (value, session_before.get(key))
+ for key, value in dict(session_after).items()
+ if session_before.get(key) != value
+ }
+ )
+ )
+ assert workspace.is_dir(), (
+ f"the release removed the workspace {workspace} of a session the winner is now "
+ "bound to; its first turn has no cwd"
+ )
+
+ assert definition_after is not None
+ # The ONLY change the winner's own adoption makes: its binding and the timestamp it
+ # stamps. Everything else in the row must be exactly what it was.
+ expected_definition = {
+ **definition_before,
+ "session_id": reserved_id,
+ "updated_at": "2026-07-28T00:00:05Z",
+ }
+ assert dict(definition_after) == expected_definition, (
+ "the release damaged the definition that adopted the reserved session before "
+ "deciding it was not allowed to delete it. Differing fields: "
+ + repr(
+ {
+ key: (value, expected_definition.get(key))
+ for key, value in dict(definition_after).items()
+ if expected_definition.get(key) != value
+ }
+ )
+ )
+ assert definition_after["enabled"] == 1, (
+ "the winner's definition was PAUSED by a release that then kept its session: it "
+ "is disabled, and nothing will re-enable it"
+ )
+ assert definition_after["last_error"] is None, (
+ f"the winner's definition explains itself with {definition_after['last_error']!r}, "
+ "a reason from a release that touched nothing it owns"
+ )
+ assert SESSION_SETTINGS_SNAPSHOT_KEY not in json.loads(
+ definition_after["metadata_json"] or "{}"
+ ), (
+ "the release wrote a teardown settings snapshot onto a LIVE binding; a later "
+ "create_once rebind reads that snapshot and would come back on the wrong route"
+ )
+
+ # The accounting half: a reclaim that must not happen must not be reported either.
+ assert ledger_entries == [], (
+ f"the release credited a reclaim to the teardown ledger: {ledger_entries!r}"
+ )
+
+
+def test_releasing_a_reservation_holds_the_write_lock_at_its_decision_read(
+ tmp_path: Path,
+) -> None:
+ """HFR-278 — the mechanism, pinned where the previous test can only infer it.
+
+ The test above proves the OUTCOME (a winner that adopted the reservation is left
+ exactly as it was). This proves the PROPERTY that outcome now rests on: when the
+ release's decision read completes, this transaction already owns SQLite's writer slot,
+ so there is no instant at which an adoption can be committed between that read and the
+ reclaim it authorises. Checked the two complementary ways the HFR-262 tests use: the
+ statement sequence shows a reservation ahead of the read, and a competing writer with
+ zero patience is REFUSED at it -- which is the half that cannot be faked by emitting a
+ reservation that does not take the lock.
+ """
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ reserved_id = service.reserve_standalone_agent_session(
+ agent_backend="codex",
+ session_anchor="slack_CA:reserved",
+ workdir=str(tmp_path / "reserved-ws"),
+ )
+ with service.engine.begin() as conn:
+ _bind_definition(conn, definition_id="def-late", session_id=None)
+
+ def _adopt(other_conn) -> None: # noqa: ANN001
+ other_conn.execute(
+ run_definitions.update()
+ .where(run_definitions.c.id == "def-late")
+ .values(session_id=reserved_id, updated_at="2026-07-28T00:00:09Z")
+ )
+
+ statements = _record_statements(service.engine)
+ race = _refuse_a_competing_writer_at(
+ service.engine,
+ db_path,
+ read=_RESERVED_RELEASE_DECISION_SELECT,
+ write=_adopt,
+ )
+ released = service.release_reserved_agent_session(reserved_id, reason="lost the race")
+ finally:
+ service.close()
+
+ assert _RESERVED_RELEASE_DECISION_SELECT in statements, (
+ f"the release no longer emits the read it decides from: {statements!r}"
+ )
+ decision_at = statements.index(_RESERVED_RELEASE_DECISION_SELECT)
+ reserved_at = [index for index, sql in enumerate(statements) if sql in _WRITE_LOCK_RESERVATIONS]
+ assert reserved_at and min(reserved_at) < decision_at, (
+ f"no write-lock reservation precedes the release's decision read: {statements!r}"
+ )
+ assert race["fired"] == 1, (
+ "the competing adoption never ran inside the window, so this test proved nothing"
+ )
+ assert race["committed"] == 0, (
+ f"a competing connection ADOPTED the reserved session while the release was "
+ f"deciding it was unreferenced: {race!r}. The reclaim that follows that read then "
+ "pauses the winner's definition"
+ )
+ assert released is True, (
+ "nothing adopted the reservation, so the release must still remove it: a fix that "
+ "makes the cleanup stop working is not a fix"
+ )
diff --git a/tests/test_watches.py b/tests/test_watches.py
index 003347949..b41e17bc7 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -2151,3 +2151,1054 @@ def test_managed_watch_service_ignores_runtime_state_write_failure(tmp_path: Pat
assert saved is not None
assert saved.enabled is False
assert runtime_store.writes > 0
+
+
+#: The ``existing`` probe ``_upsert_definition`` runs before its guarded UPDATE.
+#: The competing reclaim is committed when THIS read completes, which puts it
+#: exactly inside the window the guard exists for: after the supervisor decided
+#: what to write, before the write takes the lock.
+_DEFINITION_EXISTS_SELECT = (
+ "SELECT run_definitions.id FROM run_definitions WHERE run_definitions.id = ? LIMIT ? OFFSET ?"
+)
+
+
+def _bare_watch_session_row(*, workdir: Path, anchor: str = "slack_C123") -> str:
+ """A real Session row for a watch to be bound to."""
+ from config import paths as config_paths
+ from storage.agent_session_rows import create_agent_session_row
+ from storage.db import create_sqlite_engine
+
+ engine = create_sqlite_engine(config_paths.get_sqlite_state_path())
+ try:
+ with engine.begin() as conn:
+ return create_agent_session_row(
+ conn,
+ scope_id=None,
+ session_anchor=anchor,
+ agent_backend="codex",
+ agent_variant="codex",
+ model="gpt-5.5-codex",
+ native_session_id="codex-native",
+ workdir=str(workdir),
+ require_workdir=False,
+ )
+ finally:
+ engine.dispose()
+
+
+def _commit_reclaim_after(engine, session_id: str, *, read: str, reason: str, occurrence: int = 1) -> dict:
+ """Commit the REAL ``/new`` reclaim from a genuinely separate connection.
+
+ The watch-side twin of ``_commit_competing_bind_after`` in
+ ``tests/test_sqlite_sessions_store.py``: hooks ``after_cursor_execute`` on the
+ engine the code under test uses, and when ``read`` completes opens its own
+ engine, runs ``reclaim_bound_definitions`` and COMMITS. Control returns to the
+ supervisor mid-write, so its next statement runs against a database another
+ writer has already changed. Fires once; the returned dict records it, so a
+ rendered-SQL drift shows up as "never raced" instead of a vacuous pass.
+
+ ``occurrence`` selects WHICH guarded write to race. One ``_run_watch`` iteration
+ runs several of them (``mark_cycle_start``, then ``mark_cycle_result``), and each
+ emits ``read`` once, so ``occurrence=2`` lands the reclaim inside the RESULT
+ stamp's write window -- after the start stamp has already been accepted. That is
+ the window HFR-267 is about: the cycle legitimately ran, and the teardown arrives
+ while its outcome is being recorded.
+ """
+ from sqlalchemy import event
+
+ from config import paths as config_paths
+ from storage.db import create_sqlite_engine
+ from storage.session_reclaim import RECLAIM_PAUSE, reclaim_bound_definitions
+
+ state: dict = {"fired": 0, "seen": 0, "summary": None}
+
+ @event.listens_for(engine, "after_cursor_execute")
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or " ".join(statement.split()) != read:
+ return
+ state["seen"] += 1
+ if state["seen"] < occurrence:
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(config_paths.get_sqlite_state_path())
+ try:
+ with other.begin() as other_conn:
+ state["summary"] = reclaim_bound_definitions(
+ other_conn, session_id, mode=RECLAIM_PAUSE, reason=reason
+ )
+ finally:
+ other.dispose()
+
+ return state
+
+
+def test_run_watch_stops_when_its_start_stamp_loses_to_a_reclaim(tmp_path: Path) -> None:
+ """HFR-263 — a refused ``mark_cycle_start`` must stop the cycle, not be discarded.
+
+ THE PRODUCTION STORY. A ``forever`` watch is bound to a Session. The user types
+ ``/new`` in that channel: the teardown deletes the session row and
+ ``reclaim_bound_definitions(mode='pause')`` pauses the watch and stamps its
+ settings snapshot, and ``/new`` replies "1 watch paused". The supervisor loop was
+ already past its own ``maybe_reload``, so it holds the pre-teardown mirror.
+
+ THE CONSUMING END WAS MISSING. HFR-261 made ``mark_cycle_start`` a guarded
+ full-row write that correctly REFUSES the stale payload and returns ``False`` --
+ but ``_watch_store_call`` was ``callback(); return True``, discarding the
+ callback's own return value. The refusal was reported to the loop as success, so
+ the cycle went on to spawn its waiter subprocess and enqueue a hook against the
+ definition the database had just torn down: the user is told the watch is paused
+ while it runs a command and delivers a prompt into a dead session.
+
+ Driven through the REAL ``_run_watch``, with the reclaim committed from a second
+ connection INSIDE the write window. ``_run_cycle`` is the only double, and it
+ returns a SUCCESS result on purpose: on the unfixed wrapper that is what produces
+ the enqueued hook this test forbids.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
+
+ reason = "the bound agent session was cleared"
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test needs the SQLite-backed store; the guard lives there"
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ session_id = _bare_watch_session_row(workdir=tmp_path)
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="",
+ session_id=session_id,
+ session_policy="existing",
+ command=[sys.executable, "-c", "print('event')"],
+ shell_command=None,
+ prefix="CI is green.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0.01,
+ post_to=None,
+ deliver_key=None,
+ metadata={"origin": "cli"},
+ )
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ service._running = True
+ service._requires_service_lease = False
+
+ cycles: list[str] = []
+
+ async def _spy_cycle(watch_arg, *, timeout_seconds): # noqa: ANN001
+ cycles.append(watch_arg.id)
+ return _CycleResult(exit_code=0, stdout="ci is green", stderr="", timed_out=False)
+
+ service._run_cycle = _spy_cycle # type: ignore[method-assign]
+
+ race = _commit_reclaim_after(
+ store._sqlite.engine, session_id, read=_DEFINITION_EXISTS_SELECT, reason=reason
+ )
+
+ asyncio.run(service._run_watch(watch.id))
+
+ assert race["fired"] == 1, (
+ "the competing reclaim never landed inside the write window, so this test "
+ "proved nothing; the rendered SQL of the guarded upsert's existence probe drifted"
+ )
+ assert race["summary"] == {"paused": 1, "deleted": 0, "snapshotted": 1}, (
+ f"the reclaim itself did not land ({race['summary']!r})"
+ )
+
+ assert cycles == [], (
+ "the cycle ran its command after the store refused the start stamp; the "
+ "waiter subprocess is spawned for a watch the teardown already paused"
+ )
+ assert request_store.list_pending() == [], (
+ "a hook was enqueued for a refused cycle; the prompt is delivered into the "
+ "session /new just tore down, after /new told the user the watch was paused"
+ )
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None
+ assert stored.enabled is False, (
+ "the refused start stamp re-enabled the watch the reclaim paused"
+ )
+ assert stored.last_error == reason, "the reclaim's pause reason was overwritten"
+ assert stored.last_started_at is None, (
+ "the start stamp partially landed — a lost compare-and-set must change NOTHING"
+ )
+ assert stored.last_exit_code is None and stored.last_finished_at is None, (
+ "a success-shaped cycle result was recorded for a cycle that never ran"
+ )
+ assert SESSION_SETTINGS_SNAPSHOT_KEY in stored.metadata, (
+ "the reclaim's settings snapshot was replaced by the pre-teardown metadata"
+ )
+ # HFR-271's rule: the refusal is only proven when the DURABLE row above and the LIVE
+ # store the service is still running on say the same thing. ``store`` is the object
+ # ``_run_watch`` mutated before the refused stamp, and the one ``reconcile_watches``
+ # reads next.
+ live = store.get_watch(watch.id)
+ assert live is not None and live.to_dict() == stored.to_dict(), (
+ "the start stamp was refused and the live store kept it: it serves "
+ f"enabled={None if live is None else live.enabled!r} "
+ f"last_started_at={None if live is None else live.last_started_at!r} while the "
+ f"row says enabled={stored.enabled!r} last_started_at={stored.last_started_at!r}"
+ )
+
+
+#: Sentinel ``cwd``: replaced with a path under ``tmp_path`` that is deliberately
+#: never created, so ``_missing_watch_cwd_error`` fires on the real filesystem.
+_MISSING_CWD = "<missing-cwd>"
+
+#: One row per ``_run_watch`` branch that enqueues a completion hook. ALL FIVE of
+#: them: every ``_commit_cycle_result`` call site that can produce a hook is a row
+#: here, so a branch cannot be added to production without a control below.
+#:
+#: ``cycles`` is what the doubled ``_run_cycle`` returns, one entry per call.
+#: ``occurrence`` is which guarded definition write to land the reclaim inside --
+#: every ``mark_cycle_start`` and ``mark_cycle_result`` emits the existence probe
+#: once, in order, so the number identifies the RESULT stamp of the branch under
+#: test. ``expect_hook`` is a fragment of the prompt the branch delivers, which is
+#: what proves the control run reached that branch instead of some other one.
+#: ``expect_cycle`` is False for the one branch that stops before the waiter spawns.
+_HOOK_BRANCHES: dict[str, dict] = {
+ # exit 0 -> the event fired; the watch delivers the waiter's stdout.
+ "success": {
+ "overrides": {"mode": "once", "lifetime_timeout_seconds": 0},
+ "cycles": [_CycleResult(exit_code=0, stdout="ci is green", stderr="", timed_out=False)],
+ "occurrence": 2,
+ "expect_hook": "ci is green",
+ "expect_exit_code": 0,
+ },
+ # the waiter overran its per-cycle timeout and 124 is not a retry code.
+ "cycle_timeout": {
+ "overrides": {"mode": "forever", "lifetime_timeout_seconds": 0},
+ "cycles": [_CycleResult(exit_code=124, stdout="", stderr="", timed_out=True)],
+ "occurrence": 2,
+ "expect_hook": "the waiter timed out",
+ "expect_exit_code": 124,
+ },
+ # the waiter exited non-zero with a code outside ``retry_exit_codes``.
+ "terminal_failure": {
+ "overrides": {"mode": "forever", "lifetime_timeout_seconds": 0},
+ "cycles": [_CycleResult(exit_code=2, stdout="", stderr="boom", timed_out=False)],
+ "occurrence": 2,
+ "expect_hook": "exited with code 2",
+ "expect_exit_code": 2,
+ },
+ # the supervisor's own deadline. Cycle 1 retries (75 IS a retry code) and its
+ # ``retry_delay_seconds`` sleep pushes the loop past the lifetime, so iteration 2
+ # takes the lifetime branch BEFORE it ever reaches ``mark_cycle_start``. Writes in
+ # order: start #1, retry result #2, lifetime result #3.
+ "lifetime_expiry": {
+ "overrides": {"mode": "forever", "lifetime_timeout_seconds": 0.02, "retry_delay_seconds": 0.15},
+ "cycles": [_CycleResult(exit_code=75, stdout="", stderr="not yet", timed_out=False)],
+ "occurrence": 3,
+ "expect_hook": "reached its lifetime timeout",
+ "expect_exit_code": 124,
+ },
+ # the definition's working directory is gone (a deleted worktree). The check runs
+ # right AFTER ``mark_cycle_start`` lands and before the waiter is spawned, so this
+ # is the one hook-producing branch that never runs a cycle. Writes in order:
+ # start #1, missing-cwd result #2.
+ "missing_cwd": {
+ "overrides": {"mode": "forever", "lifetime_timeout_seconds": 0, "cwd": _MISSING_CWD},
+ "cycles": [],
+ "occurrence": 2,
+ "expect_hook": "working directory is no longer available",
+ "expect_exit_code": 1,
+ "expect_cycle": False,
+ },
+}
+
+
+def _assert_branch_was_reached(branch: str, calls: list[str]) -> None:
+ """The scenario is only wired if the branch under test was actually taken.
+
+ Four branches are reached by running a cycle. ``missing_cwd`` is reached by NOT
+ running one -- a spawned waiter there would mean the run took a different path --
+ and the guarded result write the callers assert on is what proves it arrived.
+ """
+
+ if _HOOK_BRANCHES[branch].get("expect_cycle", True):
+ assert calls, f"the {branch} branch never ran a cycle, so the scenario is not wired"
+ else:
+ assert calls == [], (
+ f"the {branch} branch spawned a waiter, so the run did not take the "
+ f"missing-cwd path at all: {calls!r}"
+ )
+
+
+def _hook_branch_service(tmp_path: Path, branch: str, *, request_store=None) -> tuple:
+ """Build a real store/service/watch for one ``_HOOK_BRANCHES`` row.
+
+ ``request_store`` defaults to a file-backed outbox, which is enough for the
+ ordering tests. Pass ``TaskExecutionStore()`` for the SQLite outbox — the real
+ ``agent_runs`` ledger, and the only backend that can share a transaction with the
+ definition stamp (HFR-269).
+ """
+
+ spec = _HOOK_BRANCHES[branch]
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test needs the SQLite-backed store; the guard lives there"
+ if request_store is None:
+ request_store = TaskExecutionStore(tmp_path / f"requests_{branch}")
+ runtime_store = WatchRuntimeStateStore(tmp_path / f"runtime_{branch}.json")
+ session_id = _bare_watch_session_row(workdir=tmp_path, anchor=f"slack_C_{branch}")
+ kwargs = {
+ "name": f"Watch {branch}",
+ "session_key": "",
+ "session_id": session_id,
+ "session_policy": "existing",
+ "command": [sys.executable, "-c", "print('event')"],
+ "shell_command": None,
+ "prefix": "CI update.",
+ "cwd": None,
+ "mode": "forever",
+ "timeout_seconds": 5,
+ "lifetime_timeout_seconds": 0,
+ "retry_exit_codes": [75],
+ "retry_delay_seconds": 0.01,
+ "post_to": None,
+ "deliver_key": None,
+ "metadata": {"origin": "cli"},
+ }
+ kwargs.update(spec["overrides"])
+ if kwargs.get("cwd") == _MISSING_CWD:
+ # Never created on purpose: the production check is a real ``Path.is_dir()``.
+ kwargs["cwd"] = str(tmp_path / f"removed_worktree_{branch}")
+ watch = store.add_watch(**kwargs)
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+ service._running = True
+ service._requires_service_lease = False
+
+ results = list(spec["cycles"])
+ calls: list[str] = []
+
+ async def _spy_cycle(watch_arg, *, timeout_seconds): # noqa: ANN001
+ calls.append(watch_arg.id)
+ return results[min(len(calls) - 1, len(results) - 1)]
+
+ service._run_cycle = _spy_cycle # type: ignore[method-assign]
+ return store, service, watch, request_store, session_id, calls
+
+
[email protected]("branch", list(_HOOK_BRANCHES))
+def test_run_watch_enqueues_the_branch_hook_when_the_result_stamp_lands(tmp_path: Path, branch: str) -> None:
+ """HFR-267 control — with no teardown racing it, every branch DOES deliver its hook.
+
+ Without this, the refusal tests below could pass because the branch was never
+ reached at all. Here the same wiring, minus the reclaim, must enqueue exactly one
+ hook carrying that branch's own text.
+ """
+ _store, service, watch, request_store, _session_id, calls = _hook_branch_service(tmp_path, branch)
+
+ asyncio.run(service._run_watch(watch.id))
+
+ _assert_branch_was_reached(branch, calls)
+ pending = request_store.list_pending()
+ assert len(pending) == 1, f"the {branch} branch enqueued {len(pending)} hooks, expected exactly 1"
+ assert _HOOK_BRANCHES[branch]["expect_hook"] in (pending[0].prompt or ""), (
+ f"the enqueued hook is not the {branch} branch's: {pending[0].prompt!r}"
+ )
+
+
[email protected]("branch", list(_HOOK_BRANCHES))
+def test_run_watch_enqueues_no_hook_when_the_result_stamp_is_refused(tmp_path: Path, branch: str) -> None:
+ """HFR-267 — the guarded stamp must run BEFORE the hook it authorises, in every branch.
+
+ THE PRODUCTION STORY. A watch is bound to a Session and its cycle completes. In the
+ same instant the user types ``/new`` in that channel: the teardown deletes the
+ session row, ``reclaim_bound_definitions(mode='pause')`` pauses the watch, and
+ ``/new`` replies "1 watch paused".
+
+ THE GUARD WAS ASKED TOO LATE. HFR-261 made ``mark_cycle_result`` a guarded
+ compare-and-set and HFR-263 taught ``_watch_store_call`` to honour its refusal --
+ but all four hook-enqueueing branches ran
+
+ self._enqueue_hook(...) # durable request row, now unrecallable
+ if not self._watch_store_call(..., guarded=True):
+ return # refused; unqueues nothing
+
+ ``enqueue_hook_send`` writes a row a separate drain loop claims and executes, so
+ ``return`` after the refusal cancels nothing: the prompt is still delivered into
+ the session ``/new`` just deleted, for a definition the database has torn down,
+ after the user was told the watch was paused. Respecting the guard's answer is not
+ enough -- the effect has to come after the guard.
+
+ Driven through the REAL ``_run_watch``, with the real ``/new`` reclaim committed
+ from a second connection INSIDE the result stamp's write window. ``_run_cycle`` is
+ the only double, and it returns each branch's own success/timeout/failure shape on
+ purpose: on the unfixed ordering that is exactly what produces the hook this test
+ forbids.
+ """
+ from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
+
+ reason = "the bound agent session was cleared"
+ store, service, watch, request_store, session_id, calls = _hook_branch_service(tmp_path, branch)
+
+ race = _commit_reclaim_after(
+ store._sqlite.engine,
+ session_id,
+ read=_DEFINITION_EXISTS_SELECT,
+ reason=reason,
+ occurrence=_HOOK_BRANCHES[branch]["occurrence"],
+ )
+
+ asyncio.run(service._run_watch(watch.id))
+
+ assert race["fired"] == 1, (
+ f"the competing reclaim never landed inside the {branch} result stamp's write "
+ f"window (saw {race['seen']} guarded writes, wanted #{_HOOK_BRANCHES[branch]['occurrence']}), "
+ "so this test proved nothing"
+ )
+ assert race["summary"] == {"paused": 1, "deleted": 0, "snapshotted": 1}, (
+ f"the reclaim itself did not land ({race['summary']!r})"
+ )
+ _assert_branch_was_reached(branch, calls)
+
+ assert request_store.list_pending() == [], (
+ f"the {branch} branch enqueued a hook for a cycle result the store REFUSED; the "
+ "prompt is delivered into the session /new just tore down, after /new told the "
+ "user the watch was paused"
+ )
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None
+ assert stored.enabled is False, "the refused result stamp re-enabled the watch the reclaim paused"
+ assert stored.last_error == reason, "the reclaim's pause reason was overwritten by the refused stamp"
+ assert SESSION_SETTINGS_SNAPSHOT_KEY in stored.metadata, (
+ "the reclaim's settings snapshot was replaced by the pre-teardown metadata"
+ )
+ # HFR-271's rule, on the live half a fresh store cannot see.
+ live = service.store.get_watch(watch.id)
+ assert live is not None and live.to_dict() == stored.to_dict(), (
+ "the result stamp was refused and the live store kept it: it serves "
+ f"enabled={None if live is None else live.enabled!r} "
+ f"retired_at={None if live is None else live.retired_at!r} while the row says "
+ f"enabled={stored.enabled!r} retired_at={stored.retired_at!r}"
+ )
+
+
+#: The outbox row's own INSERT. Matched by prefix so a new ``agent_runs`` column
+#: cannot silently stop these tests from racing anything.
+_AGENT_RUNS_INSERT = "INSERT INTO AGENT_RUNS"
+
+
+def _is_agent_runs_insert(statement: str) -> bool:
+ return " ".join(statement.split()).upper().startswith(_AGENT_RUNS_INSERT)
+
+
+def _try_archive_before_the_outbox_insert(engines, session_id: str, *, reason: str) -> dict:
+ """Try to commit the REAL archive teardown in the gap before the outbox INSERT.
+
+ Hooks ``before_cursor_execute`` on every engine the code under test might write the
+ ``agent_runs`` row through — the watch store's and the request store's, because
+ WHICH one carries the INSERT is exactly what this test is about — and when that
+ INSERT is about to run, opens its own engine and commits
+ ``reclaim_bound_definitions(mode='delete')`` from a genuinely separate connection.
+
+ ``PRAGMA busy_timeout = 0`` is what turns the outcome into a FACT instead of a five
+ second sleep: at this instant the result stamp has already been decided, so if the
+ stamp was its OWN transaction the database is unlocked and the teardown commits
+ immediately; if the stamp and this INSERT are one transaction the write lock is
+ already held and SQLite refuses at once with "database is locked". ``blocked``
+ records which of the two happened, so "there is no gap" is asserted rather than
+ assumed, and a rendered-SQL drift shows up as "never raced".
+ """
+ from sqlalchemy import event
+ from sqlalchemy.exc import OperationalError
+
+ from config import paths as config_paths
+ from storage.db import create_sqlite_engine
+ from storage.session_reclaim import RECLAIM_DELETE, reclaim_bound_definitions
+
+ state: dict = {"fired": 0, "blocked": None, "summary": None}
+
+ def _race(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if state["fired"] or not _is_agent_runs_insert(statement):
+ return
+ state["fired"] += 1
+ other = create_sqlite_engine(config_paths.get_sqlite_state_path())
+ try:
+ with other.begin() as other_conn:
+ other_conn.exec_driver_sql("PRAGMA busy_timeout = 0")
+ state["summary"] = reclaim_bound_definitions(
+ other_conn, session_id, mode=RECLAIM_DELETE, reason=reason
+ )
+ state["blocked"] = False
+ except OperationalError as exc:
+ # Serialised behind the transaction that holds the stamp: the teardown
+ # cannot land in between, which is the property under test.
+ state["blocked"] = True
+ state["detail"] = str(exc)
+ finally:
+ other.dispose()
+
+ for engine in engines:
+ event.listens_for(engine, "before_cursor_execute")(_race)
+ return state
+
+
+def _fail_the_outbox_insert(engines) -> dict:
+ """Make the outbox row's INSERT fail, wherever the code under test writes it."""
+ from sqlalchemy import event
+
+ state: dict = {"fired": 0}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if not _is_agent_runs_insert(statement):
+ return
+ state["fired"] += 1
+ raise RuntimeError("outbox write failed: disk I/O error")
+
+ for engine in engines:
+ event.listens_for(engine, "before_cursor_execute")(_boom)
+ return state
+
+
+def _hook_branch_service_on_the_run_ledger(tmp_path: Path, branch: str) -> tuple:
+ """``_hook_branch_service`` on the SQLite outbox — the real ``agent_runs`` ledger."""
+
+ request_store = TaskExecutionStore()
+ assert request_store._sqlite is not None, "this test needs the SQLite outbox; a transaction is the fix"
+ store, service, watch, request_store, session_id, calls = _hook_branch_service(
+ tmp_path, branch, request_store=request_store
+ )
+ assert store._sqlite.db_path == request_store._sqlite.db_path, (
+ "the definition and the outbox must be in ONE database for a shared transaction "
+ "to be possible at all"
+ )
+ engines = [store._sqlite.engine, request_store._sqlite.engine]
+ return store, service, watch, request_store, session_id, calls, engines
+
+
[email protected]("branch", list(_HOOK_BRANCHES))
+def test_the_atomic_stamp_and_its_hook_both_land_when_nothing_races_them(tmp_path: Path, branch: str) -> None:
+ """HFR-269 control — with nothing racing and nothing faulting, BOTH halves land.
+
+ A combined operation that simply refused everything would satisfy the two tests
+ below vacuously: "no hook was queued" and "the watch was not retired" are precisely
+ what a ``_commit_cycle_result`` that always returned False, or an
+ ``upsert_watch_with_queued_run`` that never committed, would produce. So each
+ terminal branch needs its positive half too, and this is it -- the same real
+ ``_run_watch`` over the same real ``agent_runs`` ledger, with NO teardown racing the
+ write and NO injected outbox fault. The one transaction must COMMIT, carrying both
+ of the things it makes atomic:
+
+ * the branch's own result transition, read back from the definition (that branch's
+ terminal exit code, disabled, retired, finished), and
+ * exactly ONE outbox row, carrying that branch's OWN prompt text -- so a branch
+ cannot be credited with a row some other branch wrote, and "exactly one" rules
+ out the atomic write and the fallback ``enqueue`` both firing.
+
+ Parametrized over every row of ``_HOOK_BRANCHES``, which is every hook-producing
+ ``_commit_cycle_result`` call site in ``_run_watch``: success, per-cycle timeout,
+ terminal failure, lifetime expiry, and missing cwd.
+ """
+ _store, service, watch, request_store, _session_id, calls, _engines = (
+ _hook_branch_service_on_the_run_ledger(tmp_path, branch)
+ )
+
+ asyncio.run(service._run_watch(watch.id))
+
+ _assert_branch_was_reached(branch, calls)
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None, f"the {branch} branch's definition is gone"
+ assert stored.last_exit_code == _HOOK_BRANCHES[branch]["expect_exit_code"], (
+ f"the {branch} branch's result transition did not commit: the definition records "
+ f"exit {stored.last_exit_code!r}, not {_HOOK_BRANCHES[branch]['expect_exit_code']!r}"
+ )
+ assert stored.enabled is False and stored.retired_at is not None, (
+ f"the {branch} branch is terminal, but the definition is still enabled/unretired "
+ f"(enabled={stored.enabled!r}, retired_at={stored.retired_at!r}): the stamp was "
+ "refused or rolled back when nothing opposed it"
+ )
+ assert stored.last_finished_at is not None, (
+ f"the {branch} branch's stamp committed without recording that the cycle finished"
+ )
+
+ pending = request_store.list_pending()
+ assert len(pending) == 1, (
+ f"the {branch} branch queued {len(pending)} hooks on the run ledger, expected "
+ "exactly 1; with nothing racing it, the hook the branch authorises must be durable"
+ )
+ assert _HOOK_BRANCHES[branch]["expect_hook"] in (pending[0].prompt or ""), (
+ f"the queued hook is not the {branch} branch's own: {pending[0].prompt!r}"
+ )
+ assert pending[0].task_id == watch.id, (
+ f"the queued hook belongs to {pending[0].task_id!r}, not to the watch under test"
+ )
+
+
[email protected]("branch", list(_HOOK_BRANCHES))
+def test_no_teardown_can_commit_between_the_result_stamp_and_its_hook(tmp_path: Path, branch: str) -> None:
+ """HFR-269 — the stamp and the hook it authorises must be ONE transaction.
+
+ THE PRODUCTION STORY. A watch bound to a Session finishes a cycle. In the same
+ instant the user archives that Session: the archive runs
+ ``reclaim_bound_definitions(mode='delete')``, which soft-deletes the watch, and the
+ confirm dialog reports it.
+
+ ORDERING WAS NOT ENOUGH. HFR-267 put the guarded stamp before the hook, so the
+ guard now runs before the effect it authorises — but the two are separate
+ transactions:
+
+ self.store.mark_cycle_result(...) # transaction 1, COMMITS
+ self.request_store.enqueue_hook_send(...) # transaction 2, COMMITS
+
+ and the archive commits in the GAP between those commits. The stamp is accepted —
+ it won its compare-and-set fairly, against the state that existed when it ran — and
+ the hook is queued afterwards anyway: a durable request row the drain loop will
+ deliver into a session that no longer exists, under a definition the database has
+ soft-deleted, after the user was told the archive was done. Nothing is refused,
+ because by the time the teardown lands there is nothing left to refuse.
+
+ Driven through the REAL ``_run_watch`` over the REAL ``agent_runs`` ledger, with the
+ real archive reclaim attempted from a second connection at the instant the outbox
+ INSERT is about to run, and a zero busy timeout so "could it commit in the gap?" is
+ answered by the database rather than by a sleep. Green requires that it could NOT:
+ the write lock the stamp took is still held, so the teardown is serialised behind
+ the single transaction and can only land before the stamp (where HFR-267's tests
+ show it is refused) or after the hook is already durable.
+ """
+ store, service, watch, request_store, session_id, calls, engines = (
+ _hook_branch_service_on_the_run_ledger(tmp_path, branch)
+ )
+
+ race = _try_archive_before_the_outbox_insert(
+ engines, session_id, reason="the session was archived"
+ )
+
+ outcome: dict = {}
+ try:
+ asyncio.run(service._run_watch(watch.id))
+ except Exception as exc: # noqa: BLE001 - the split-transaction path can also fault here
+ outcome["error"] = exc
+
+ _assert_branch_was_reached(branch, calls)
+ assert race["fired"] == 1, (
+ f"the {branch} branch never wrote an outbox row, so this test proved nothing; "
+ "the rendered SQL of the run INSERT drifted"
+ )
+ assert race["blocked"] is True, (
+ f"the archive teardown COMMITTED between the {branch} branch's result stamp and "
+ f"its hook ({race['summary']!r}): the two are separate transactions, so a "
+ "reclaim lands in the gap and the hook is queued anyway — delivered into the "
+ "session the archive removed, under a definition it soft-deleted"
+ )
+ assert not outcome, f"the atomic stamp+hook write faulted: {outcome.get('error')!r}"
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None
+ assert stored.enabled is False and stored.retired_at is not None, (
+ f"the {branch} branch's terminal stamp did not land with its hook"
+ )
+ assert stored.last_exit_code == _HOOK_BRANCHES[branch]["expect_exit_code"], (
+ f"the stamp recorded exit {stored.last_exit_code!r} for the {branch} branch"
+ )
+ pending = request_store.list_pending()
+ assert len(pending) == 1, f"the {branch} branch queued {len(pending)} hooks, expected exactly 1"
+ assert _HOOK_BRANCHES[branch]["expect_hook"] in (pending[0].prompt or ""), (
+ f"the queued hook is not the {branch} branch's: {pending[0].prompt!r}"
+ )
+
+
[email protected]("branch", list(_HOOK_BRANCHES))
+def test_a_failed_outbox_write_does_not_retire_the_watch_with_its_hook_lost(
+ tmp_path: Path, branch: str
+) -> None:
+ """HFR-269, inverse half — the other thing two commits cost.
+
+ Same scenario id as ``test_no_teardown_can_commit_between_the_result_stamp_and_its_hook``:
+ one defect (the stamp and its outbox row are not one transaction) with two failure
+ halves, tested separately because they fail for opposite reasons -- that one needs a
+ teardown racing the gap, this one needs no race at all, just a fault on the second
+ commit.
+
+ HFR-267's ordering traded one failure for another. With the stamp committed first
+ and the hook second, a fault on the outbox write — a full disk, a locked database,
+ any error between the two commits — leaves the watch DURABLY DISABLED and retired
+ while the hook that tells the user it finished is gone. A ``once`` watch is
+ unrecoverable at that point: the definition says "finished", the user was never
+ told, and nothing will run it again.
+
+ One transaction removes the trade instead of reversing it: the outbox INSERT and the
+ stamp roll back together, so the watch stays enabled and its completion is still
+ owed. The fault is injected at the INSERT itself, on whichever connection the code
+ under test writes the row through.
+ """
+ store, service, watch, request_store, _session_id, calls, engines = (
+ _hook_branch_service_on_the_run_ledger(tmp_path, branch)
+ )
+
+ boom = _fail_the_outbox_insert(engines)
+
+ outcome: dict = {}
+ try:
+ asyncio.run(service._run_watch(watch.id))
+ except Exception as exc: # noqa: BLE001 - the unfixed path lets the fault escape the loop
+ outcome["error"] = exc
+
+ _assert_branch_was_reached(branch, calls)
+ assert boom["fired"] >= 1, (
+ f"the {branch} branch never attempted an outbox INSERT, so no fault was injected"
+ )
+ assert request_store.list_pending() == [], "the failed INSERT queued a hook anyway"
+
+ stored = ManagedWatchStore().get_watch(watch.id)
+ assert stored is not None
+ assert stored.enabled is True, (
+ f"the {branch} branch retired the watch while the hook that reports its outcome "
+ "was lost to the failed outbox write; a once watch is finished, silent and "
+ "unrecoverable"
+ )
+ assert stored.retired_at is None and stored.last_finished_at is None, (
+ "a terminal cycle result survived the failure of the hook it authorises"
+ )
+
+ # HFR-271 — AND THE OTHER HALF OF "IT ROLLED BACK". Everything above reads the
+ # DURABLE row through a store this test just built. That is the half that was never
+ # in doubt once the write became one transaction; the half that stayed wrong is the
+ # SERVICE STILL RUNNING, whose ``ManagedWatch`` mirror ``mark_cycle_result`` mutated
+ # BEFORE the write it then lost. A rollback is not proven by re-reading the row.
+ live = service.store.get_watch(watch.id)
+ assert live is not None, "the live store dropped the watch the database still has"
+ assert (live.enabled, live.retired_at, live.last_finished_at) == (
+ stored.enabled,
+ stored.retired_at,
+ stored.last_finished_at,
+ ), (
+ "the transaction rolled back and the LIVE store did not: it reports "
+ f"enabled={live.enabled!r} retired_at={live.retired_at!r} "
+ f"last_finished_at={live.last_finished_at!r} while the durable row says "
+ f"enabled={stored.enabled!r} retired_at={stored.retired_at!r} "
+ f"last_finished_at={stored.last_finished_at!r}. Every in-process reader "
+ "(``reconcile_watches`` decides which watches to keep running from exactly "
+ "this mirror) believes a watch retired that the database never retired"
+ )
+ assert live.last_exit_code == stored.last_exit_code, (
+ f"the live mirror kept the rolled-back exit code {live.last_exit_code!r}"
+ )
+
+
+#: Any full-row write of a definition. Prefix-matched on both statement shapes so a
+#: column change cannot silently stop the fault from being injected.
+_DEFINITION_WRITES = ("UPDATE RUN_DEFINITIONS", "INSERT INTO RUN_DEFINITIONS")
+
+
+def _fail_the_definition_write(engine) -> dict:
+ """Make the ``run_definitions`` write itself fail, the way a real fault would."""
+ from sqlalchemy import event
+
+ state: dict = {"fired": 0}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ normalized = " ".join(statement.split()).upper()
+ if not normalized.startswith(_DEFINITION_WRITES):
+ return
+ state["fired"] += 1
+ raise RuntimeError("definition write failed: disk I/O error")
+
+ event.listens_for(engine, "before_cursor_execute")(_boom)
+ return state
+
+
+#: Every guarded writer that mutates the cached ``ManagedWatch`` before persisting it.
+#: The value applies the writer and returns the fields it was supposed to change.
+_MIRROR_WRITERS = {
+ "mark_cycle_start": lambda store, watch_id: store.mark_cycle_start(watch_id),
+ "mark_cycle_result": lambda store, watch_id: store.mark_cycle_result(
+ watch_id, exit_code=0, error=None, disable=True
+ ),
+ "set_enabled": lambda store, watch_id: store.set_enabled(watch_id, False),
+ "update_watch": lambda store, watch_id: store.update_watch(
+ watch_id,
+ **{**_WATCH_FIXTURE_PAYLOAD, "name": "renamed", "session_id": None},
+ ),
+}
+
+#: Values a round trip through ``run_definitions`` returns unchanged, so a baseline
+#: mismatch cannot be mistaken for a mirror the failed write left ahead.
+_WATCH_FIXTURE_PAYLOAD = {
+ "name": "original",
+ "session_key": "slack::channel::C1",
+ "command": ["true"],
+ "shell_command": None,
+ "prefix": None,
+ "cwd": None,
+ "mode": "once",
+ "timeout_seconds": 1.0,
+ "lifetime_timeout_seconds": 0.0,
+ "retry_exit_codes": [75],
+ "retry_delay_seconds": 30.0,
+ "post_to": None,
+ "deliver_key": None,
+}
+
+
[email protected]("writer", list(_MIRROR_WRITERS))
+def test_a_definition_write_that_raises_leaves_no_live_mirror_ahead_of_the_database(
+ tmp_path: Path, writer: str
+) -> None:
+ """HFR-271 — when the write raises, the in-process mirror must roll back with it.
+
+ THE RULE THIS TEST EXISTS FOR. ``ManagedWatchStore`` is a WRITE-THROUGH CACHE: every
+ writer below edits the cached ``ManagedWatch`` first and hands the whole row to
+ ``_write_watch`` second. ``_write_watch`` already reloads when the compare-and-set
+ RETURNS ``False`` — and only then. When the write RAISES, the mirror keeps edits the
+ database rolled back, and the process goes on serving them: ``reconcile_watches``
+ picks which watches keep running out of exactly this dict, ``vibe watch list``
+ renders it, and the next guarded write derives its ``expect`` snapshot from it
+ (``_read_state``), so a stale mirror also sends the NEXT compare-and-set the wrong
+ expectation.
+
+ Nothing about that is specific to the outbox fault HFR-269 found; the outbox fault is
+ just the first caller that made the raising path reachable in a test. So this is
+ parametrized over EVERY guarded writer that goes through the shared choke point, and
+ the fault is injected at the ``run_definitions`` statement itself — a disk error, a
+ locked database, anything — rather than at one caller's second write.
+ """
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ watch = store.add_watch(**_WATCH_FIXTURE_PAYLOAD)
+
+ durable_before = ManagedWatchStore().get_watch(watch.id)
+ live_before = store.get_watch(watch.id)
+ assert durable_before is not None and live_before is not None
+ assert live_before.to_dict() == durable_before.to_dict(), (
+ "the fixture starts with the mirror already disagreeing with the row, so the "
+ "assertion below would pass or fail for the wrong reason"
+ )
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ _MIRROR_WRITERS[writer](store, watch.id)
+
+ assert boom["fired"] >= 1, (
+ f"{writer} never wrote a run_definitions row, so no fault was injected and this "
+ "test proves nothing"
+ )
+
+ durable_after = ManagedWatchStore().get_watch(watch.id)
+ assert durable_after is not None
+ assert durable_after.to_dict() == durable_before.to_dict(), (
+ f"{writer} committed something despite the injected fault; this test can no "
+ "longer tell a rolled-back mirror from a written one"
+ )
+
+ live = store.get_watch(watch.id)
+ assert live is not None, f"{writer} dropped the watch from the live store"
+ assert live.to_dict() == durable_after.to_dict(), (
+ f"{writer} left the live mirror ahead of the database. The transaction rolled "
+ "back; the cached ManagedWatch kept the edit. Differing fields: "
+ + repr(
+ {
+ key: (value, durable_after.to_dict().get(key))
+ for key, value in live.to_dict().items()
+ if durable_after.to_dict().get(key) != value
+ }
+ )
+ )
+
+
+def test_a_failed_create_leaves_no_phantom_watch_in_the_live_store() -> None:
+ """HFR-275 — the create entry point must roll its mirror back as well.
+
+ ``upsert_watch`` is the one writer that can put an id in the mirror the database has
+ NEVER seen, and it inserted into ``self._watches`` before writing. It is also the
+ worst place to leave a mirror ahead: the caller is told the watch could not be
+ created, while ``reconcile_watches`` -- which picks what to run out of exactly this
+ dict -- STARTS it, spawning its command and posting its output on every tick, with no
+ durable row to stop it and nothing that will ever reload it away.
+ """
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ before = {watch.id for watch in store.list_watches()}
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.add_watch(**_WATCH_FIXTURE_PAYLOAD)
+
+ assert boom["fired"] >= 1, "no run_definitions write was attempted, so nothing failed"
+ phantom = {watch.id for watch in store.list_watches()} - before
+ assert not phantom, (
+ f"the failed create left {sorted(phantom)} in the live store: a watch the "
+ "database never accepted, that reconcile_watches will start running anyway"
+ )
+ assert not {watch.id for watch in ManagedWatchStore().list_watches()} - before, (
+ "the create committed despite the injected fault, so this test proves nothing"
+ )
+
+
+def test_a_failed_delete_does_not_stop_a_watch_the_database_still_has() -> None:
+ """HFR-275 — the delete entry point, the same class in the safer direction.
+
+ ``remove_watch`` drops the entry before the soft delete. The failure direction is the
+ conservative one (absent reads as "gone" and stops the watch), but it is silent and
+ it does NOT heal: the row is still there and UNCHANGED, so ``maybe_reload`` sees no
+ external write, and the watch the user was told could not be deleted simply stops
+ until the process restarts.
+ """
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ watch = store.add_watch(**_WATCH_FIXTURE_PAYLOAD)
+ boom = _fail_the_definition_write(store._sqlite.engine)
+
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.remove_watch(watch.id)
+
+ assert boom["fired"] >= 1, "no run_definitions write was attempted, so nothing failed"
+ durable = ManagedWatchStore().get_watch(watch.id)
+ assert durable is not None, (
+ "the delete committed despite the injected fault, so this test proves nothing"
+ )
+ live = store.get_watch(watch.id)
+ assert live is not None, (
+ f"the failed delete dropped watch {watch.id} from the live store while the "
+ "database still has it: it stops running, silently, until the process restarts"
+ )
+ assert live.to_dict() == durable.to_dict()
+
+
+#: The list read ``ManagedWatchStore.load`` issues -- the only ``run_definitions``
+#: SELECT that filters by ``definition_type`` -- so the guard's own
+#: ``SELECT id ... LIMIT 1`` still runs and the write is genuinely ATTEMPTED.
+_DEFINITION_LIST_READ_MARKERS = ("FROM RUN_DEFINITIONS", "DEFINITION_TYPE = ?")
+
+
+def _fail_the_definition_write_and_the_reload(engine) -> dict:
+ """A transient fault that takes out the guarded write AND the recovery read.
+
+ The task store's twin helper. Flip ``state["live"]`` to ``False`` to end the fault
+ WITHOUT committing anything: a commit would bump ``PRAGMA data_version`` and heal the
+ mirror for a reason that has nothing to do with the fix.
+ """
+ from sqlalchemy import event
+
+ state: dict = {"writes": 0, "reads": 0, "live": True}
+
+ def _boom(conn, cursor, statement, parameters, context, executemany) -> None: # noqa: ANN001
+ if not state["live"]:
+ return
+ normalized = " ".join(statement.split()).upper()
+ if normalized.startswith(("UPDATE RUN_DEFINITIONS", "INSERT INTO RUN_DEFINITIONS")):
+ state["writes"] += 1
+ raise RuntimeError("definition write failed: disk I/O error")
+ if all(marker in normalized for marker in _DEFINITION_LIST_READ_MARKERS):
+ state["reads"] += 1
+ raise RuntimeError("definition read failed: disk I/O error")
+
+ event.listens_for(engine, "before_cursor_execute")(_boom)
+ return state
+
+
+def test_a_dropped_watch_mirror_recovers_with_no_unrelated_commit_to_wake_it() -> None:
+ """HFR-277 — the consuming end of HFR-271's own recovery path.
+
+ THE DEFECT, and it is one WE introduced. ``_reload_after_lost_write`` drops the
+ cached ``ManagedWatch`` when the guarded write fails and the immediate recovery
+ ``load`` fails with it -- deliberately, because an absent watch reads as "gone" to
+ ``reconcile_watches`` and stops it, where a stale one keeps running against state the
+ database never had -- and promises ``maybe_reload`` restores it "as soon as the
+ database is reachable again". It did not. ``maybe_reload`` asked only
+ ``SqliteInvalidationProbe`` (``PRAGMA data_version``), which moves when another
+ connection COMMITS; the failed write ROLLED BACK, so it never moved. Every later
+ supervisor tick answered "nothing changed" and the watch stayed durably enabled in
+ SQLite and invisible in-process until the service restarted.
+
+ THE CLAUSE THAT IS THE TEST: nothing commits between the failure and the recovery.
+ A witness probe on its own connection asserts data_version is unchanged at that
+ instant, so a mirror that comes back did so because the store remembered it must
+ reload -- not because an unrelated writer woke it up.
+ """
+ from storage.db import SqliteInvalidationProbe, create_sqlite_engine
+
+ store = ManagedWatchStore()
+ assert store._sqlite is not None, "this test is about the guarded SQLite path"
+ watch = store.add_watch(**_WATCH_FIXTURE_PAYLOAD)
+ durable_before = ManagedWatchStore().get_watch(watch.id)
+ assert durable_before is not None and durable_before.enabled, (
+ "the fixture must start from a definition the database has, and has enabled"
+ )
+
+ # Settle the store's own probe on the fixture's commits first: a pending
+ # data_version bump would reload the mirror below for the wrong reason.
+ store.maybe_reload()
+ assert store.maybe_reload() is False, "the store's probe is not settled"
+ witness_engine = create_sqlite_engine(store._sqlite.db_path)
+ witness = SqliteInvalidationProbe(witness_engine)
+ witness.has_external_write()
+ assert witness.has_external_write() is False, "the witness probe is not settled"
+
+ fault = _fail_the_definition_write_and_the_reload(store._sqlite.engine)
+ try:
+ with pytest.raises(Exception): # noqa: B017 - the fault type is the injected one's
+ store.mark_cycle_start(watch.id)
+
+ assert fault["writes"] >= 1, "no run_definitions write was attempted"
+ assert fault["reads"] >= 1, (
+ "the recovery reload was never attempted, so the entry was not dropped for "
+ "the reason this test is about"
+ )
+ assert store.get_watch(watch.id) is None, (
+ "the failed write did not drop the mirror entry, so there is nothing for "
+ "maybe_reload to recover and this test proves nothing"
+ )
+ assert [item.id for item in store.list_watches()] == [], (
+ "the dropped entry is still listed; the precondition is a mirror that has "
+ "LOST the definition"
+ )
+
+ # The fault clears the way a transient one does: nothing is written.
+ fault["live"] = False
+ assert witness.has_external_write() is False, (
+ "something COMMITTED between the failed write and the reload below. A "
+ "data_version bump heals the mirror on its own, so this test would pass "
+ "without the fix"
+ )
+
+ assert store.maybe_reload() is True, (
+ "maybe_reload reported 'nothing changed' for a mirror the store itself knows "
+ "is incomplete. data_version cannot see a rolled-back write, so the dropped "
+ "watch stays invisible to reconcile_watches until the process restarts"
+ )
+ live = store.get_watch(watch.id)
+ assert live is not None, (
+ f"watch {watch.id} is still missing from the live store after a reload; it is "
+ "enabled in SQLite and will never be reconciled again"
+ )
+ assert live.to_dict() == durable_before.to_dict(), (
+ "the recovered entry does not match the durable row. Differing fields: "
+ + repr(
+ {
+ key: (value, durable_before.to_dict().get(key))
+ for key, value in live.to_dict().items()
+ if durable_before.to_dict().get(key) != value
+ }
+ )
+ )
+ assert [item.id for item in store.list_watches()] == [watch.id]
+ assert store.maybe_reload() is False, (
+ "the store keeps reloading unconditionally; the flag must be cleared by the "
+ "reload that repaired the mirror"
+ )
+ finally:
+ witness.close()
+ witness_engine.dispose()
+
+ durable_after = ManagedWatchStore().get_watch(watch.id)
+ assert durable_after is not None and durable_after.to_dict() == durable_before.to_dict(), (
+ "the durable row changed, so the failed write committed something and the "
+ "recovery above was reading a different definition than the one that was dropped"
+ )
diff --git a/vibe/cli.py b/vibe/cli.py
index 8afbf2ccd..e43574e96 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -35,6 +35,7 @@ from sqlalchemy import select
from config import SettingsStore, paths
from config.v2_config import V2Config
from core.scheduled_tasks import (
+ BINDING_FOLLOWS_SESSION_METADATA_KEY,
ScheduledTaskStore,
TaskExecutionStore,
parse_scope_id,
@@ -66,6 +67,7 @@ from vibe.upgrade import (
)
from storage.db import create_sqlite_engine
from storage.background import (
+ DefinitionWriteConflict,
SQLiteBackgroundTaskStore,
compute_next_run_at,
normalize_run_status,
@@ -211,6 +213,33 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non
print(json.dumps(payload, indent=2), file=sys.stderr)
+def _definition_conflict_cli_error(
+ exc: DefinitionWriteConflict,
+ *,
+ help_command: str,
+ details: dict | None = None,
+) -> TaskCliError:
+ """A refused full-row write, told to the user as a first-class command failure.
+
+ The store writes EVERY column of a definition, so an update built from a read
+ that a teardown has since invalidated is refused rather than applied (HFR-261).
+ That refusal has to reach the user with its own code: without it the command
+ would print the definition it *meant* to write and exit 0, while the stored row
+ still holds whatever ``/new`` or the archive dialog put there.
+ """
+
+ return TaskCliError(
+ str(exc),
+ code="definition_write_conflict",
+ hint=(
+ "A /new clear or a Session archive reclaimed this definition while the "
+ "update was being prepared. Re-read it and re-apply the change."
+ ),
+ help_command=help_command,
+ details=details or {"definition_id": exc.definition_id},
+ )
+
+
def _cli_payload(kind: str, **fields) -> dict:
return {"schema_version": 1, "ok": True, "kind": kind, **fields}
@@ -2859,7 +2888,20 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):
)
)
return 1
- updated = store.set_enabled(task_id, enabled)
+ try:
+ updated = store.set_enabled(task_id, enabled)
+ except DefinitionWriteConflict as exc:
+ # Pause/resume is also a full-row write, so it is refused when a teardown
+ # changed the definition first. Reporting the switch as flipped would be a lie
+ # about a row this command did not write.
+ _print_task_error(
+ _definition_conflict_cli_error(
+ exc,
+ help_command="vibe task list",
+ details={"task_id": task_id},
+ )
+ )
+ return 1
task_payload = _task_payload(updated)
_print_definition_payload(task_payload)
return 0
@@ -2973,6 +3015,25 @@ def cmd_task_update(args):
else:
name = task.name
+ # Rejected rather than silently resolved, exactly as ``--name`` /
+ # ``--clear-name`` above. The two flags mean opposite things and the pair had
+ # no single sensible reading: ``--clear-agent`` won for ``agent_name`` (→
+ # None) while the mere PRESENCE of ``--agent`` set
+ # ``explicit_agent_requested``, which POPS the follow-the-session marker. The
+ # definition then looked like "no Agent pinned and not following its
+ # Session", so the resolve below wrote today's scope / default Agent back as
+ # a hard pin — the exact regression the marker exists to prevent (HFR-245),
+ # reachable in one command.
+ if getattr(args, "agent", None) is not None and getattr(args, "clear_agent", False):
+ raise TaskCliError(
+ "use either --agent or --clear-agent, not both",
+ code="conflicting_agent_update",
+ hint=(
+ "Pin an Agent with --agent, or hand Agent authority back to the bound "
+ "Session with --clear-agent."
+ ),
+ help_command="vibe task update --help",
+ )
if getattr(args, "clear_agent", False):
agent_name = None
elif getattr(args, "agent", None) is not None:
@@ -2980,6 +3041,16 @@ def cmd_task_update(args):
else:
agent_name = task.agent_name
+ # "Follow the bound Session's Agent" is a durable state (set by a reset
+ # rebind, or by ``--clear-agent``), not merely a missing ``agent_name``.
+ # An explicit ``--agent`` is the user pinning again, so it ends the state.
+ explicit_agent_requested = getattr(args, "agent", None) is not None
+ if explicit_agent_requested:
+ metadata.pop(BINDING_FOLLOWS_SESSION_METADATA_KEY, None)
+ elif getattr(args, "clear_agent", False):
+ metadata[BINDING_FOLLOWS_SESSION_METADATA_KEY] = True
+ follows_session_agent = bool(metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY))
+
message_changed = any(
getattr(args, name, None) is not None
for name in ("message", "message_file", "prompt", "prompt_file")
@@ -3097,7 +3168,14 @@ def cmd_task_update(args):
hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
help_command="vibe task update --help",
)
- if agent_name is None and session_policy != "existing":
+ if follows_session_agent and not explicit_agent_requested:
+ # Deliberately resolves NOTHING. Re-resolving here would write today's
+ # scope/default Agent back onto a definition whose Agent authority now
+ # belongs to its bound Session, and the pin wins over the Session row at
+ # dispatch -- so an unrelated ``--name`` edit would silently move every
+ # future fire onto a different Agent.
+ pass
+ elif agent_name is None and session_policy != "existing":
agent = _resolve_agent_for_target(
agent_name=None,
session_id=None,
@@ -3202,6 +3280,15 @@ def cmd_task_update(args):
task_payload = _task_payload(updated)
_print_definition_payload(task_payload, warnings=warnings)
return 0
+ except DefinitionWriteConflict as exc:
+ _print_task_error(
+ _definition_conflict_cli_error(
+ exc,
+ help_command="vibe task update --help",
+ details={"task_id": getattr(args, "task_id", exc.definition_id)},
+ )
+ )
+ return 1
except Exception as exc:
_print_task_error(exc, help_command="vibe task update --help")
return 1
@@ -8015,7 +8102,17 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):
)
)
return 1
- updated = store.set_enabled(watch_id, enabled)
+ try:
+ updated = store.set_enabled(watch_id, enabled)
+ except DefinitionWriteConflict as exc:
+ _print_task_error(
+ _definition_conflict_cli_error(
+ exc,
+ help_command="vibe watch list",
+ details={"watch_id": watch_id},
+ )
+ )
+ return 1
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
watch_payload = _watch_payload(updated, runtime_entry)
_print_definition_payload(watch_payload)
@@ -8143,12 +8240,41 @@ def cmd_watch_update(args):
message = prefix
else:
message = getattr(watch, "message", None) or watch.prefix
+ # Same three durable Agent-authority states ``vibe task update`` keeps, on the
+ # sibling definition command. Rejected rather than silently resolved, exactly
+ # as ``--name`` / ``--clear-name`` above: the two flags mean opposite things
+ # and the pair honours neither -- ``--clear-agent`` wins for ``agent_name``
+ # (-> None) while the mere PRESENCE of ``--agent`` POPS the
+ # follow-the-session marker, so the definition looks like "no Agent pinned and
+ # not following its Session" and the resolve below writes today's scope /
+ # default Agent back as a hard pin (HFR-255, HFR-256).
+ if getattr(args, "agent", None) is not None and getattr(args, "clear_agent", False):
+ raise TaskCliError(
+ "use either --agent or --clear-agent, not both",
+ code="conflicting_agent_update",
+ hint=(
+ "Pin an Agent with --agent, or hand Agent authority back to the bound "
+ "Session with --clear-agent."
+ ),
+ help_command="vibe watch update --help",
+ )
if getattr(args, "clear_agent", False):
agent_name = None
elif getattr(args, "agent", None) is not None:
agent_name = _validate_agent_name_arg(args.agent)
else:
agent_name = watch.agent_name
+
+ # "Follow the bound Session's Agent" is a durable state (set by
+ # ``--clear-agent``, or by a reset rebind on a ``create_once`` definition),
+ # not merely a missing ``agent_name``. An explicit ``--agent`` is the user
+ # pinning again, so it ends the state.
+ explicit_agent_requested = getattr(args, "agent", None) is not None
+ if explicit_agent_requested:
+ metadata.pop(BINDING_FOLLOWS_SESSION_METADATA_KEY, None)
+ elif getattr(args, "clear_agent", False):
+ metadata[BINDING_FOLLOWS_SESSION_METADATA_KEY] = True
+ follows_session_agent = bool(metadata.get(BINDING_FOLLOWS_SESSION_METADATA_KEY))
cwd = (
None
if getattr(args, "clear_cwd", False)
@@ -8211,7 +8337,14 @@ def cmd_watch_update(args):
hint="Pass --scope-id <scopes.id>, or run from an Avibe Agent Session and pass --same-scope.",
help_command="vibe watch update --help",
)
- if agent_name is None and session_policy != "existing":
+ if follows_session_agent and not explicit_agent_requested:
+ # Deliberately resolves NOTHING. Re-resolving here would write today's
+ # scope/default Agent back onto a definition whose Agent authority now
+ # belongs to its bound Session, and the pin wins over the Session row at
+ # dispatch -- so an unrelated ``--name`` edit would silently move every
+ # future watch hook onto a different Agent.
+ pass
+ elif agent_name is None and session_policy != "existing":
agent = _resolve_agent_for_target(
agent_name=None,
session_id=None,
@@ -8306,6 +8439,15 @@ def cmd_watch_update(args):
watch_payload = _watch_payload(updated, runtime_entry)
_print_definition_payload(watch_payload, warnings=warnings)
return 0
+ except DefinitionWriteConflict as exc:
+ _print_task_error(
+ _definition_conflict_cli_error(
+ exc,
+ help_command="vibe watch update --help",
+ details={"watch_id": getattr(args, "watch_id", exc.definition_id)},
+ )
+ )
+ return 1
except Exception as exc:
_print_task_error(exc, help_command="vibe watch update --help")
return 1
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index d71488b60..ea6ce479a 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -260,7 +260,7 @@
"mentionStatusOn": "Require @",
"mentionStatusOff": "Don't require @",
"requireMentionLarkNote": "Note: To receive non-mention messages in groups, the Feishu app needs the `im:message.group_msg` permission.",
- "language": "Language / \u8bed\u8a00",
+ "language": "Language / 语言",
"languageHint": "Changes the language for bot messages in Slack and the Web UI."
},
"cwd": {
@@ -337,12 +337,15 @@
"directMessage": "Direct Message"
},
"new": {
- "started": "Started a fresh session. Your next message will begin a new conversation."
+ "started": "Started a fresh session. Your next message will begin a new conversation.",
+ "pausedReason": "the bound agent session was cleared by /new",
+ "pausedTasks": "⏸️ Paused {count} scheduled task(s) pinned to the cleared session. Re-point with `vibe task list` → `vibe task update <id> --session-id <new>`, then `vibe task resume <id>`.",
+ "pausedWatches": "⏸️ Paused {count} watch(es) pinned to the cleared session. Re-point with `vibe watch list` → `vibe watch update <id> --session-id <new>`, then `vibe watch resume <id>`."
},
"clear": {
"noSessions": "No active sessions to clear.\nSession state has been reset.",
"cleared": "Cleared active sessions for:\n{details}\nAll sessions reset.",
- "sessionItem": "{agent} \u2192 {count} session(s)"
+ "sessionItem": "{agent} → {count} session(s)"
},
"cwd": {
"current": "Current Working Directory:",
@@ -480,7 +483,7 @@
"language": {
"systemDefault": "(System Default)",
"en": "English",
- "zh": "\u4e2d\u6587"
+ "zh": "中文"
},
"telegram": {
"commandMenu": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index a7e22312f..3fc63d51f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -337,7 +337,10 @@
"directMessage": "私信"
},
"new": {
- "started": "已开启新的会话。你下一条消息会从全新对话开始。"
+ "started": "已开启新的会话。你下一条消息会从全新对话开始。",
+ "pausedReason": "绑定的 Agent 会话已被 /new 清除",
+ "pausedTasks": "⏸️ 已暂停 {count} 个绑定到被清理会话的定时任务。用 `vibe task list` → `vibe task update <id> --session-id <new>` 重新指向,再 `vibe task resume <id>`。",
+ "pausedWatches": "⏸️ 已暂停 {count} 个绑定到被清理会话的 watch。用 `vibe watch list` → `vibe watch update <id> --session-id <new>` 重新指向,再 `vibe watch resume <id>`。"
},
"clear": {
"noSessions": "没有要清除的活动会话。\n会话状态已重置。",