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): collapse legacy restart notice fanout

cyh917a11df0bff
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index b8b10b921..aa701f48f 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -8762,10 +8762,77 @@ class ScheduledTaskService:
"""Settle late accepted Runs from their immutable Turn snapshot."""
if settled_by in SETTLEMENTS_WITHOUT_RESULT:
- self.settle_agent_runs_without_result(
- execution_ids,
- settled_by=str(settled_by),
+ normalized_settlement = str(settled_by)
+ store = self.request_store.sqlite_backend
+ if store is None:
+ self.settle_agent_runs_without_result(
+ execution_ids,
+ settled_by=normalized_settlement,
+ )
+ return
+ normalized_execution_ids = list(
+ dict.fromkeys(
+ execution_id
+ for value in execution_ids
+ if (execution_id := str(value or "").strip())
+ )
+ )
+ terminal_status = SETTLEMENT_TERMINAL_STATUS.get(
+ normalized_settlement,
+ "failed",
+ )
+ error_text = self._t(
+ SETTLEMENT_I18N_KEYS.get(
+ normalized_settlement,
+ SETTLEMENT_I18N_KEYS[SETTLED_BY_NO_TERMINAL_RESULT],
+ )
+ )
+ provenance: dict[str, Any] = {
+ "turn_id": turn_id,
+ "evidence_kind": evidence_kind,
+ "settled_by": normalized_settlement,
+ "interrupt_reason": normalized_settlement,
+ }
+ if terminal_status == "failed":
+ provenance["turn_failure_notification"] = {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ }
+ results = store.record_turn_run_outputs(
+ normalized_execution_ids,
+ output_id=f"resultless:{normalized_settlement}",
+ text="",
+ provenance=provenance,
+ terminal_status=terminal_status,
+ error=error_text,
+ )
+ repaired_ids = (
+ store.reconcile_resultless_turn_failure_notices(
+ normalized_execution_ids,
+ turn_id=turn_id,
+ settled_by=normalized_settlement,
+ )
+ if terminal_status == "failed"
+ else []
)
+ transitioned = False
+ for execution_id, result in results.items():
+ if not result.get("terminal_transition"):
+ continue
+ transitioned = True
+ run = result.get("run")
+ expected_status = str((run or {}).get("status") or terminal_status)
+ self._project_terminal_definition_result(
+ run,
+ execution_id=execution_id,
+ expected_status=expected_status,
+ )
+ if transitioned or repaired_ids:
+ self._wake_runtime_work(
+ RuntimeWorkLane.REQUESTS,
+ RuntimeWorkLane.RUN_CALLBACKS,
+ RuntimeWorkLane.FAILURE_NOTICES,
+ )
return
if evidence.get("settles_run") is not True:
return
diff --git a/core/session_turns.py b/core/session_turns.py
index 56f098167..b8ace4112 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -60,7 +60,7 @@ from storage import messages_service
from storage import message_deliveries as delivery_store
from storage.agent_session_rows import reserve_write_lock
from storage.db import get_cached_sqlite_engine
-from storage.background import normalize_run_status
+from storage.background import OWED_FAILURE_NOTICE_KEY, normalize_run_status
from storage.session_reclaim import reconcile_explicit_overrides
from storage.models import (
agent_runs,
@@ -3859,6 +3859,7 @@ class SessionTurnManager:
result: dict[str, Any]
materialized_id: str | None = None
terminal_run_ids: list[str] = []
+ terminal_turn_snapshot: dict[str, Any] | None = None
projected_status: str | None = None
status_changed = False
replayed_unknown_start = False
@@ -4275,6 +4276,7 @@ class SessionTurnManager:
turn_id,
)
)
+ terminal_turn_snapshot = delivery_store.get_turn(conn, turn_id)
projected_status = (
"running"
if claimed_successor
@@ -4295,7 +4297,20 @@ class SessionTurnManager:
if result.get("unknown_start_exhausted")
else settled_by
)
- self._settle_agent_run_ids(terminal_run_ids, run_settled_by)
+ if (
+ terminal_turn_snapshot is not None
+ and run_settled_by in SETTLEMENTS_WITHOUT_RESULT
+ ):
+ terminal_turn_snapshot = {
+ **terminal_turn_snapshot,
+ "settled_by": run_settled_by,
+ }
+ self._settle_agent_run_ids_from_terminal_turn(
+ terminal_run_ids,
+ terminal_turn_snapshot,
+ )
+ else:
+ self._settle_agent_run_ids(terminal_run_ids, run_settled_by)
if materialized_id:
self._publish_materialized_delivery(materialized_id)
if result.get("changed"):
@@ -6119,24 +6134,61 @@ class SessionTurnManager:
for _terminal_turn, run_ids in terminal_run_owners
for run_id in run_ids
}
- statuses = {
- str(row["id"]): normalize_run_status(row["status"])
+ run_rows = {
+ str(row["id"]): row
for row in conn.execute(
- select(agent_runs.c.id, agent_runs.c.status).where(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.metadata_json,
+ ).where(
agent_runs.c.id.in_(all_run_ids)
)
).mappings()
}
- unsettled_owners: list[tuple[dict[str, Any], list[str]]] = []
+ recoverable_owners: list[tuple[dict[str, Any], list[str]]] = []
for terminal_turn, run_ids in terminal_run_owners:
unsettled = [
run_id
for run_id in run_ids
- if statuses.get(run_id) in {"queued", "running"}
+ if run_id in run_rows
+ and normalize_run_status(run_rows[run_id]["status"])
+ in {"queued", "running"}
]
- if unsettled:
- unsettled_owners.append((terminal_turn, unsettled))
- for terminal_turn, run_ids in unsettled_owners:
+ settled_by = str(terminal_turn.get("settled_by") or "")
+ legacy_pending_notice = False
+ if settled_by in SETTLEMENTS_WITHOUT_RESULT:
+ for run_id in run_ids:
+ row = run_rows.get(run_id)
+ if row is None:
+ continue
+ try:
+ metadata = json.loads(str(row["metadata_json"] or "{}"))
+ except (TypeError, ValueError, json.JSONDecodeError):
+ continue
+ notice = (
+ metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(metadata, dict)
+ else None
+ )
+ if (
+ isinstance(notice, dict)
+ and notice.get("state") == "pending"
+ and not str(notice.get("turn_id") or "").strip()
+ and str(
+ notice.get("interrupt_reason")
+ or metadata.get("interrupt_reason")
+ or ""
+ ).strip()
+ == settled_by
+ ):
+ legacy_pending_notice = True
+ break
+ if unsettled or legacy_pending_notice:
+ # Older releases stamped one notice per Run even though the
+ # accepted Delivery relation retained this exact Turn owner.
+ recoverable_owners.append((terminal_turn, run_ids))
+ for terminal_turn, run_ids in recoverable_owners:
self._settle_agent_run_ids_from_terminal_turn(run_ids, terminal_turn)
with self._sqlite_engine().begin() as conn:
reserve_write_lock(conn)
diff --git a/docs/plans/harness-watch-run-failure-boundary.md b/docs/plans/harness-watch-run-failure-boundary.md
index bee0521a0..54d284182 100644
--- a/docs/plans/harness-watch-run-failure-boundary.md
+++ b/docs/plans/harness-watch-run-failure-boundary.md
@@ -191,6 +191,13 @@ does not claim that an event was detected.
- `HFR-473`: a definitively dead Codex transport can be replaced for the next
request even while stale Turn ownership from that dead generation remains;
unknown ownership and active Activities continue to fail closed.
+- `HFR-474`: result-less settlement carries the durable Turn failure contract
+ into every accepted Run. During an old-to-new upgrade, startup repairs legacy
+ per-Run restart notices from the exact accepted `Run -> Delivery -> Turn`
+ relation before activating the notice lane. It never groups by Session or
+ timestamp. If one legacy notice was already sent, that delivery evidence owns
+ the Turn and all pending siblings stand down; otherwise one stable participant
+ becomes the only fallback.
Residual manual check: trigger two one-shot Watches into one failing Turn and
confirm that the conversation contains one backend error, both Runs are failed,
diff --git a/storage/background.py b/storage/background.py
index 7c0ac1f27..f52288e8c 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -4881,6 +4881,7 @@ class SQLiteBackgroundTaskStore:
"turn_id",
"turn_failure_notification",
TURN_PARTICIPANT_RUN_IDS_METADATA_KEY,
+ "interrupt_reason",
)
if provenance and (value := provenance.get(key)) is not None
}
@@ -5128,6 +5129,7 @@ class SQLiteBackgroundTaskStore:
"turn_id",
"turn_failure_notification",
TURN_PARTICIPANT_RUN_IDS_METADATA_KEY,
+ "interrupt_reason",
)
if (value := terminal_provenance.get(key)) is not None
}
@@ -5163,6 +5165,184 @@ class SQLiteBackgroundTaskStore:
)
return results
+ def reconcile_resultless_turn_failure_notices(
+ self,
+ run_ids: Sequence[str],
+ *,
+ turn_id: str,
+ settled_by: str,
+ updated_at: Optional[str] = None,
+ ) -> list[str]:
+ """Attach one exact Turn owner to legacy per-Run interruption notices.
+
+ Releases before HFR-474 lost the notification contract from Run metadata,
+ but accepted Delivery ownership still retained the exact Turn. Startup calls
+ this before the notice lane activates. A sent notice is authoritative;
+ otherwise one pending participant is elected deterministically. Notice state,
+ attempts, errors, and retry timing remain unchanged.
+ """
+
+ from core import failure_notices
+
+ normalized_turn_id = str(turn_id or "").strip()
+ normalized_reason = str(settled_by or "").strip()
+ normalized_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for value in run_ids
+ if (run_id := str(value or "").strip())
+ )
+ )
+ if not normalized_turn_id or not normalized_reason or not normalized_run_ids:
+ return []
+
+ now = updated_at or _utc_now_iso()
+ changed_ids: list[str] = []
+ with run_update_event_transaction(self.engine) as conn:
+ reserve_write_lock(conn)
+ rows: dict[str, Any] = {}
+ for batch in _id_batches(normalized_run_ids):
+ rows.update(
+ {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(agent_runs).where(agent_runs.c.id.in_(batch))
+ ).mappings()
+ }
+ )
+ participant_ids = [
+ run_id for run_id in normalized_run_ids if run_id in rows
+ ]
+ notice_rows: dict[str, tuple[Any, dict[str, Any], dict[str, Any]]] = {}
+ for run_id in participant_ids:
+ row = rows[run_id]
+ if normalize_run_status(row["status"]) != "failed":
+ continue
+ metadata = _decoded_failure_notice_metadata(row["metadata_json"])
+ if metadata is None:
+ continue
+ notice = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if not isinstance(notice, dict) or notice.get("state") not in {
+ NOTICE_PENDING,
+ NOTICE_SENT,
+ }:
+ continue
+ notice_turn_id = failure_notices.notice_turn_id(notice)
+ if notice_turn_id and notice_turn_id != normalized_turn_id:
+ continue
+ reason = str(
+ notice.get("interrupt_reason")
+ or metadata.get("interrupt_reason")
+ or ""
+ ).strip()
+ if reason != normalized_reason:
+ continue
+ notice_rows[run_id] = (row, metadata, dict(notice))
+ if not notice_rows:
+ return []
+
+ ordered_ids = sorted(
+ notice_rows,
+ key=lambda run_id: (
+ str(notice_rows[run_id][0]["created_at"] or ""),
+ run_id,
+ ),
+ )
+ sent_ids = [
+ run_id
+ for run_id in ordered_ids
+ if notice_rows[run_id][2].get("state") == NOTICE_SENT
+ ]
+ pending_ids = [
+ run_id
+ for run_id in ordered_ids
+ if notice_rows[run_id][2].get("state") == NOTICE_PENDING
+ ]
+ existing_owner = ""
+ for run_id in ordered_ids:
+ _row, metadata, notice = notice_rows[run_id]
+ notification = metadata.get("turn_failure_notification")
+ notification = notification if isinstance(notification, dict) else {}
+ candidate = str(
+ notification.get("fallback_run_id")
+ or notice.get("turn_fallback_run_id")
+ or ""
+ ).strip()
+ if candidate in notice_rows:
+ existing_owner = candidate
+ break
+
+ if sent_ids:
+ owner_id = sent_ids[0]
+ elif existing_owner in pending_ids:
+ owner_id = existing_owner
+ else:
+ owner_id = next(
+ (
+ run_id
+ for run_id in pending_ids
+ if not _callback_parent_owns_failure_notice(
+ conn,
+ source_kind=notice_rows[run_id][0]["source_kind"],
+ parent_run_id=notice_rows[run_id][0]["parent_run_id"],
+ )
+ ),
+ pending_ids[0] if pending_ids else "",
+ )
+ if not owner_id:
+ return []
+
+ delivered = bool(sent_ids)
+ ack_evidence = None
+ if sent_ids:
+ evidence_values = [
+ str(notice_rows[run_id][2].get("ack_evidence") or "")
+ for run_id in sent_ids
+ ]
+ ack_evidence = max(
+ evidence_values,
+ key=lambda value: _ACK_EVIDENCE_PRIORITY.get(value, 0),
+ ) or None
+ failure_id = f"turn:{normalized_turn_id}"
+ notification: dict[str, Any] = {
+ "failure_id": failure_id,
+ "delivered": delivered,
+ "fallback_run_id": owner_id,
+ }
+ if ack_evidence:
+ notification["ack_evidence"] = ack_evidence
+
+ for run_id in ordered_ids:
+ _row, metadata, notice = notice_rows[run_id]
+ updated_metadata = dict(metadata)
+ updated_notice = dict(notice)
+ updated_metadata["turn_id"] = normalized_turn_id
+ updated_metadata["turn_failure_notification"] = dict(notification)
+ updated_notice.update(
+ {
+ "failure_id": failure_id,
+ "turn_id": normalized_turn_id,
+ "turn_notification_delivered": delivered,
+ "turn_notification_ack_evidence": ack_evidence,
+ "turn_fallback_run_id": owner_id,
+ TURN_PARTICIPANT_RUN_IDS_METADATA_KEY: participant_ids,
+ }
+ )
+ updated_metadata[OWED_FAILURE_NOTICE_KEY] = updated_notice
+ if updated_metadata == metadata:
+ continue
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(
+ metadata_json=_json_dumps(updated_metadata),
+ updated_at=now,
+ )
+ )
+ changed_ids.append(run_id)
+ _defer_run_ids_updated_from_connection(conn, changed_ids)
+ return changed_ids
+
def settle_run_terminal(
self,
run_id: str,
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 66e737ea9..1cd8f1214 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4255,6 +4255,16 @@ scenarios:
# A definitive process death makes the old local Turn fence non-authoritative;
# only unknown ownership or an active Activity can still veto replacement.
test: tests/test_codex_agent.py::CodexTransportCwdStalenessTests::test_hfr_473_dead_transport_restarts_past_stale_turn_ownership
+ - id: HFR-474
+ name: upgrade recovery collapses legacy restart notices by durable Turn ownership
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ # Before the notice lane starts, accepted Delivery ownership repairs legacy
+ # per-Run restart notices into one Turn fallback. A notice already sent remains
+ # authoritative and suppresses every pending sibling.
+ test: tests/test_session_delivery_fsm.py::test_hfr_474_startup_collapses_legacy_restart_notices_by_durable_turn
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 2637e7226..2053b781a 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -6841,6 +6841,55 @@ def test_hfr_439_turn_failure_metadata_reaches_every_linked_run(
assert notice["turn_fallback_run_id"] == expected_owner
+def test_hfr_474_resultless_turn_settlement_creates_one_restart_notice(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A current release never creates the legacy per-Run restart shape."""
+
+ from core import failure_notices
+ from core.run_settlement import SETTLED_BY_RESTARTED
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ requests = [
+ request_store.enqueue_agent_run(message=message, agent_name="codex")
+ for message in ("participant one", "participant two", "participant three")
+ ]
+ for request in requests:
+ assert request_store.claim(request.id) is not None
+
+ service = _callback_service(tmp_path=tmp_path, request_store=request_store)
+ service.settle_agent_runs_from_terminal_turn(
+ [request.id for request in requests],
+ turn_id="turn-resultless-restart",
+ outcome="failed",
+ settled_by=SETTLED_BY_RESTARTED,
+ evidence_kind="service_shutdown",
+ evidence={"reason": "scheduled_service_shutdown"},
+ )
+
+ expected_owner = min(request.id for request in requests)
+ deliverable = []
+ for request in requests:
+ row = request_store.get_run(request.id)
+ assert row is not None and row["status"] == "failed"
+ notice = request_store.sqlite_backend.owed_failure_notice(request.id)
+ assert notice is not None
+ assert notice["failure_id"] == "turn:turn-resultless-restart"
+ assert notice["turn_id"] == "turn-resultless-restart"
+ assert notice["turn_fallback_run_id"] == expected_owner
+ if failure_notices.decide(
+ run_id=request.id,
+ definition_id=None,
+ notice=notice,
+ streak_facts=None,
+ earlier_unsettled=None,
+ ).action == failure_notices.ACTION_DELIVER:
+ deliverable.append(request.id)
+ assert deliverable == [expected_owner]
+
+
def test_turn_fallback_owner_excludes_a_canceled_participant(
tmp_path: Path,
monkeypatch,
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 35cd6e630..28eb12ba2 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -6090,6 +6090,148 @@ def test_owned_run_sweep_retries_terminal_turn_settlement_before_orphaning(
).scalar_one() == "succeeded"
[email protected]("sent_before_recovery", [False, True])
+def test_hfr_474_startup_collapses_legacy_restart_notices_by_durable_turn(
+ managers,
+ tmp_path: Path,
+ sent_before_recovery: bool,
+) -> None:
+ """Upgrade recovery uses exact Delivery ownership before notices can drain."""
+
+ from core import failure_notices
+ from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
+ from storage.background import SQLiteBackgroundTaskStore
+
+ manager, _restarted, engine, _engine_b, _starts = managers
+ turn_id, _context_value = asyncio.run(_activate(manager))
+ run_ids = [f"run-legacy-restart-{index}" for index in range(3)]
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ initial = delivery_store.initial_deliveries_for_turn(conn, turn_id)[0]
+ assert initial["state"] == "accepted"
+ initial_row = delivery_store.get_delivery(conn, str(initial["id"]))
+ assert initial_row is not None
+ delivery_ids = [str(initial["id"])]
+ for index in range(1, len(run_ids)):
+ delivery_id = delivery_store.new_delivery_id()
+ values = dict(initial_row)
+ values.update(
+ id=delivery_id,
+ priority="p1",
+ dedupe_key=None,
+ turn_role="steer",
+ turn_position=index,
+ submitted_at=now,
+ updated_at=now,
+ version=1,
+ )
+ conn.execute(message_deliveries.insert().values(**values))
+ delivery_ids.append(delivery_id)
+ for run_id, delivery_id in zip(run_ids, delivery_ids, strict=True):
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ definition_id=None,
+ run_type="agent_run",
+ status="running",
+ cancel_requested=0,
+ session_id="ses_fsm",
+ callback_status="pending",
+ delivery_id=delivery_id,
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ db_path = Path(str(engine.url.database))
+ run_store = SQLiteBackgroundTaskStore(db_path)
+ request_store = TaskExecutionStore(root=tmp_path / "legacy-restart-requests")
+ request_store._sqlite = run_store
+ scheduled = ScheduledTaskService.__new__(ScheduledTaskService)
+ scheduled.controller = manager.controller
+ scheduled.request_store = request_store
+ scheduled._drain_dirty = False
+ manager.controller.scheduled_task_service = scheduled
+ try:
+ # Reproduce the old release: each failed Run independently receives a
+ # restart notice although all rows retain the same exact durable Turn.
+ for run_id in run_ids:
+ assert run_store.settle_run_terminal(
+ run_id,
+ terminal_status="failed",
+ error="service restarted",
+ metadata={"interrupt_reason": SETTLED_BY_RESTARTED},
+ updated_at=now,
+ ) == "failed"
+ sent_id = run_ids[0]
+ if sent_before_recovery:
+ run_store.update_owed_failure_notice(
+ sent_id,
+ state="sent",
+ ack_evidence="receipt",
+ )
+
+ # Match an upgrade: the old process wrote the terminal Turn and per-Run
+ # notices; the new process owns startup reconciliation.
+ with engine.begin() as conn:
+ terminal = manager._write_terminal_snapshot(
+ conn,
+ turn_id,
+ outcome="failed",
+ settled_by=SETTLED_BY_RESTARTED,
+ evidence_kind="service_shutdown",
+ evidence={"reason": "scheduled_service_shutdown"},
+ )
+ assert terminal["changed"] is True
+
+ asyncio.run(manager.recover_durable_delivery_state(service_restart=True))
+
+ notices = {
+ run_id: run_store.owed_failure_notice(run_id) for run_id in run_ids
+ }
+ assert all(notice is not None for notice in notices.values())
+ assert {
+ notice["turn_id"] for notice in notices.values() if notice is not None
+ } == {turn_id}
+ assert {
+ notice["turn_fallback_run_id"]
+ for notice in notices.values()
+ if notice is not None
+ } == {sent_id}
+ assert {
+ tuple(notice["turn_participant_run_ids"])
+ for notice in notices.values()
+ if notice is not None
+ } == {tuple(run_ids)}
+
+ deliverable = [
+ run_id
+ for run_id, notice in notices.items()
+ if notice is not None
+ and notice["state"] == "pending"
+ and failure_notices.decide(
+ run_id=run_id,
+ definition_id=None,
+ notice=notice,
+ streak_facts=None,
+ earlier_unsettled=None,
+ ).action
+ == failure_notices.ACTION_DELIVER
+ ]
+ assert deliverable == ([] if sent_before_recovery else [sent_id])
+ if sent_before_recovery:
+ assert notices[sent_id]["state"] == "sent"
+ assert all(
+ notice["turn_notification_delivered"] is True
+ for notice in notices.values()
+ if notice is not None
+ )
+ finally:
+ run_store.close()
+
+
def test_restored_opencode_generation_rebinds_turn_control_and_steer(
managers,
) -> None: