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): separate watch and run failures (#1223)

Call White64a5537a68da
diff --git a/core/backend_failure.py b/core/backend_failure.py
index 8c3aa9757..350545dc7 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -3,9 +3,15 @@
from __future__ import annotations
import uuid
+from dataclasses import replace
+from inspect import Parameter, signature
from typing import Any
-from core.delivery_evidence import DeliveryEvidence
+from core.delivery_evidence import (
+ ACK_EVIDENCE_DELIVERY_ONLY,
+ ACK_EVIDENCE_RECEIPT,
+ DeliveryEvidence,
+)
from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
from vibe.message_types import spec_for
@@ -32,13 +38,30 @@ def _terminal_output(request: Any, output: MessageOutput | None) -> MessageOutpu
def _harness_run_identity(context: Any, request: Any) -> str:
- """The run id a harness execution's failure notice is keyed by, if any."""
+ """The Run id proving that this Turn was entered through Harness, if any."""
for source in (getattr(request, "context", None), context):
payload = getattr(source, "platform_specific", None) or {}
identity = str(payload.get("task_execution_id") or "").strip()
if identity:
return identity
+ accepted = payload.get("accepted_agent_run_ids")
+ if isinstance(accepted, list):
+ for value in accepted:
+ identity = str(value or "").strip()
+ if identity:
+ return identity
+ return ""
+
+
+def _turn_failure_identity(context: Any, request: Any) -> str:
+ """Stable user-visible failure identity shared by every Run in one Turn."""
+
+ for source in (getattr(request, "context", None), context):
+ payload = getattr(source, "platform_specific", None) or {}
+ identity = str(payload.get("turn_token") or "").strip()
+ if identity:
+ return f"turn:{identity}"
return ""
@@ -57,19 +80,17 @@ def _failure_identity(
if identity and authoritative:
return identity
- # A harness execution is keyed by its RUN, whichever backend reported the
- # failure. Codex and OpenCode pass their own turn/message/session id at five
- # call sites, and preferring that over the run id meant the live notification
- # and the drain's replay had different identities — so the drain could not see
- # the message the live path had already persisted, and sent a duplicate. The
- # run id is the one identity BOTH paths can derive, the live one from its
- # context and the drain from the durable row.
+ # A Harness failure is user-visible once per TURN, whichever backend reported
+ # it and however many Runs that Turn accepted. Codex and OpenCode pass their
+ # own turn/message/session ids at five call sites, so the durable turn token is
+ # the shared identity both the live notification and every linked Run can carry.
+ # Legacy callers without a turn token still fall back to the Harness Run id.
#
# Non-harness contexts have no run to align to, so a backend's explicit id
# still wins there and that path is unchanged.
harness_identity = _harness_run_identity(context, request)
if harness_identity:
- return harness_identity
+ return _turn_failure_identity(context, request) or harness_identity
if identity:
return identity
@@ -226,58 +247,90 @@ async def emit_backend_failure(
failure_id: str | None = None,
delivery: DeliveryEvidence | None = None,
) -> bool:
- """Settle one terminal backend failure, notifying live only outside Harness.
+ """Notify and settle one terminal backend failure.
Backend adapters own structured failure recognition. This helper owns the
shared representation and keeps visible delivery separate from lifecycle
- settlement. Harness executions already own a durable owed-notice row whose drain
- applies streak suppression, callback coordination, claims, and retry policy. For
- those runs this emitter settles only; the drain is the single delivery owner.
- Non-Harness callers retain immediate auth recovery and notification. The return
- value is true when auth recovery supplied that immediate notification.
+ settlement. A live Agent Turn is the primary owner of its user-visible error,
+ including a Turn entered through Harness. Linked Runs retain durable owed notices
+ only as one Turn-scoped fallback when this notification cannot be acknowledged.
+ Non-Harness callers retain immediate auth recovery. The return value is true when
+ auth recovery supplied that immediate notification.
``delivery``, when supplied, is filled in with what the notify attempt actually
- proved. Nothing here can report that otherwise: this function DISCARDS the
- result of ``emit_agent_message`` and returns normally whether or not the notify
- was delivered, so a caller that owes a durable notice had no way to tell a
- delivered notice from a lost one and would ack on a send that never happened.
- Callers with nothing durable at stake pass nothing and are unaffected.
+ proved. Harness supplies an evidence object automatically because linked Runs
+ owe a durable fallback; other callers opt in when they need the same proof. A
+ clean return alone is not enough to distinguish a delivered message from a lost
+ one.
"""
backend_name = str(backend or "backend").strip() or "backend"
error, visible = _failure_texts(backend_name, diagnostic, display_text)
terminal = _terminal_output(request, output)
+ harness_run_id = _harness_run_identity(context, request)
+ notification = backend_failure_notification_output(
+ context,
+ backend_name,
+ request=request,
+ output=terminal,
+ failure_id=failure_id,
+ )
+ notification_identity = str(notification.metadata.get("failure_id") or "").strip()
+ live_delivery = delivery
+ if harness_run_id and live_delivery is None:
+ live_delivery = DeliveryEvidence()
+
+ platform_specific = getattr(context, "platform_specific", None) or {}
+ delivery_override = (
+ platform_specific.get("delivery_override")
+ if isinstance(platform_specific, dict)
+ else None
+ )
+ target_platform = str(
+ (
+ delivery_override.get("platform")
+ if isinstance(delivery_override, dict)
+ else None
+ )
+ or getattr(context, "platform", "")
+ or ""
+ ).strip()
+
+ def notification_acknowledged() -> bool:
+ if live_delivery is None:
+ return False
+ evidence = live_delivery.ack_evidence
+ if evidence == ACK_EVIDENCE_RECEIPT:
+ return True
+ return (
+ evidence == ACK_EVIDENCE_DELIVERY_ONLY
+ and target_platform != "avibe"
+ )
+
async def settle_terminal_failure() -> None:
+ terminal_output = terminal
+ if harness_run_id:
+ metadata = dict(terminal.metadata)
+ metadata["turn_failure_notification"] = {
+ "failure_id": notification_identity,
+ "ack_evidence": live_delivery.ack_evidence if live_delivery else None,
+ "delivered": notification_acknowledged(),
+ }
+ terminal_output = replace(terminal, metadata=metadata)
await controller.emit_agent_message(
context,
"result",
"",
is_error=True,
level="silent",
- output=terminal,
+ output=terminal_output,
terminal_error=error,
)
- # A Harness run is durable before the backend executes. Its terminal settlement
- # stamps the owed notice atomically, and that notice drain is the only layer with
- # enough definition history to suppress a recurring failure streak correctly.
- # Sending here as well creates two competing delivery owners and lets every live
- # failure bypass that policy before the drain can classify it.
- if _harness_run_identity(context, request):
- await settle_terminal_failure()
- return False
-
- notification = backend_failure_notification_output(
- context,
- backend_name,
- request=request,
- output=terminal,
- failure_id=failure_id,
- )
-
# Auth recovery is unconditional for non-Harness live callers, and there is no
# switch to turn it off. A real interactive 401 should offer its reset-OAuth
- # affordance immediately; a Harness failure is reported by the durable drain.
+ # affordance immediately; a Harness Turn uses the ordinary backend failure
+ # notification so the Run fallback remains backend-neutral.
#
# The one caller that must not do that — the owed-notice drain, replaying a
# possibly hours-old failure it read back from a durable row — does not call this
@@ -286,7 +339,7 @@ async def emit_backend_failure(
# live behaviours switched off one at a time.
auth_service = getattr(controller, "agent_auth_service", None)
maybe_recover = getattr(auth_service, "maybe_emit_auth_recovery_message", None)
- if callable(maybe_recover):
+ if not harness_run_id and callable(maybe_recover):
try:
handled_auth = await maybe_recover(
context,
@@ -301,20 +354,37 @@ async def emit_backend_failure(
if handled_auth:
return True
- # ``delivery`` is passed ONLY when a caller asked for it. Sending it
- # unconditionally changed the call signature for every controller-like object
- # that implements ``emit_agent_message`` without the new keyword, which is a
- # breaking change for an optional diagnostic — three suites caught it.
+ # ``delivery`` is passed only when the emitter supports it. Harness creates the
+ # object automatically, but controller-like test and integration doubles with
+ # the legacy signature must keep working.
notify_kwargs: dict[str, Any] = {"output": notification}
- if delivery is not None:
- notify_kwargs["delivery"] = delivery
+ if live_delivery is not None:
+ emit = controller.emit_agent_message
+ try:
+ parameters = signature(emit).parameters.values()
+ accepts_delivery = any(
+ parameter.name == "delivery" or parameter.kind is Parameter.VAR_KEYWORD
+ for parameter in parameters
+ )
+ except (TypeError, ValueError):
+ accepts_delivery = False
+ if accepts_delivery:
+ notify_kwargs["delivery"] = live_delivery
try:
- await controller.emit_agent_message(
+ delivered_id = await controller.emit_agent_message(
context,
"notify",
visible,
**notify_kwargs,
)
+ if (
+ live_delivery is not None
+ and live_delivery.delivered_id is None
+ and delivered_id is not None
+ and not bool((context.platform_specific or {}).get("suppress_delivery"))
+ ):
+ live_delivery.delivered_id = str(delivered_id)
+ live_delivery.send_returned = True
finally:
await settle_terminal_failure()
return False
diff --git a/core/failure_notices.py b/core/failure_notices.py
index 665b11bdb..d71fbfa00 100644
--- a/core/failure_notices.py
+++ b/core/failure_notices.py
@@ -5,7 +5,12 @@ transitions a run to ``failed`` — lives in ``storage/background.py``. This mod
owns the POLICY over it, kept separate from the delivery plumbing in
``core/scheduled_tasks.py`` so every branch is testable without a controller.
-Three lanes, and the asymmetries between them are the whole design:
+Four lanes, and the asymmetries between them are the whole design:
+
+* **Turn fallbacks** report one terminal Agent Turn, not every Harness Run that
+ Turn accepted. The live backend notification is primary; if its delivery cannot
+ be acknowledged, one elected Run owns the durable fallback and all other linked
+ Runs stand down.
* **Failures** of a definition can recur *unboundedly* — every tick produces
another one — so without a scope the user gets a message per tick forever. They
@@ -381,11 +386,28 @@ def is_binding_change(notice: Optional[dict[str, Any]]) -> bool:
return notice_kind(notice) == NOTICE_KIND_BINDING_CHANGE
+def notice_turn_id(notice: Optional[dict[str, Any]]) -> str:
+ """The terminal Turn that owns this failure's user-visible report."""
+
+ return str((notice or {}).get("turn_id") or "").strip()
+
+
+def turn_notification_delivered(notice: Optional[dict[str, Any]]) -> bool:
+ """Whether the Turn's primary backend failure notification was acknowledged."""
+
+ # Legacy Harness contexts predate ``turn_token`` and therefore stamp no Turn id,
+ # but the explicit delivery flag still comes from the live notification's
+ # DeliveryEvidence. Requiring the newer identity discards valid evidence and lets
+ # the durable fallback repeat a notification that was already delivered.
+ return bool((notice or {}).get("turn_notification_delivered"))
+
+
def bypasses_suppression(notice: Optional[dict[str, Any]]) -> bool:
"""Whether this notice is delivered per-run, outside the failure streak.
- Two lanes qualify, for the SAME reason and not by accident:
+ Three lanes qualify because each carries its own bound:
+ * a Turn fallback elects one Run across all definitions linked to that Turn;
* an interruption hits a run at most once, so per-run notices are self-bounding;
* a binding change is already scoped by ``SessionBindingChange.signature`` — one
broken binding, one notification — so it carries its own bound and does not
@@ -399,7 +421,26 @@ def bypasses_suppression(notice: Optional[dict[str, Any]]) -> bool:
never sent.
"""
- return is_interruption(notice) or is_binding_change(notice)
+ return (
+ is_interruption(notice)
+ or is_binding_change(notice)
+ or bool(notice_turn_id(notice))
+ )
+
+
+def turn_fallback_owner_eligible(run: Any) -> bool:
+ """Whether a Run can own the fallback for one failed terminal Turn."""
+
+ if not isinstance(run, dict) or bool(run.get("cancel_requested")):
+ return False
+ status = str(run.get("status") or "").strip().lower()
+ return status not in {
+ "canceled",
+ "cancelled",
+ "succeeded",
+ "completed",
+ "success",
+ }
def decide(
@@ -418,9 +459,11 @@ def decide(
no streak was read (the bypass lanes below return before it is consulted).
``earlier_unsettled`` is an earlier-created execution of the same definition that
has not settled. ``callback_status`` is the run's effective callback delivery
- state read FRESH at decision time (``run_callback_state``): a queued callback
- child remains pending, only a succeeded child is sent, and a terminally failed
- child releases the notice. ``None`` means the run has no callback.
+ state read FRESH at decision time: a queued callback child remains pending,
+ only a succeeded child is sent, and a terminally failed child releases the
+ notice. For a Turn fallback this is aggregated across every linked Run because
+ one callback carries the shared terminal result. ``None`` means no effective
+ callback exists in the applicable ownership scope.
Facts, not rows. This function used to receive the streak itself and rederive
"anyone sent?" and "who is canonical?" from it in Python, which is what made the
@@ -430,6 +473,12 @@ def decide(
included.
"""
+ # The backend's ordinary failure notification is the primary report for a
+ # terminal Turn. All Runs accepted by that Turn still owe durable notices, but
+ # those notices are fallbacks rather than independent reports.
+ if turn_notification_delivered(notice):
+ return NoticeDecision(ACTION_SKIP, "delivered_by_turn")
+
# A PENDING CALLBACK IS ALREADY A DELIVERY for the same transition (plan
# correction, 2026-07-29): a failed run carrying ``callback_session_id`` gets a
# user-visible result turn from ``_drain_callbacks``, so the notice lane firing
@@ -451,6 +500,13 @@ def decide(
if callback_status == "sent":
return NoticeDecision(ACTION_SKIP, "delivered_by_callback")
+ turn_id = notice_turn_id(notice)
+ if turn_id:
+ fallback_run_id = str((notice or {}).get("turn_fallback_run_id") or "").strip()
+ if fallback_run_id and fallback_run_id != run_id:
+ return NoticeDecision(ACTION_SKIP, f"turn_fallback_owned:{fallback_run_id}")
+ return NoticeDecision(ACTION_DELIVER, "turn_fallback")
+
if is_interruption(notice):
# Per-run, always, with no suppression scope and no deferral: the streak is
# irrelevant to a notice that can only happen once for this run, and
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 5909b5bfd..dc75014e2 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -22,6 +22,7 @@ from config.v2_config import DEFAULT_AGENT_PROGRESS_STYLE
from modules.im import MessageContext
from modules.im.formatters.base_formatter import to_status_label
from core.delivery_evidence import STAGE_PERSIST, STAGE_SEND, STAGE_STREAM, DeliveryEvidence
+from core import failure_notices
from core.message_context import resolve_turn_sink_key
from core.message_mirror import (
agent_message_exists,
@@ -1128,7 +1129,7 @@ class ConsolidatedMessageDispatcher:
self,
context: MessageContext,
text: str,
- message_id: str,
+ message_id: str | None,
*,
terminal_status: Optional[str] = None,
) -> None:
@@ -1167,8 +1168,69 @@ class ConsolidatedMessageDispatcher:
output_semantics: MessageOutput,
provenance: dict[str, Any],
) -> None:
- for run_id in run_ids:
- get_run = getattr(store, "get_run", None)
+ normalized_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for value in run_ids
+ if (run_id := str(value or "").strip())
+ )
+ )
+ output_id = str(output_semantics.idempotency_key or "").strip()
+ if not output_id and output_semantics.sequence is not None:
+ output_id = f"sequence:{output_semantics.sequence}"
+ if not output_id and terminal_status:
+ output_id = "terminal"
+ if not output_id:
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20]
+ output_id = f"content:{digest}"
+ record_turn_outputs = getattr(store, "record_turn_run_outputs", None)
+ if callable(record_turn_outputs):
+ deferred_run_ids = (
+ [
+ run_id
+ for run_id in normalized_run_ids
+ if terminal_status and self._run_has_blocking_activity(run_id)
+ ]
+ if terminal_status
+ else []
+ )
+ record_turn_outputs(
+ normalized_run_ids,
+ output_id=output_id,
+ text=text,
+ message_id=message_id,
+ sequence=output_semantics.sequence,
+ provenance=provenance,
+ terminal_status=terminal_status,
+ error=terminal_error,
+ deferred_run_ids=deferred_run_ids,
+ )
+ return
+ get_run = getattr(store, "get_run", None)
+ eligible_run_ids = (
+ [
+ run_id
+ for run_id in normalized_run_ids
+ if failure_notices.turn_fallback_owner_eligible(get_run(run_id))
+ ]
+ if callable(get_run)
+ else normalized_run_ids
+ )
+ terminal_provenance = dict(provenance)
+ notification = terminal_provenance.get("turn_failure_notification")
+ if isinstance(notification, dict) and eligible_run_ids:
+ notification = dict(notification)
+ current_owner = str(notification.get("fallback_run_id") or "").strip()
+ if not (
+ current_owner
+ and callable(get_run)
+ and failure_notices.turn_fallback_owner_eligible(
+ get_run(current_owner)
+ )
+ ):
+ notification["fallback_run_id"] = min(eligible_run_ids)
+ terminal_provenance["turn_failure_notification"] = notification
+ for run_id in normalized_run_ids:
if callable(get_run) and _run_is_cancelled(get_run(run_id)):
continue
run_terminal_status = terminal_status
@@ -1181,24 +1243,23 @@ class ConsolidatedMessageDispatcher:
}
if terminal_error is not None:
defer_kwargs["error"] = terminal_error
+ deferred_metadata = {
+ key: value
+ for key in ("turn_id", "turn_failure_notification")
+ if (value := terminal_provenance.get(key)) is not None
+ }
+ if deferred_metadata:
+ defer_kwargs["metadata"] = deferred_metadata
defer_terminal(run_id, **defer_kwargs)
run_terminal_status = None
record_output = getattr(store, "record_run_output", None)
if callable(record_output):
- output_id = str(output_semantics.idempotency_key or "").strip()
- if not output_id and output_semantics.sequence is not None:
- output_id = f"sequence:{output_semantics.sequence}"
- if not output_id and run_terminal_status:
- output_id = "terminal"
- if not output_id:
- digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20]
- output_id = f"content:{digest}"
record_kwargs = {
"output_id": output_id,
"text": text,
"message_id": message_id,
"sequence": output_semantics.sequence,
- "provenance": provenance,
+ "provenance": terminal_provenance,
"terminal_status": run_terminal_status,
}
if terminal_error is not None:
@@ -1222,6 +1283,78 @@ class ConsolidatedMessageDispatcher:
**record_kwargs,
)
+ def _terminal_agent_run_ids(
+ self,
+ context: MessageContext,
+ output_semantics: MessageOutput,
+ ) -> list[str]:
+ run_ids: list[str] = []
+ for value in output_semantics.run_ids:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+ explicit_run_id = str(output_semantics.run_id or "").strip()
+ if explicit_run_id and explicit_run_id not in run_ids:
+ run_ids.append(explicit_run_id)
+ explicit_run_ids = output_semantics.metadata.get("run_ids")
+ if isinstance(explicit_run_ids, list):
+ for value in explicit_run_ids:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+ if not run_ids:
+ run_ids = _owned_agent_run_ids(context.platform_specific or {})
+ for durable_run_id in self._durable_accepted_agent_run_ids(context):
+ if durable_run_id not in run_ids:
+ run_ids.append(durable_run_id)
+ return run_ids
+
+ def _output_with_turn_fallback_owner(
+ self,
+ context: MessageContext,
+ output_semantics: MessageOutput,
+ ) -> MessageOutput:
+ """Elect the fallback before writing the immutable terminal snapshot."""
+
+ notification = output_semantics.metadata.get("turn_failure_notification")
+ if not isinstance(notification, dict):
+ return output_semantics
+ run_ids = self._terminal_agent_run_ids(context, output_semantics)
+ if not run_ids:
+ return output_semantics
+ current_owner = str(notification.get("fallback_run_id") or "").strip()
+ store = None
+ try:
+ store = SQLiteBackgroundTaskStore()
+ eligible = [
+ run_id
+ for run_id in run_ids
+ if failure_notices.turn_fallback_owner_eligible(store.get_run(run_id))
+ ]
+ current_owner_eligible = bool(
+ current_owner
+ and failure_notices.turn_fallback_owner_eligible(
+ store.get_run(current_owner)
+ )
+ )
+ except Exception:
+ logger.warning(
+ "Failed to elect terminal Turn fallback owner",
+ exc_info=True,
+ )
+ return output_semantics
+ finally:
+ if store is not None:
+ store.close()
+ if not eligible:
+ return output_semantics
+ notification = dict(notification)
+ if not current_owner_eligible:
+ notification["fallback_run_id"] = min(eligible)
+ metadata = dict(output_semantics.metadata)
+ metadata["turn_failure_notification"] = notification
+ return replace(output_semantics, metadata=metadata)
+
def _run_has_blocking_activity(self, run_id: str) -> bool:
service = getattr(self.controller, "agent_service", None)
registry = getattr(service, "activities", None)
@@ -1376,28 +1509,9 @@ class ConsolidatedMessageDispatcher:
output_semantics: MessageOutput | None = None,
log_label: str = "agent run terminal result",
) -> None:
- payload = context.platform_specific or {}
semantics = output_semantics or MessageOutput(completes_turn=True)
require_confirmation = semantics.requires_delivery_for_run_settlement
- run_ids: list[str] = []
- for value in semantics.run_ids:
- run_id = str(value or "").strip()
- if run_id and run_id not in run_ids:
- run_ids.append(run_id)
- explicit_run_id = str(semantics.run_id or "").strip()
- if explicit_run_id and explicit_run_id not in run_ids:
- run_ids.append(explicit_run_id)
- explicit_run_ids = semantics.metadata.get("run_ids")
- if isinstance(explicit_run_ids, list):
- for value in explicit_run_ids:
- run_id = str(value or "").strip()
- if run_id and run_id not in run_ids:
- run_ids.append(run_id)
- if not run_ids:
- run_ids = _owned_agent_run_ids(payload)
- for durable_run_id in self._durable_accepted_agent_run_ids(context):
- if durable_run_id not in run_ids:
- run_ids.append(durable_run_id)
+ run_ids = self._terminal_agent_run_ids(context, semantics)
if not run_ids:
return
terminal_status = None
@@ -1883,6 +1997,11 @@ class ConsolidatedMessageDispatcher:
canonical_type = settings_manager._canonicalize_message_type(message_type or "")
settings_key = self._get_settings_key(context)
output_semantics = output_for_message(canonical_type, output)
+ if canonical_type == "result" and output_semantics.completes_turn:
+ output_semantics = self._output_with_turn_fallback_owner(
+ context,
+ output_semantics,
+ )
activity_batch_incomplete = bool(
output_semantics.requires_delivery_for_run_settlement
and output_semantics.metadata.get("activity_batch_complete") is False
@@ -2045,7 +2164,18 @@ class ConsolidatedMessageDispatcher:
# cross-platform history) — persist_agent_message attributes IM rows to
# this target's scope.
target_context = self._get_target_context(context)
+ suppresses_outward_delivery = bool(
+ (context.platform_specific or {}).get("suppress_delivery")
+ )
output_metadata = output_semantics.provenance(context) if output is not None else None
+ if suppresses_outward_delivery:
+ # A background transcript row is local history, not an outward receipt.
+ # Mark that fact durably: a later user-visible fallback keeps the stable
+ # native identity but must send before promoting the row to a receipt.
+ output_metadata = {
+ **(output_metadata or {}),
+ "delivery_suppressed": True,
+ }
native_output_id = output_semantics.native_message_id(target_context) if output is not None else None
# For a result, persist the SAME cleaned text the user receives:
@@ -2069,10 +2199,27 @@ class ConsolidatedMessageDispatcher:
)
)
for candidate in native_output_candidates:
- accepted_message = agent_message_exists(target_context, candidate)
- if accepted_message:
- native_output_id = candidate
- break
+ candidate_message = agent_message_exists(target_context, candidate)
+ if not candidate_message:
+ continue
+ candidate_metadata = (
+ candidate_message.get("metadata")
+ if isinstance(candidate_message, Mapping)
+ else None
+ )
+ if (
+ not suppresses_outward_delivery
+ and isinstance(candidate_metadata, Mapping)
+ and candidate_metadata.get("delivery_suppressed") is True
+ ):
+ logger.info(
+ "Replaying local-only agent output %s to its outward target",
+ candidate,
+ )
+ continue
+ accepted_message = candidate_message
+ native_output_id = candidate
+ break
if accepted_message:
logger.info("Skipping duplicate agent output %s", native_output_id)
accepted_output_semantics = self._output_with_accepted_provenance(
@@ -2092,7 +2239,7 @@ class ConsolidatedMessageDispatcher:
# re-send, report nothing, and then either walk on to another delivery
# rung (a duplicate by another route) or exhaust its backoff and
# dead-letter a notice the user already has.
- if delivery is not None:
+ if delivery is not None and not suppresses_outward_delivery:
delivery.send_returned = True
delivery.delivered_id = native_output_id
delivery.persisted_row = {
@@ -2180,7 +2327,7 @@ class ConsolidatedMessageDispatcher:
# and the persisted row is the inbox/transcript source of truth.
persists_without_delivery = target_context.platform == "avibe"
- if (context.platform_specific or {}).get("suppress_delivery"):
+ if suppresses_outward_delivery:
try:
recorded_text = self._fold_footer(persist_text, result_footer)
persisted_output = None
@@ -2218,7 +2365,7 @@ class ConsolidatedMessageDispatcher:
metadata=output_metadata,
native_message_id=native_output_id,
)
- message_id = (persisted_output or {}).get("id") or (
+ local_message_id = (persisted_output or {}).get("id") or (
f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"
)
terminal_status = None
@@ -2233,7 +2380,7 @@ class ConsolidatedMessageDispatcher:
self._record_suppressed_agent_run_terminal_result(
context,
recorded_text,
- message_id,
+ None,
is_error=is_error,
terminal_error=terminal_error,
output_semantics=output_semantics,
@@ -2242,7 +2389,7 @@ class ConsolidatedMessageDispatcher:
self._record_suppressed_run_message(
context,
recorded_text,
- message_id,
+ None,
terminal_status=terminal_status,
)
if mutates_turn_lifecycle:
@@ -2265,7 +2412,7 @@ class ConsolidatedMessageDispatcher:
"Suppressed Activity output local settlement is incomplete",
delivered=False,
)
- return message_id
+ return local_message_id
finally:
if mutates_turn_lifecycle:
await self._finish_processing_indicator_turn(context)
diff --git a/core/message_mirror.py b/core/message_mirror.py
index c45f80c61..3addb8b3b 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -419,6 +419,26 @@ def persist_agent_message(
parent_native_message_id=context.thread_id,
content=content,
)
+ if (
+ appended_row is None
+ and native_message_id
+ and not suppress_delivery
+ and canonical_type in {"result", "error", "notify"}
+ ):
+ # The unique row may be local-only history from an earlier
+ # suppress_delivery attempt. This call occurs after the visible
+ # result/notify send, so only now may that row become a receipt.
+ appended_row = messages_service.promote_suppressed_native_message(
+ conn,
+ platform=context.platform,
+ scope_id=scope_id,
+ session_id=row_session_id,
+ native_message_id=native_message_id,
+ message_type=message_type,
+ text=text,
+ content=content,
+ metadata=metadata,
+ )
# Recompute the session's inbox row so the realtime event can patch
# the browser without a refetch. avibe-only: the workbench inbox is
# scoped to avibe sessions (IM rows persist but aren't shown there).
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index e82f979b3..d7007c312 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -113,6 +113,9 @@ from storage.background import (
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
SweptRun,
+ WATCH_HOOK_OUTCOME_EVENT,
+ WATCH_HOOK_OUTCOME_METADATA_KEY,
+ WATCH_HOOK_OUTCOME_WAITER_FAILURE,
compute_next_run_at,
notice_write_expectation,
owed_notice_eligible,
@@ -928,13 +931,6 @@ def enqueue_session_callback(
session_id = (session_id or "").strip()
if not session_id or not (message or "").strip():
return None
- if parent_run_id:
- existing = request_store.find_callback_run(
- parent_run_id=parent_run_id,
- source_actor=source_actor,
- )
- if existing is not None:
- return TaskExecutionRequest.from_dict(existing)
target = resolve_session_id_target(session_id)
from core.message_priority import delivery_intent_for_trigger
@@ -953,6 +949,7 @@ def enqueue_session_callback(
parent_run_id=parent_run_id,
delivery_intent=delivery_intent_for_trigger("callback"),
metadata={"callback_parent_run_id": parent_run_id} if parent_run_id else {},
+ callback_parent_to_arm=parent_run_id,
)
@@ -2522,7 +2519,8 @@ class TaskExecutionStore:
delivery_intent: str = AGENT_RUN_DELIVERY_STEER,
metadata: Optional[dict[str, Any]] = None,
expected_enabled_agent_id: Optional[str] = None,
- ) -> TaskExecutionRequest:
+ callback_parent_to_arm: Optional[str] = None,
+ ) -> Optional[TaskExecutionRequest]:
if not (message or "").strip():
# Refuse at the door: a blank prompt never reaches an agent backend
# (``MessageHandler`` returns early), so the run could never be settled
@@ -2532,31 +2530,70 @@ class TaskExecutionStore:
normalized_delivery_intent = normalize_agent_run_delivery_intent(delivery_intent)
run_metadata = dict(metadata or {})
run_metadata[AGENT_RUN_DELIVERY_INTENT_METADATA_KEY] = normalized_delivery_intent
- return self.enqueue(
- TaskExecutionRequest(
- id=uuid4().hex[:12],
- request_type="agent_run",
- session_key=session_key,
- session_id=session_id,
- post_to=post_to,
- deliver_key=deliver_key,
- prompt=message,
- message=message,
- source_kind=source_kind,
- source_actor=source_actor,
- parent_run_id=parent_run_id,
- callback_session_id=callback_session_id,
- callback_status="pending" if callback_session_id and callback_active else None,
- agent_name=agent_name,
- agent_id=agent_id,
- agent_backend=agent_backend,
- model=model,
- reasoning_effort=reasoning_effort,
- session_policy=session_policy,
- metadata=run_metadata,
- ),
+ request = TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type="agent_run",
+ session_key=session_key,
+ session_id=session_id,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ prompt=message,
+ message=message,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
+ callback_session_id=callback_session_id,
+ callback_status="pending" if callback_session_id and callback_active else None,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ agent_backend=agent_backend,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ session_policy=session_policy,
+ metadata=run_metadata,
+ )
+ normalized_callback_parent = str(callback_parent_to_arm or "").strip()
+ if normalized_callback_parent and self._sqlite is not None:
+ callback_run_id = self._sqlite.enqueue_callback_run(
+ self.queued_run_payload(request),
+ parent_run_id=normalized_callback_parent,
+ source_actor=str(source_actor or ""),
+ )
+ if callback_run_id is None:
+ return None
+ stored = self._sqlite.get_run(callback_run_id)
+ return TaskExecutionRequest.from_dict(stored) if stored is not None else request
+ if normalized_callback_parent:
+ existing = self.find_callback_run(
+ parent_run_id=normalized_callback_parent,
+ source_actor=str(source_actor or ""),
+ )
+ if existing is not None:
+ self.update_callback_status(
+ normalized_callback_parent,
+ status="sent",
+ callback_run_id=str(existing["id"]),
+ )
+ return TaskExecutionRequest.from_dict(existing)
+ parent = self.get_run(normalized_callback_parent)
+ if parent is None:
+ raise ValueError(
+ f"callback parent Run not found: {normalized_callback_parent}"
+ )
+ parent_status = _normalize_requested_run_status(parent.get("status"))
+ if bool(parent.get("cancel_requested")) and parent_status != "canceled":
+ return None
+ queued = self.enqueue(
+ request,
expected_enabled_agent_id=expected_enabled_agent_id,
)
+ if normalized_callback_parent:
+ self.update_callback_status(
+ normalized_callback_parent,
+ status="sent",
+ callback_run_id=queued.id,
+ )
+ return queued
def list_pending(
self,
@@ -2821,6 +2858,7 @@ class TaskExecutionStore:
terminal_status: str,
error: Optional[str] = None,
result_text: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> bool:
if self._sqlite is None:
return False
@@ -2829,6 +2867,7 @@ class TaskExecutionStore:
terminal_status=terminal_status,
error=error,
result_text=result_text,
+ metadata=metadata,
)
def update_callback_status(
@@ -3647,7 +3686,10 @@ class _ScheduledRuntimeWorkHandler(RuntimeWorkHandler):
definition_id = str(
row.get("definition_id") or row.get("task_id") or ""
)
- if definition_id and not failure_notices.bypasses_suppression(notice):
+ turn_id = failure_notices.notice_turn_id(notice)
+ if turn_id:
+ partition = f"turn:{turn_id}"
+ elif definition_id and not failure_notices.bypasses_suppression(notice):
partition = f"definition:{definition_id}"
else:
partition = f"run:{run_id}"
@@ -5670,10 +5712,23 @@ class ScheduledTaskService:
# callback already landed, and a stale absence would deliver beside it. A
# read failure propagates to the drain loop's per-row handler and the row is
# retried later, which errs toward one message rather than two.
- callback_status = await self._run_runtime_sync(
- store.run_callback_state,
- run_id,
- )
+ turn_id = failure_notices.notice_turn_id(notice)
+ if turn_id and hasattr(store, "turn_callback_state"):
+ participant_run_ids = notice.get("turn_participant_run_ids")
+ callback_status = await self._run_runtime_sync(
+ store.turn_callback_state,
+ turn_id,
+ participant_run_ids=(
+ participant_run_ids
+ if isinstance(participant_run_ids, list)
+ else []
+ ),
+ )
+ else:
+ callback_status = await self._run_runtime_sync(
+ store.run_callback_state,
+ run_id,
+ )
decision = failure_notices.decide(
run_id=run_id,
definition_id=definition_id,
@@ -6637,6 +6692,16 @@ class ScheduledTaskService:
name=name,
reason=self._t(failure_notices.notice_reason_i18n_key(reason)),
)
+ elif is_watch and str(
+ ((run.get("metadata") or {}).get(WATCH_HOOK_OUTCOME_METADATA_KEY) or "")
+ ).strip() == WATCH_HOOK_OUTCOME_EVENT:
+ headline = self._t("harness.notice.watchProcessingFailed", name=name)
+ elif is_watch and str(
+ ((run.get("metadata") or {}).get(WATCH_HOOK_OUTCOME_METADATA_KEY) or "")
+ ).strip() == WATCH_HOOK_OUTCOME_WAITER_FAILURE:
+ headline = self._t("harness.notice.watchFailureReportFailed", name=name)
+ elif is_watch:
+ headline = self._t("harness.notice.watchFollowUpFailed", name=name)
else:
headline = self._t("harness.notice.failed", name=name)
# COMMAND COPY, ORDINARY-FAILED LANE ONLY. A command definition's notice named
@@ -6731,7 +6796,8 @@ class ScheduledTaskService:
# history genuinely cannot prove which of the two happened, and
# ``definition_lifecycle_expression`` makes the same call.
if str(watch.get("retired_at") or "").strip():
- lines.append(self._t("harness.notice.watchRetired"))
+ if failure_notices.is_interruption(notice):
+ lines.append(self._t("harness.notice.watchRetired"))
else:
lines.append(self._t("harness.notice.watchPaused", id=definition_id))
# No re-run affordance, because there is no ``vibe watch run``: a watch
@@ -8703,44 +8769,37 @@ class ScheduledTaskService:
None,
)
has_blocker = getattr(registry, "has_blocking_run_activity", None)
- settled_any = False
- for raw_execution_id in execution_ids:
- execution_id = str(raw_execution_id or "").strip()
- if not execution_id:
- continue
- run_terminal_status = terminal_status
- if callable(has_blocker) and has_blocker(execution_id):
- if not store.defer_run_terminal(
- execution_id,
- terminal_status=terminal_status,
- result_text=result_text,
- error=(
- str(terminal_error) if terminal_error is not None else None
- ),
- ):
- logger.warning(
- "failed to defer late terminal settlement for Run=%s Turn=%s",
- execution_id,
- turn_id,
- )
- run_terminal_status = None
- result = store.record_run_output(
- execution_id,
- output_id=output_id,
- text=result_text,
- message_id=message_id,
- provenance={
- **output_provenance,
- "turn_id": turn_id,
- "evidence_kind": evidence_kind,
- "settled_by": settled_by,
- },
- terminal_status=run_terminal_status,
- error=str(terminal_error) if terminal_error is not None else None,
- )
- settled_any = settled_any or bool(
- result.get("terminal_transition") or result.get("text_backfilled")
+ normalized_execution_ids = list(
+ dict.fromkeys(
+ execution_id
+ for value in execution_ids
+ if (execution_id := str(value or "").strip())
)
+ )
+ deferred_run_ids = [
+ execution_id
+ for execution_id in normalized_execution_ids
+ if callable(has_blocker) and has_blocker(execution_id)
+ ]
+ results = store.record_turn_run_outputs(
+ normalized_execution_ids,
+ output_id=output_id,
+ text=result_text,
+ message_id=message_id,
+ provenance={
+ **output_provenance,
+ "turn_id": turn_id,
+ "evidence_kind": evidence_kind,
+ "settled_by": settled_by,
+ },
+ terminal_status=terminal_status,
+ error=str(terminal_error) if terminal_error is not None else None,
+ deferred_run_ids=deferred_run_ids,
+ )
+ settled_any = any(
+ result.get("terminal_transition") or result.get("text_backfilled")
+ for result in results.values()
+ )
if settled_any:
self._wake_runtime_work(
RuntimeWorkLane.REQUESTS,
diff --git a/core/session_turns.py b/core/session_turns.py
index 3690bf4af..e58726d93 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -612,7 +612,15 @@ class SessionTurnManager:
run_ids: set[str] | list[str],
turn: dict[str, Any],
) -> None:
- normalized = sorted({str(run_id) for run_id in run_ids if str(run_id).strip()})
+ turn_id = str(turn.get("id") or "").strip()
+ durable_ids = self.accepted_agent_run_ids_for_turn(turn_id) if turn_id else []
+ normalized = sorted(
+ {
+ str(run_id)
+ for run_id in [*run_ids, *durable_ids]
+ if str(run_id).strip()
+ }
+ )
if not normalized:
return
service = (
diff --git a/core/watches.py b/core/watches.py
index 25079e7c5..b2b4b0bd1 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -40,6 +40,9 @@ from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStore
from storage.background import (
DEFINITION_CYCLE_COLUMNS,
NO_EVENT_EXIT_CODE,
+ WATCH_HOOK_OUTCOME_EVENT,
+ WATCH_HOOK_OUTCOME_METADATA_KEY,
+ WATCH_HOOK_OUTCOME_WAITER_FAILURE,
DefinitionWriteConflict,
DefinitionWriteExpectation,
SQLiteBackgroundTaskStore,
@@ -1987,6 +1990,7 @@ class ManagedWatchService:
self,
watch: ManagedWatch,
*,
+ event_detected: bool = False,
prompt: Optional[str] = None,
prefix: Optional[str] = None,
body: Optional[str] = None,
@@ -2011,7 +2015,14 @@ class ManagedWatchService:
run_type="watch",
definition_id=watch.id,
source_kind="watch",
- metadata=watch.metadata,
+ metadata={
+ **watch.metadata,
+ WATCH_HOOK_OUTCOME_METADATA_KEY: (
+ WATCH_HOOK_OUTCOME_EVENT
+ if event_detected
+ else WATCH_HOOK_OUTCOME_WAITER_FAILURE
+ ),
+ },
)
def _commit_cycle_result(
@@ -2055,7 +2066,13 @@ class ManagedWatchService:
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)
+ request = self._hook_request(
+ watch,
+ event_detected=event_detected,
+ 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(
diff --git a/docs/plans/harness-watch-run-failure-boundary.md b/docs/plans/harness-watch-run-failure-boundary.md
new file mode 100644
index 000000000..ef0105ad3
--- /dev/null
+++ b/docs/plans/harness-watch-run-failure-boundary.md
@@ -0,0 +1,181 @@
+# Harness Watch and Run Failure Boundary
+
+## Background
+
+A Watch waiter and the Agent Run created from a detected event answer different
+questions:
+
+- the waiter reports whether observation succeeded;
+- the Agent Run reports whether Avibe processed the observed event successfully.
+
+The Run must retain the Watch id as provenance, but provenance does not imply a
+shared lifecycle. A successful one-shot waiter may retire normally while its
+downstream Agent Turn fails.
+
+One Agent Turn can also accept Runs from several Watch or Task definitions. A
+single backend failure currently settles each linked Run and lets every Run own
+an independent failure notice. That converts one user-visible failure into
+several misleading Harness failures.
+
+## Contract
+
+### Notification ownership
+
+The terminal Agent Turn owns the user-visible execution failure. The backend's
+ordinary failure notification is the primary notification and is emitted once
+per Turn, including Turns entered through Harness Runs.
+
+Every linked Run still settles independently for audit and retry policy. Its
+owed failure notice is a fallback only:
+
+1. a persisted or externally delivered Turn notification suppresses all linked
+ Run notices;
+2. if the Turn notification was not acknowledged, exactly one linked Run that
+ has actually settled failed and owes a notice may deliver the fallback;
+3. the remaining linked Runs record that the same Turn was already reported;
+4. if an owned Activity delays Run settlement, the Turn notification evidence
+ is committed with the deferred terminal intent and survives until settlement.
+
+Fallback election and every linked Run output write share one SQLite write
+transaction. The transaction reserves the writer before reading participants,
+so a concurrent cancellation either precedes the election and is excluded or
+follows the complete settlement. A Run whose Activity defers settlement cannot
+own notices that non-deferred siblings owe immediately. If every participant is
+deferred, the first Run that actually settles failed elects itself and propagates
+that stable owner to the remaining deferred participants in the same locked
+transaction. Every election phase uses the same metadata-writability predicate
+as notice persistence, so a malformed legacy row cannot be named as an owner
+that is unable to record the notice.
+
+Persistence caused only by `suppress_delivery` is local history, not delivery
+evidence. It is tagged as suppressed, rejected by outward receipt lookup, and
+promoted under its stable native identity only after a later user-visible send
+succeeds. Promotion rebinds the row to that visible target Session. Its local
+Message row is also stamped with the visible delivery time, so transcript order
+reflects when the user could first see it rather than its earlier hidden creation.
+The row id is not written into the Run's transport receipts. It leaves the Turn
+notification unacknowledged so the durable fallback can route the failure to a
+user-visible target.
+
+A callback delivers the terminal result for its whole Turn. One effective callback
+receipt suppresses every linked Run fallback, while one pending callback defers the
+Turn fallback until its delivery outcome is known. The aggregate is read from one
+SQLite snapshot and includes participants whose Turn attribution is still held in
+a deferred terminal intent. Membership comes from the notice's bounded participant
+snapshot plus the indexed Delivery-to-Turn ownership relation, not a Run-history
+scan. Canceled and cancel-requested parents are excluded only before a callback is
+armed; an accepted callback child remains delivery evidence after parent cancellation.
+
+Terminal output replay is idempotent for status and content but monotonic for
+delivery evidence. A later same-Turn notification acknowledgement upgrades the
+existing owed notice without resetting its attempts, state, or fallback owner, so
+the durable drain cannot repeat a primary notification that succeeded on retry.
+The acknowledgement policy follows the routed target platform, not the originating
+Session platform, when a delivery override redirects the notification.
+
+Fallback ownership uses the complete notice-writability predicate: malformed
+metadata, an owned escalation, and a callback child whose parent already owns the
+notice are all ineligible. Eligibility is projected in terminal-write order before
+the stable owner tie-breaker, so a parent that acquires its notice in the same batch
+removes the callback child that notice suppresses. Callback child insertion and the
+parent's armed marker commit in one SQLite transaction. The transaction rejects a
+new failure callback after a settled parent is cancel-requested, but still repairs
+the armed marker for a child accepted before cancellation. A Run whose terminal
+outcome is `canceled` still reports that outcome to its delegator because it never
+owns a failure fallback.
+
+Waiter health is observed only from completed outcome fields. Starting the first
+cycle does not prove success, so a Watch with no prior exit, finish, or error remains
+unknown while that waiter is in flight.
+
+Turn execution provenance alone does not enter this ownership lane. A terminal
+output must carry the explicit `turn_failure_notification` contract; direct error
+results without it remain under the existing definition-level notice policy.
+
+The Turn id is the failure identity. Definition ids remain provenance and do
+not create additional user-visible failures.
+
+### Health ownership
+
+For Watch definitions, `health` describes only the waiter. Downstream Agent Run
+history is exposed separately as `processing_health` with independent counters.
+Scheduled Tasks continue to use their existing execution health projection.
+An unobserved waiter remains `unknown`; absent downstream history is `healthy`.
+An `unknown` downstream verdict means the health projection itself could not be
+read and remains visible without a count instead of being presented as healthy.
+
+This is an additive projection change and requires no schema migration. Existing
+Run-to-definition and Run-to-Turn links remain intact.
+
+### User-facing copy
+
+A successful Watch followed by a failed Agent Run is described as event
+processing failure. It is not described as a Watch failure, and normal one-shot
+retirement is not presented as a consequence of the Agent failure.
+If the waiter itself failed, the fallback says that failure reporting failed and
+does not claim that an event was detected.
+
+## Acceptance
+
+- `HFR-436`: Watch health remains healthy after a successful waiter while its
+ event processing health becomes failing. Retry exit codes are healthy only
+ while a `forever` Watch remains enabled and can actually retry; the same retry
+ outcome remains failing when a lifetime, binding, or operator stop makes it
+ terminal. An unreadable processing verdict remains visible as `unknown` in
+ both the Watch list and its detail pane.
+- `HFR-437`: one acknowledged Turn failure suppresses every linked Run notice.
+- `HFR-438`: a missing Turn notification produces exactly one fallback across
+ all linked Runs. Canceled Runs are excluded from ownership, and Runs accepted
+ after terminal settlement reuse the owner elected from all durable Turn
+ participants. Election and participant writes use one locked snapshot. A
+ deferred participant becomes eligible only when it actually settles failed,
+ so cancellation cannot invalidate an owner that sibling notices depend on.
+- `HFR-439`: terminal Turn notification evidence reaches every linked Run in
+ the same failed transition, or in the deferred terminal intent when an
+ Activity still owns the Run. The immutable terminal Turn snapshot supplies
+ the initial election; the locked participant settlement validates it against
+ current cancellation and deferral state before writing every Run. Legacy
+ Harness contexts without a Turn token still honor explicit delivery evidence.
+- `HFR-440`: one effective callback receipt on any linked Run suppresses the
+ complete Turn fallback; pending callback delivery defers it.
+- `HFR-441`: persistence under `suppress_delivery` cannot satisfy or shadow a
+ later outward receipt, including in a foreground callback target Session.
+- `HFR-442`: bare Turn provenance without a notification contract does not
+ bypass definition-level failure-notice suppression.
+- `HFR-443`: a deferred participant's pending callback remains part of the Turn
+ callback aggregate and blocks an immediate sibling fallback.
+- `HFR-444`: a Watch in its first in-flight waiter cycle reports unknown waiter
+ health until an outcome exists.
+- `HFR-445`: promoting suppressed history rebinds the stable row to the visible
+ target Session after delivery.
+- `HFR-446`: promotion stamps the visible delivery time so hidden history cannot
+ appear before newer target-Session content.
+- `HFR-447`: fallback ownership requires metadata that can persist the notice in
+ both immediate and deferred settlement.
+- `HFR-448`: a cancel-requested deferred callback participant no longer blocks
+ the remaining Turn fallback.
+- `HFR-449`: cancellation preserves pending and delivered callback evidence once
+ the callback child has been accepted.
+- `HFR-450`: a same-Turn terminal replay merges newer delivery evidence without
+ resetting notice progress.
+- `HFR-451`: Turn callback aggregation uses bounded participant ownership and
+ indexed Delivery membership instead of scanning Run JSON.
+- `HFR-452`: callback children suppressed by their parent's notice cannot become
+ the Turn fallback owner.
+- `HFR-453`: callback child enqueue and parent arming commit atomically.
+- `HFR-454`: transport-only acknowledgement follows the routed target platform.
+- `HFR-455`: Turn fallback election excludes callback children suppressed by a
+ parent notice created in the same batch.
+- `HFR-456`: late-canceled failed parents reject new callbacks while preserving
+ accepted children.
+- `HFR-457`: stale Turn participant ids are excluded before ownership projection
+ and cannot roll back settlement for valid Runs.
+- `HFR-458`: a callback accepted into an active Turn can prove its persisted
+ receipt through the shared Turn output even when another Run owns the Message.
+- `HFR-459`: independent Activity completions reserve the SQLite writer before
+ reading deferred participants and electing their shared Turn fallback owner.
+
+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,
+both Watches retire normally, and the UI separates waiter health from event
+processing health.
diff --git a/storage/background.py b/storage/background.py
index 798dfc38d..ffb090e42 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -43,7 +43,15 @@ from storage.migrations import (
guard_source_checkout_default_state_migration,
initialize_background_tables,
)
-from storage.models import agents, agent_runs, agent_sessions, messages, run_definitions, scopes
+from storage.models import (
+ agents,
+ agent_runs,
+ agent_sessions,
+ message_deliveries,
+ messages,
+ run_definitions,
+ scopes,
+)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.sqlite_semantics import sqlite_cast_integer
from storage.session_reclaim import (
@@ -881,6 +889,8 @@ _TERMINAL_STATUS_PRIORITY = {
# The closed set of terminal run statuses. Shared so guarded writers and reconcile
# paths cannot drift apart (this file previously spelled the set inline).
TERMINAL_RUN_STATUSES = frozenset(_TERMINAL_STATUS_PRIORITY)
+DEFERRED_TERMINAL_METADATA_KEY = "deferred_terminal_metadata"
+TURN_PARTICIPANT_RUN_IDS_METADATA_KEY = "turn_participant_run_ids"
def _parse_iso_instant(value: Any) -> Optional[datetime]:
@@ -1462,6 +1472,14 @@ HEALTH_HEALTHY = "healthy"
#: health signal that cannot be computed must not read as a clean bill.
HEALTH_UNKNOWN = "unknown"
+#: Durable provenance for the Agent Run queued by one Watch cycle. The Watch
+#: definition owns waiter state while this value says which kind of follow-up the
+#: Run is processing, so a failed reporting Turn cannot rewrite a waiter failure as
+#: a detected event.
+WATCH_HOOK_OUTCOME_METADATA_KEY = "watch_hook_outcome"
+WATCH_HOOK_OUTCOME_EVENT = "event"
+WATCH_HOOK_OUTCOME_WAITER_FAILURE = "waiter_failure"
+
#: The health window: the last N verdicts OR the last T hours, whichever is
#: shorter. Both bounds live in the ``WHERE``/``LIMIT`` of one query rather than
#: one of them in prose — bounded only by count, a definition that failed once and
@@ -1522,6 +1540,40 @@ def _owed_failure_notice_for_transition(
# The escalation turn IS the user-visible report for this failure.
return None
reason = str(metadata.get("interrupt_reason") or "").strip() or None
+ turn_notification = metadata.get("turn_failure_notification")
+ turn_notification = (
+ dict(turn_notification) if isinstance(turn_notification, dict) else {}
+ )
+ turn_failure_id = str(turn_notification.get("failure_id") or "").strip()
+ has_turn_notification = bool(turn_failure_id)
+ # ``turn_id`` is broad execution provenance. It becomes notification ownership
+ # only when the terminal output also carries the explicit Turn-failure contract.
+ # A direct error result (for example the disabled OpenCode question tool) has a
+ # Turn id but no separate notification; admitting it here would stamp every linked
+ # Run as an ownerless Turn fallback and bypass ordinary definition suppression.
+ turn_id = (
+ str(metadata.get("turn_id") or "").strip() or None
+ if has_turn_notification
+ else None
+ )
+ fallback_run_id = (
+ str(turn_notification.get("fallback_run_id") or "").strip()
+ if has_turn_notification
+ else ""
+ )
+ participant_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for value in (
+ metadata.get(TURN_PARTICIPANT_RUN_IDS_METADATA_KEY)
+ if isinstance(
+ metadata.get(TURN_PARTICIPANT_RUN_IDS_METADATA_KEY), list
+ )
+ else []
+ )
+ if (run_id := str(value or "").strip())
+ )
+ )
return {
"state": NOTICE_PENDING,
"attempts": 0,
@@ -1565,8 +1617,16 @@ def _owed_failure_notice_for_transition(
"failure_id": (
f"interrupt:{run_id}:{reason}"
if reason in RUN_INTERRUPTION_REASONS
- else run_id
+ else (turn_failure_id or run_id)
),
+ # A Turn is the user-visible failure owner. Every accepted Run keeps its
+ # own terminal audit row, while this shared identity and elected fallback
+ # owner prevent those rows from becoming duplicate messages.
+ "turn_id": turn_id,
+ "turn_notification_delivered": bool(turn_notification.get("delivered")),
+ "turn_notification_ack_evidence": turn_notification.get("ack_evidence"),
+ "turn_fallback_run_id": fallback_run_id or None,
+ TURN_PARTICIPANT_RUN_IDS_METADATA_KEY: participant_run_ids if turn_id else [],
# Optional, and only ever a copy selector. The lane a notice belongs to is
# decided from this value's membership in ``RUN_INTERRUPTION_REASONS``, not
# from its presence.
@@ -1696,6 +1756,45 @@ def _callback_parent_owns_failure_notice(
return isinstance(notice, dict) and bool(str(notice.get("state") or "").strip())
+def _decoded_failure_notice_metadata(raw: Any) -> Optional[dict[str, Any]]:
+ """Return the writable metadata object used by every notice owner decision."""
+
+ if isinstance(raw, (bytes, bytearray)):
+ raw = bytes(raw).decode("utf-8", "replace")
+ if raw is None or (isinstance(raw, str) and not raw.strip()):
+ return {}
+ decoded = _json_loads(raw if isinstance(raw, str) else None, None)
+ return decoded if isinstance(decoded, dict) else None
+
+
+def _run_can_own_failure_notice(
+ conn: Any,
+ row: Any,
+ *,
+ turn_id: str,
+ will_settle_failed: bool,
+) -> bool:
+ """Whether this transaction leaves the Run owning this Turn's notice."""
+
+ metadata = _decoded_failure_notice_metadata(row["metadata_json"])
+ if metadata is None:
+ return False
+ existing = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(existing, dict) and str(existing.get("state") or "").strip():
+ return bool(turn_id) and (
+ str(existing.get("turn_id") or "").strip() == turn_id
+ )
+ if not will_settle_failed:
+ return False
+ if str(metadata.get("escalation_run_id") or "").strip():
+ return False
+ return not _callback_parent_owns_failure_notice(
+ conn,
+ source_kind=row["source_kind"],
+ parent_run_id=row["parent_run_id"],
+ )
+
+
def _merge_owed_failure_notice(
values: dict[str, Any],
*,
@@ -1737,22 +1836,14 @@ def _merge_owed_failure_notice(
unreachable — and it is the direction every other reader on this path chose.
"""
- if isinstance(row_metadata_json, (bytes, bytearray)):
- row_metadata_json = bytes(row_metadata_json).decode("utf-8", "replace")
- if row_metadata_json is None or (
- isinstance(row_metadata_json, str) and not row_metadata_json.strip()
- ):
- merged: dict[str, Any] = {}
- else:
- decoded = _json_loads(row_metadata_json if isinstance(row_metadata_json, str) else None, None)
- if not isinstance(decoded, dict):
- logger.warning(
- "run %s has unreadable metadata_json; settling it without touching the "
- "column, so it records no owed failure notice",
- run_id,
- )
- return
- merged = decoded
+ merged = _decoded_failure_notice_metadata(row_metadata_json)
+ if merged is None:
+ logger.warning(
+ "run %s has unreadable metadata_json; settling it without touching the "
+ "column, so it records no owed failure notice",
+ run_id,
+ )
+ return
if extra_metadata:
merged.update(extra_metadata)
notice = None
@@ -1767,6 +1858,10 @@ def _merge_owed_failure_notice(
metadata=merged,
now=now,
)
+ # Participant membership belongs to the notice snapshot, not as a second
+ # top-level metadata contract. Deferred settlement reads its local copy before
+ # reaching this writer.
+ merged.pop(TURN_PARTICIPANT_RUN_IDS_METADATA_KEY, None)
if notice is None and not extra_metadata:
return
if notice is not None:
@@ -1774,6 +1869,90 @@ def _merge_owed_failure_notice(
values["metadata_json"] = _json_dumps(merged)
+_ACK_EVIDENCE_PRIORITY = {"": 0, "delivery_only": 1, "receipt": 2}
+
+
+def _merge_replayed_turn_delivery_evidence(
+ conn: Any,
+ *,
+ run_id: str,
+ row: Any,
+ incoming_status: Any,
+ provenance: Optional[dict[str, Any]],
+ now: str,
+) -> bool:
+ """Promote same-Turn delivery evidence without resetting a terminal notice."""
+
+ notification = (
+ provenance.get("turn_failure_notification")
+ if isinstance(provenance, dict)
+ else None
+ )
+ turn_id = str((provenance or {}).get("turn_id") or "").strip()
+ if (
+ not turn_id
+ or not isinstance(notification, dict)
+ or not bool(notification.get("delivered"))
+ ):
+ return False
+ normalized_incoming_status = normalize_run_status(incoming_status)
+ current = row
+ for final_attempt in (False, True):
+ if normalize_run_status(current["status"]) != normalized_incoming_status:
+ return False
+ raw_metadata = current["metadata_json"]
+ metadata = _decoded_failure_notice_metadata(raw_metadata)
+ if metadata is None:
+ return False
+ notice = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if not isinstance(notice, dict) or str(notice.get("turn_id") or "").strip() != turn_id:
+ return False
+ incoming_ack = str(notification.get("ack_evidence") or "").strip()
+ current_ack = str(notice.get("turn_notification_ack_evidence") or "").strip()
+ merged_ack = current_ack
+ if _ACK_EVIDENCE_PRIORITY.get(incoming_ack, 1 if incoming_ack else 0) > (
+ _ACK_EVIDENCE_PRIORITY.get(current_ack, 1 if current_ack else 0)
+ ):
+ merged_ack = incoming_ack
+ if bool(notice.get("turn_notification_delivered")) and merged_ack == current_ack:
+ return False
+ merged_notice = dict(notice)
+ merged_notice["turn_notification_delivered"] = True
+ if merged_ack:
+ merged_notice["turn_notification_ack_evidence"] = merged_ack
+ metadata[OWED_FAILURE_NOTICE_KEY] = merged_notice
+ updated = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(agent_runs.c.metadata_json == raw_metadata)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values(normalized_incoming_status)
+ )
+ )
+ .values(metadata_json=_json_dumps(metadata), updated_at=now)
+ )
+ if updated.rowcount:
+ return True
+ if final_attempt:
+ return False
+ current = (
+ conn.execute(
+ select(
+ agent_runs.c.status,
+ agent_runs.c.metadata_json,
+ )
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if current is None:
+ return False
+ return False
+
+
def normalize_run_status(status: Any) -> str:
return RUN_STATUS_ALIASES.get(str(status or "").strip(), str(status or "").strip() or "queued")
@@ -2980,6 +3159,60 @@ class SQLiteBackgroundTaskStore:
values["agent_backend"] = identity["backend"]
enqueue_run_in_connection(conn, values)
+ def enqueue_callback_run(
+ self,
+ payload: dict[str, Any],
+ *,
+ parent_run_id: str,
+ source_actor: str,
+ ) -> Optional[str]:
+ """Find-or-enqueue a callback child and arm its live parent atomically."""
+
+ values = self._run_values(payload)
+ now = str(values.get("updated_at") or _utc_now_iso())
+ with run_update_event_transaction(self.engine) as conn:
+ reserve_write_lock(conn)
+ parent = conn.execute(
+ select(agent_runs.c.status, agent_runs.c.cancel_requested)
+ .where(agent_runs.c.id == parent_run_id)
+ .limit(1)
+ ).mappings().first()
+ if parent is None:
+ raise ValueError(f"callback parent Run not found: {parent_run_id}")
+ callback_run_id = conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.run_type == "agent_run")
+ .where(agent_runs.c.source_kind == "callback")
+ .where(agent_runs.c.parent_run_id == parent_run_id)
+ .where(agent_runs.c.source_actor == source_actor)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ ).scalar_one_or_none()
+ parent_status = normalize_run_status(parent["status"])
+ parent_refuses_new_child = bool(parent["cancel_requested"]) and (
+ parent_status != "canceled"
+ )
+ if callback_run_id is None and parent_refuses_new_child:
+ return None
+ if callback_run_id is None:
+ enqueue_run_in_connection(conn, values)
+ callback_run_id = str(values["id"])
+ parent_update = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == parent_run_id)
+ .values(
+ callback_status="sent",
+ callback_error=None,
+ callback_run_id=callback_run_id,
+ callback_completed_at=now,
+ updated_at=now,
+ )
+ )
+ if not parent_update.rowcount:
+ raise ValueError(f"callback parent Run not found: {parent_run_id}")
+ _defer_run_ids_updated_from_connection(conn, [parent_run_id])
+ return str(callback_run_id)
+
def enqueue_definition_run(
self,
payload: dict[str, Any],
@@ -3991,37 +4224,63 @@ class SQLiteBackgroundTaskStore:
row = conn.execute(statement).first()
return None if row is None else str(row[0])
- def run_callback_state(self, run_id: str) -> Optional[str]:
- """This run's effective callback delivery state, or ``None`` without one.
-
- Read FRESH, at decision time, rather than trusted from the drain's listing:
- the owed-notice batch is listed once per pass and each row is then decided
- one at a time, so by the time a row is reached ``_drain_callbacks`` may
- already have moved its callback from ``pending`` to ``sent`` — and the
- notice decision keyed on the stale copy would defer a row whose blocker is
- already resolved, or worse, deliver beside a callback that just landed.
- A parent marked ``sent`` only proves that ``_drain_callbacks`` enqueued the
- callback child. The user has the callback only after that child succeeds and
- records delivery evidence. A persisted result row is evidence only while its
- target Session is admitted by the Inbox; a recorded native send id for a real
- IM conversation is transport evidence in its own right because it is returned
- only after delivery. Archiving or deleting the local Session afterwards cannot
- revoke that completed send. Workbench ids are synthetic and never qualify on
- their own, while a receipt in suppressed background history proves persistence,
- not visibility. This read joins the child and target Session and projects the
- state the notice lane actually needs: queued/running is pending, succeeded with
- effective delivery evidence is sent, and every other terminal outcome releases
- the notice as failed. All three lookups are primary-key probes in one statement.
-
- ``None`` means "no callback exists for this run" (no target session), which
- is different from a callback whose status column is empty — a target with
- no recorded status has never been armed, and the caller treats both as
- no-shield.
- """
+ def _callback_state_rows(
+ self,
+ *,
+ run_id: Optional[str] = None,
+ turn_id: Optional[str] = None,
+ participant_run_ids: Sequence[str] = (),
+ ) -> list[Any]:
+ """Read callback delivery facts from bounded Run ownership."""
parent = agent_runs.alias("callback_parent")
child = agent_runs.alias("callback_child")
callback_session = agent_sessions.alias("callback_session")
+ callback_output = (
+ func.json_each(child.c.result_payload_json, "$.outputs")
+ .table_valued("value")
+ .alias("callback_output")
+ )
+ linked_output_receipt = (
+ select(literal(1))
+ .select_from(callback_output)
+ .where(func.json_valid(child.c.result_payload_json) == 1)
+ .where(
+ cast(func.json_extract(callback_output.c.value, "$.id"), Text)
+ == cast(
+ func.json_extract(messages.c.metadata_json, "$.output_id"),
+ Text,
+ )
+ )
+ .where(
+ cast(
+ func.json_extract(
+ callback_output.c.value,
+ "$.provenance.turn_id",
+ ),
+ Text,
+ )
+ == cast(
+ func.json_extract(messages.c.metadata_json, "$.turn_id"),
+ Text,
+ )
+ )
+ .where(
+ func.coalesce(
+ cast(
+ func.json_extract(
+ callback_output.c.value,
+ "$.provenance.turn_id",
+ ),
+ Text,
+ ),
+ "",
+ )
+ != ""
+ )
+ .correlate(child, messages)
+ .exists()
+ )
persisted_receipt = (
select(literal(1))
.select_from(messages)
@@ -4029,34 +4288,88 @@ class SQLiteBackgroundTaskStore:
.where(messages.c.type == "result")
.where(func.json_valid(messages.c.metadata_json) == 1)
.where(
- cast(func.json_extract(messages.c.metadata_json, "$.run_id"), Text)
- == child.c.id
+ or_(
+ cast(
+ func.json_extract(messages.c.metadata_json, "$.run_id"),
+ Text,
+ )
+ == child.c.id,
+ linked_output_receipt,
+ )
+ )
+ .where(
+ func.coalesce(
+ cast(
+ func.json_extract(
+ messages.c.metadata_json,
+ "$.delivery_suppressed",
+ ),
+ Integer,
+ ),
+ 0,
+ )
+ == 0
)
.correlate(child)
.exists()
)
- with self.engine.connect() as conn:
- row = conn.execute(
- select(
- parent.c.callback_session_id,
- parent.c.callback_status,
- parent.c.callback_run_id,
- child.c.status,
- persisted_receipt,
- callback_session.c.status,
- callback_session.c.visibility,
- child.c.legacy_session_key,
- child.c.message_ids_json,
+ statement = select(
+ parent.c.callback_session_id,
+ parent.c.callback_status,
+ parent.c.callback_run_id,
+ child.c.status,
+ persisted_receipt,
+ callback_session.c.status,
+ callback_session.c.visibility,
+ child.c.legacy_session_key,
+ child.c.message_ids_json,
+ ).select_from(
+ parent.outerjoin(child, child.c.id == parent.c.callback_run_id).outerjoin(
+ callback_session,
+ callback_session.c.id == child.c.session_id,
+ )
+ )
+ live_parent = and_(
+ func.coalesce(parent.c.cancel_requested, 0) == 0,
+ ~parent.c.status.in_(_status_query_values("canceled")),
+ )
+ armed_callback = and_(
+ parent.c.callback_status == "sent",
+ parent.c.callback_run_id.is_not(None),
+ parent.c.callback_run_id != "",
+ )
+ statement = statement.where(or_(live_parent, armed_callback))
+ normalized_turn_id = str(turn_id or "").strip()
+ if normalized_turn_id:
+ normalized_participant_ids = list(
+ dict.fromkeys(
+ participant_id
+ for value in participant_run_ids
+ if (participant_id := str(value or "").strip())
)
+ )
+ durable_participant_ids = (
+ select(agent_runs.c.id)
.select_from(
- parent.outerjoin(child, child.c.id == parent.c.callback_run_id).outerjoin(
- callback_session,
- callback_session.c.id == child.c.session_id,
+ agent_runs.join(
+ message_deliveries,
+ message_deliveries.c.id == agent_runs.c.delivery_id,
)
)
- .where(parent.c.id == str(run_id))
- .limit(1)
- ).first()
+ .where(message_deliveries.c.turn_id == normalized_turn_id)
+ .where(message_deliveries.c.state == "accepted")
+ )
+ membership = [parent.c.id.in_(durable_participant_ids)]
+ if normalized_participant_ids:
+ membership.append(parent.c.id.in_(normalized_participant_ids))
+ statement = statement.where(or_(*membership))
+ else:
+ statement = statement.where(parent.c.id == str(run_id or ""))
+ with self.engine.connect() as conn:
+ return list(conn.execute(statement))
+
+ @staticmethod
+ def _callback_state_from_row(row: Any) -> Optional[str]:
if row is None or not str(row[0] or "").strip():
return None
callback_status = str(row[1] or "").strip() or None
@@ -4066,7 +4379,7 @@ class SQLiteBackgroundTaskStore:
child_status = normalize_run_status(row[3]) if row[3] is not None else ""
if child_status in {"queued", "running"}:
return "pending"
- target_key_parts = self._parse_session_key(row[7])
+ target_key_parts = SQLiteBackgroundTaskStore._parse_session_key(row[7])
message_ids = _json_loads(row[8], [])
descriptor = (
PLATFORM_REGISTRY.get(target_key_parts[0])
@@ -4092,6 +4405,66 @@ class SQLiteBackgroundTaskStore:
return "sent"
return "failed"
+ def run_callback_state(self, run_id: str) -> Optional[str]:
+ """This run's effective callback delivery state, or ``None`` without one.
+
+ Read FRESH, at decision time, rather than trusted from the drain's listing:
+ the owed-notice batch is listed once per pass and each row is then decided
+ one at a time, so by the time a row is reached ``_drain_callbacks`` may
+ already have moved its callback from ``pending`` to ``sent`` — and the
+ notice decision keyed on the stale copy would defer a row whose blocker is
+ already resolved, or worse, deliver beside a callback that just landed.
+ A parent marked ``sent`` only proves that ``_drain_callbacks`` enqueued the
+ callback child. The user has the callback only after that child succeeds and
+ records delivery evidence. A persisted result row is evidence only while its
+ target Session is admitted by the Inbox; a recorded native send id for a real
+ IM conversation is transport evidence in its own right because it is returned
+ only after delivery. Archiving or deleting the local Session afterwards cannot
+ revoke that completed send. Workbench ids are synthetic and never qualify on
+ their own, while a receipt in suppressed background history proves persistence,
+ not visibility. This read joins the child and target Session and projects the
+ state the notice lane actually needs: queued/running is pending, succeeded with
+ effective delivery evidence is sent, and every other terminal outcome releases
+ the notice as failed. All three lookups are primary-key probes in one statement.
+
+ ``None`` means "no callback exists for this run" (no target session), which
+ is different from a callback whose status column is empty — a target with
+ no recorded status has never been armed, and the caller treats both as
+ no-shield.
+ """
+
+ rows = self._callback_state_rows(run_id=run_id)
+ return self._callback_state_from_row(rows[0] if rows else None)
+
+ def turn_callback_state(
+ self,
+ turn_id: str,
+ *,
+ participant_run_ids: Sequence[str] = (),
+ ) -> Optional[str]:
+ """Aggregate callback delivery across every failed Run in one Turn.
+
+ A callback reports the Turn's terminal result, not only its parent Run. One
+ delivered callback therefore suppresses every sibling fallback; while any
+ callback is still pending, the fallback waits rather than racing it. The
+ aggregation is read in one SQLite snapshot so two sibling decisions cannot
+ observe a half-updated callback set.
+ """
+
+ states = [
+ state
+ for row in self._callback_state_rows(
+ turn_id=turn_id,
+ participant_run_ids=participant_run_ids,
+ )
+ if (state := self._callback_state_from_row(row)) is not None
+ ]
+ if "sent" in states:
+ return "sent"
+ if "pending" in states:
+ return "pending"
+ return "failed" if states else None
+
def update_callback_status(
self,
run_id: str,
@@ -4315,6 +4688,7 @@ class SQLiteBackgroundTaskStore:
terminal_status: Optional[str] = None,
error: Optional[str] = None,
updated_at: Optional[str] = None,
+ _conn: Any = None,
) -> dict[str, Any]:
"""Append one idempotent Run output and optionally settle the Run once."""
@@ -4325,9 +4699,11 @@ class SQLiteBackgroundTaskStore:
recorded = False
terminal_transition = False
text_backfilled = False
+ delivery_evidence_merged = False
run_payload: Optional[dict[str, Any]] = None
row_to_publish = None
- with self.engine.begin() as conn:
+ transaction = nullcontext(_conn) if _conn is not None else self.engine.begin()
+ with transaction as conn:
row = conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().first()
@@ -4430,6 +4806,16 @@ class SQLiteBackgroundTaskStore:
source_kind=terminal_row["source_kind"],
parent_run_id=terminal_row["parent_run_id"],
row_metadata_json=terminal_row["metadata_json"],
+ extra_metadata={
+ key: value
+ for key in (
+ "turn_id",
+ "turn_failure_notification",
+ TURN_PARTICIPANT_RUN_IDS_METADATA_KEY,
+ )
+ if provenance and (value := provenance.get(key)) is not None
+ }
+ or None,
now=now,
)
transition = conn.execute(
@@ -4484,6 +4870,16 @@ class SQLiteBackgroundTaskStore:
# the real terminal result is PR7's job -- PR1 must not paper
# over it by writing text that contradicts the status.
if stored_status == incoming_status:
+ delivery_evidence_merged = (
+ _merge_replayed_turn_delivery_evidence(
+ conn,
+ run_id=run_id,
+ row=terminal_row,
+ incoming_status=incoming_status,
+ provenance=provenance,
+ now=now,
+ )
+ )
if terminal_result_text.strip():
filled = conn.execute(
update(agent_runs)
@@ -4501,7 +4897,12 @@ class SQLiteBackgroundTaskStore:
)
text_backfilled = text_backfilled or bool(filled_error.rowcount)
- if payload_changed or terminal_transition or text_backfilled:
+ if (
+ payload_changed
+ or terminal_transition
+ or text_backfilled
+ or delivery_evidence_merged
+ ):
row_to_publish = dict(
conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
@@ -4510,7 +4911,10 @@ class SQLiteBackgroundTaskStore:
run_payload = self._run_from_row(row_to_publish)
else:
run_payload = self._run_from_row(row)
- _publish_run_rows_updated([row_to_publish])
+ if _conn is not None:
+ _defer_run_rows_updated_from_connection(_conn, [row_to_publish])
+ else:
+ _publish_run_rows_updated([row_to_publish])
return {
"recorded": recorded,
"terminal_transition": terminal_transition,
@@ -4518,9 +4922,178 @@ class SQLiteBackgroundTaskStore:
# text/error. Distinct from ``terminal_transition`` on purpose: no
# status changed, so callers must not read it as a settlement.
"text_backfilled": text_backfilled,
+ "delivery_evidence_merged": delivery_evidence_merged,
"run": run_payload,
}
+ def record_turn_run_outputs(
+ self,
+ run_ids: Sequence[str],
+ *,
+ output_id: str,
+ text: str,
+ message_id: str | None = None,
+ sequence: int | None = None,
+ provenance: Optional[dict[str, Any]] = None,
+ terminal_status: Optional[str] = None,
+ error: Optional[str] = None,
+ deferred_run_ids: Sequence[str] = (),
+ updated_at: Optional[str] = None,
+ ) -> dict[str, dict[str, Any]]:
+ """Record one Turn output across all participant Runs atomically.
+
+ The fallback owner is a property of the whole failed Turn, not of any one
+ Run write. Reserve SQLite's writer slot before reading participant state so
+ cancellation cannot land after owner election but before a later participant
+ is written with that owner's id.
+ """
+
+ from core import failure_notices
+
+ normalized_run_ids = list(
+ dict.fromkeys(
+ run_id
+ for value in run_ids
+ if (run_id := str(value or "").strip())
+ )
+ )
+ if not normalized_run_ids:
+ return {}
+ deferred_ids = {
+ run_id
+ for value in deferred_run_ids
+ if (run_id := str(value or "").strip())
+ }
+ now = updated_at or _utc_now_iso()
+ results: dict[str, dict[str, Any]] = {}
+ with run_update_event_transaction(self.engine) as conn:
+ reserve_write_lock(conn)
+ terminal_provenance = dict(provenance or {})
+ notification = terminal_provenance.get("turn_failure_notification")
+ current_owner = (
+ str(notification.get("fallback_run_id") or "").strip()
+ if isinstance(notification, dict)
+ else ""
+ )
+ candidate_ids = [*normalized_run_ids]
+ if current_owner and current_owner not in candidate_ids:
+ candidate_ids.append(current_owner)
+ rows: dict[str, Any] = {}
+ for batch in _id_batches(candidate_ids):
+ rows.update(
+ {
+ str(row["id"]): row
+ for row in conn.execute(
+ select(agent_runs).where(agent_runs.c.id.in_(batch))
+ ).mappings()
+ }
+ )
+ loaded_run_ids = [
+ run_id for run_id in normalized_run_ids if run_id in rows
+ ]
+ runs = {
+ run_id: self._run_from_row(row)
+ for run_id, row in rows.items()
+ }
+ turn_id = str(terminal_provenance.get("turn_id") or "").strip()
+ settles_failed_now = normalize_run_status(terminal_status) == "failed"
+ # Project notice ownership in the same order as the terminal writes below.
+ # A callback child whose earlier parent will acquire a notice is removed
+ # before the remaining candidates use their stable lexical tie-breaker.
+ same_batch_notice_owners: set[str] = set()
+ eligible_run_ids: list[str] = []
+ for run_id in loaded_run_ids:
+ row = rows[run_id]
+ parent_id = (
+ str(row["parent_run_id"] or "").strip()
+ if str(row["source_kind"] or "").strip() == "callback"
+ else ""
+ )
+ can_own = (
+ failure_notices.turn_fallback_owner_eligible(runs.get(run_id))
+ and _run_can_own_failure_notice(
+ conn,
+ row,
+ turn_id=turn_id,
+ will_settle_failed=(
+ settles_failed_now
+ and run_id not in deferred_ids
+ and normalize_run_status(runs[run_id].get("status"))
+ not in TERMINAL_RUN_STATUSES
+ ),
+ )
+ and parent_id not in same_batch_notice_owners
+ )
+ if can_own:
+ eligible_run_ids.append(run_id)
+ same_batch_notice_owners.add(run_id)
+ eligible_run_ids.sort()
+ immediate_owner_ids = [
+ run_id for run_id in eligible_run_ids if run_id not in deferred_ids
+ ]
+ if isinstance(notification, dict):
+ notification = dict(notification)
+ if immediate_owner_ids:
+ if current_owner not in immediate_owner_ids:
+ notification["fallback_run_id"] = immediate_owner_ids[0]
+ else:
+ # A deferred Run is still mutable: Stop can cancel it before its
+ # Activity releases terminal settlement. Electing it now makes
+ # already-terminal siblings permanently stand down for an owner
+ # that may never owe a notice. When every participant is deferred,
+ # the first Run that actually settles elects and propagates the
+ # owner under the settlement writer lock instead.
+ notification.pop("fallback_run_id", None)
+ terminal_provenance["turn_failure_notification"] = notification
+
+ if isinstance(notification, dict) and str(
+ notification.get("failure_id") or ""
+ ).strip():
+ terminal_provenance[TURN_PARTICIPANT_RUN_IDS_METADATA_KEY] = list(
+ loaded_run_ids
+ )
+
+ deferred_metadata = {
+ key: value
+ for key in (
+ "turn_id",
+ "turn_failure_notification",
+ TURN_PARTICIPANT_RUN_IDS_METADATA_KEY,
+ )
+ if (value := terminal_provenance.get(key)) is not None
+ }
+ for run_id in loaded_run_ids:
+ run = runs.get(run_id)
+ if run is None or normalize_run_status(run.get("status")) == "canceled":
+ continue
+ run_terminal_status = terminal_status
+ if run_terminal_status and run_id in deferred_ids:
+ defer_kwargs: dict[str, Any] = {
+ "terminal_status": run_terminal_status,
+ "result_text": text,
+ "updated_at": now,
+ "_conn": conn,
+ }
+ if error is not None:
+ defer_kwargs["error"] = error
+ if deferred_metadata:
+ defer_kwargs["metadata"] = deferred_metadata
+ self.defer_run_terminal(run_id, **defer_kwargs)
+ run_terminal_status = None
+ results[run_id] = self.record_run_output(
+ run_id,
+ output_id=output_id,
+ text=text,
+ message_id=message_id,
+ sequence=sequence,
+ provenance=terminal_provenance,
+ terminal_status=run_terminal_status,
+ error=error,
+ updated_at=now,
+ _conn=conn,
+ )
+ return results
+
def settle_run_terminal(
self,
run_id: str,
@@ -4664,13 +5237,16 @@ class SQLiteBackgroundTaskStore:
terminal_status: str,
error: Optional[str] = None,
result_text: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
updated_at: Optional[str] = None,
+ _conn: Any = None,
) -> bool:
- """Remember a terminal intent and result while an Activity blocks it."""
+ """Remember a terminal intent and its evidence while an Activity blocks it."""
now = updated_at or _utc_now_iso()
row_to_publish = None
- with self.engine.begin() as conn:
+ transaction = nullcontext(_conn) if _conn is not None else self.engine.begin()
+ with transaction as conn:
row = conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().first()
@@ -4694,13 +5270,25 @@ class SQLiteBackgroundTaskStore:
deferred_result_text is not None
and result_payload.get("deferred_terminal_result_text") != deferred_result_text
)
- if not status_changed and not error_changed and not result_text_changed:
+ deferred_metadata = dict(metadata) if isinstance(metadata, dict) else None
+ metadata_changed = bool(
+ deferred_metadata is not None
+ and result_payload.get(DEFERRED_TERMINAL_METADATA_KEY) != deferred_metadata
+ )
+ if (
+ not status_changed
+ and not error_changed
+ and not result_text_changed
+ and not metadata_changed
+ ):
return False
result_payload["deferred_terminal_status"] = normalized
if error_changed:
result_payload["deferred_terminal_error"] = error_text
if result_text_changed:
result_payload["deferred_terminal_result_text"] = deferred_result_text
+ if metadata_changed:
+ result_payload[DEFERRED_TERMINAL_METADATA_KEY] = deferred_metadata
conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
@@ -4714,7 +5302,10 @@ class SQLiteBackgroundTaskStore:
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().one()
)
- _publish_run_rows_updated([row_to_publish])
+ if _conn is not None:
+ _defer_run_rows_updated_from_connection(_conn, [row_to_publish])
+ else:
+ _publish_run_rows_updated([row_to_publish])
return True
def settle_deferred_run(
@@ -4729,8 +5320,14 @@ class SQLiteBackgroundTaskStore:
now = updated_at or _utc_now_iso()
row_to_publish = None
+ participant_rows_to_publish: list[dict[str, Any]] = []
transitioned = False
with self.engine.begin() as conn:
+ # Deferred Runs from one Turn can be released by independent Activity
+ # completions. Own SQLite's writer slot before reading either the Run
+ # or its current fallback owner so election, settlement, and sibling
+ # propagation observe one serialized snapshot.
+ reserve_write_lock(conn)
row = conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().first()
@@ -4755,12 +5352,85 @@ class SQLiteBackgroundTaskStore:
deferred_result_text = result_payload.pop(
"deferred_terminal_result_text", None
)
+ deferred_metadata = result_payload.pop(
+ DEFERRED_TERMINAL_METADATA_KEY, None
+ )
requested_status = (
_stronger_terminal_status(deferred_status, terminal_status)
if terminal_status
else normalize_run_status(deferred_status)
)
status, guards = _cancel_aware_terminal_status(row, requested_status)
+ participant_ids: list[str] = []
+ fallback_owner = ""
+ notice_metadata = (
+ dict(deferred_metadata)
+ if isinstance(deferred_metadata, dict)
+ else None
+ )
+ if notice_metadata is not None:
+ raw_participant_ids = notice_metadata.get(
+ TURN_PARTICIPANT_RUN_IDS_METADATA_KEY, []
+ )
+ participant_ids = list(
+ dict.fromkeys(
+ participant_id
+ for value in (
+ raw_participant_ids
+ if isinstance(raw_participant_ids, list)
+ else []
+ )
+ if (participant_id := str(value or "").strip())
+ )
+ )
+ if status == "failed" and notice_metadata is not None:
+ turn_id = str(notice_metadata.get("turn_id") or "").strip()
+ notification = notice_metadata.get("turn_failure_notification")
+ if turn_id and isinstance(notification, dict):
+ notification = dict(notification)
+ fallback_owner = str(
+ notification.get("fallback_run_id") or ""
+ ).strip()
+ current_can_own = _run_can_own_failure_notice(
+ conn,
+ row,
+ turn_id=turn_id,
+ will_settle_failed=True,
+ )
+ owner_has_notice = (
+ fallback_owner == run_id and current_can_own
+ )
+ if fallback_owner and fallback_owner != run_id:
+ owner_row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == fallback_owner)
+ .limit(1)
+ ).mappings().first()
+ owner_metadata = (
+ _json_loads(owner_row["metadata_json"], {})
+ if owner_row is not None
+ else {}
+ )
+ owner_notice = (
+ owner_metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(owner_metadata, dict)
+ else None
+ )
+ owner_has_notice = bool(
+ owner_row is not None
+ and normalize_run_status(owner_row["status"]) == "failed"
+ and isinstance(owner_notice, dict)
+ and str(owner_notice.get("turn_id") or "").strip()
+ == turn_id
+ )
+ if not owner_has_notice:
+ if current_can_own:
+ fallback_owner = run_id
+ notification["fallback_run_id"] = fallback_owner
+ else:
+ fallback_owner = ""
+ notification.pop("fallback_run_id", None)
+ notice_metadata["turn_failure_notification"] = notification
values: dict[str, Any] = {
"status": status,
"completed_at": now,
@@ -4780,6 +5450,9 @@ class SQLiteBackgroundTaskStore:
source_kind=row["source_kind"],
parent_run_id=row["parent_run_id"],
row_metadata_json=row["metadata_json"],
+ extra_metadata=(
+ notice_metadata
+ ),
now=now,
)
transition = conn.execute(
@@ -4790,6 +5463,73 @@ class SQLiteBackgroundTaskStore:
)
if transition.rowcount:
transitioned = True
+ if fallback_owner and participant_ids:
+ turn_id = str((notice_metadata or {}).get("turn_id") or "").strip()
+ for participant_id in participant_ids:
+ if participant_id == run_id:
+ continue
+ participant_row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == participant_id)
+ .limit(1)
+ ).mappings().first()
+ if (
+ participant_row is None
+ or normalize_run_status(participant_row["status"])
+ in TERMINAL_RUN_STATUSES
+ ):
+ continue
+ participant_payload = _json_loads(
+ participant_row["result_payload_json"], {}
+ )
+ if not isinstance(participant_payload, dict):
+ continue
+ participant_metadata = participant_payload.get(
+ DEFERRED_TERMINAL_METADATA_KEY
+ )
+ if not isinstance(participant_metadata, dict) or str(
+ participant_metadata.get("turn_id") or ""
+ ).strip() != turn_id:
+ continue
+ participant_notification = participant_metadata.get(
+ "turn_failure_notification"
+ )
+ if not isinstance(participant_notification, dict):
+ continue
+ participant_notification = dict(participant_notification)
+ if (
+ str(
+ participant_notification.get("fallback_run_id")
+ or ""
+ ).strip()
+ == fallback_owner
+ ):
+ continue
+ participant_notification["fallback_run_id"] = fallback_owner
+ participant_metadata = dict(participant_metadata)
+ participant_metadata["turn_failure_notification"] = (
+ participant_notification
+ )
+ participant_payload[DEFERRED_TERMINAL_METADATA_KEY] = (
+ participant_metadata
+ )
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == participant_id)
+ .values(
+ result_payload_json=_json_dumps(participant_payload),
+ updated_at=now,
+ )
+ )
+ participant_rows_to_publish.append(
+ dict(
+ conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.id == participant_id)
+ .limit(1)
+ ).mappings().one()
+ )
+ )
row_to_publish = dict(
conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
@@ -4805,7 +5545,7 @@ class SQLiteBackgroundTaskStore:
)
if row is None:
break
- _publish_run_rows_updated([row_to_publish])
+ _publish_run_rows_updated([row_to_publish, *participant_rows_to_publish])
return transitioned
def find_escalation_run(self, *, parent_run_id: str) -> Optional[dict[str, Any]]:
@@ -6834,11 +7574,11 @@ class SQLiteBackgroundTaskStore:
"watch runtimes",
lambda: self._watch_runtimes(conn, [row.get("id") for row in rows]),
)
- # Derived health for the whole page in one query. It goes here rather than in
- # a per-surface payload builder because this is the only chokepoint the CLI,
- # the list endpoint and the detail pane all pass through — and the Harness
- # detail pane has no fetch of its own, it re-renders the row the list
- # returned, so a field that is not on the row cannot reach it.
+ # Derived downstream execution health for the whole page in one query. It
+ # goes here rather than in a per-surface payload builder because this is the
+ # only chokepoint the CLI, list endpoint and detail pane all pass through.
+ # The detail pane has no fetch of its own, so a field absent here cannot
+ # reach it.
health = _lookup(
"definition health",
lambda: self.definition_health_batch(
@@ -6873,9 +7613,53 @@ class SQLiteBackgroundTaskStore:
"consecutive_failures": 0,
"recent_failures": 0,
}
- row["health"] = row_health["health"]
- row["consecutive_failures"] = row_health["consecutive_failures"]
- row["recent_failures"] = row_health["recent_failures"]
+ if definition_type == "watch":
+ # A Watch owns observation, not the Agent Turn created from an
+ # observed event. Keep the waiter signal on the existing health
+ # fields and expose downstream Run verdicts on a separate axis.
+ row["processing_health"] = row_health["health"]
+ row["processing_consecutive_failures"] = row_health[
+ "consecutive_failures"
+ ]
+ row["processing_recent_failures"] = row_health["recent_failures"]
+ retry_codes = row.get("retry_exit_codes")
+ retry_codes = retry_codes if isinstance(retry_codes, list) else []
+ exit_code = row.get("last_exit_code")
+ # A start timestamp is lifecycle evidence, not a waiter verdict.
+ waiter_observed = bool(
+ row.get("last_finished_at")
+ or exit_code is not None
+ or str(row.get("last_error") or "").strip()
+ )
+ retry_is_healthy = (
+ row.get("mode") == "forever"
+ and bool(row.get("enabled"))
+ and exit_code in retry_codes
+ )
+ successful_exit_codes = {0, NO_EVENT_EXIT_CODE}
+ waiter_failed = bool(
+ (
+ exit_code is not None
+ and exit_code not in successful_exit_codes
+ and not retry_is_healthy
+ )
+ or (
+ str(row.get("last_error") or "").strip()
+ and not retry_is_healthy
+ and exit_code != NO_EVENT_EXIT_CODE
+ )
+ )
+ row["health"] = (
+ HEALTH_UNKNOWN
+ if not waiter_observed
+ else (HEALTH_FAILING if waiter_failed else HEALTH_HEALTHY)
+ )
+ row["consecutive_failures"] = 1 if waiter_failed else 0
+ row["recent_failures"] = 1 if waiter_failed else 0
+ else:
+ row["health"] = row_health["health"]
+ row["consecutive_failures"] = row_health["consecutive_failures"]
+ row["recent_failures"] = row_health["recent_failures"]
state = row.get("lifecycle_state")
row["lifecycle_detail"] = definition_lifecycle_detail(
lifecycle_state=state,
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 3f82d83d1..a3e9ce18a 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -581,6 +581,70 @@ def get_native_message(
return _row_to_payload(dict(row)) if row else None
+def promote_suppressed_native_message(
+ conn: Connection,
+ *,
+ platform: str,
+ scope_id: str | None,
+ session_id: str | None,
+ native_message_id: str,
+ message_type: str,
+ text: str,
+ content: Optional[dict[str, Any]] = None,
+ metadata: Optional[dict[str, Any]] = None,
+) -> Optional[dict[str, Any]]:
+ """Turn local-only history into a receipt after outward delivery succeeds.
+
+ ``suppress_delivery`` deliberately persists the transcript before there is an
+ outward receipt. A later visible replay keeps the same native identity, so its
+ post-send persistence hits the unique constraint. This guarded update is that
+ replay's commit point: it removes the suppression marker only after the caller
+ has delivered, rebinds the row to that visible target Session, refreshes the
+ accepted body, and returns the now-valid receipt.
+ """
+
+ platform = str(platform or "").strip()
+ native_message_id = str(native_message_id or "").strip()
+ if not platform or not native_message_id:
+ return None
+ body: dict[str, Any] = {}
+ if content:
+ body.update(content)
+ body.setdefault("text", text)
+ now = canonical_message_timestamp(_utc_now_iso())
+ assert now is not None
+ scope_predicate = (
+ messages.c.scope_id == scope_id
+ if scope_id is not None
+ else messages.c.scope_id.is_(None)
+ )
+ promoted = conn.execute(
+ update(messages)
+ .where(messages.c.platform == platform)
+ .where(scope_predicate)
+ .where(messages.c.native_message_id == native_message_id)
+ .where(func.json_valid(messages.c.metadata_json) == 1)
+ .where(func.json_extract(messages.c.metadata_json, "$.delivery_suppressed") == 1)
+ .values(
+ session_id=session_id,
+ type=message_type,
+ content_text=text,
+ content_json=json.dumps(body),
+ metadata_json=json.dumps(metadata or {}),
+ delivered_at=now,
+ updated_at=now,
+ )
+ )
+ if not promoted.rowcount:
+ return None
+ return get_native_message(
+ conn,
+ platform=platform,
+ scope_id=scope_id,
+ native_message_id=native_message_id,
+ )
+
+
def get_quick_reply_chosen(conn: Connection, session_id: str, message_id: str) -> Optional[str]:
"""The label already chosen for *message_id*'s quick-reply group, or None.
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index c3f689506..c2e1ad1c9 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -1661,12 +1661,12 @@ scenarios:
test: tests/test_harness_failure_visibility.py::test_a_notice_stamped_without_a_backoff_field_is_still_reachable
# Rebase onto #1061's definition read projection.
- id: HFR-090
- name: a watch reports derived health on the same terms as a task
+ name: a watch reports processing health without poisoning waiter health
status: covered
kind: failure
layer: contract
backend: shared
- test: tests/test_harness_failure_visibility.py::test_a_watch_reports_health_on_the_same_terms_as_a_task
+ test: tests/test_harness_failure_visibility.py::test_a_watch_reports_processing_health_separately_from_waiter_health
- id: HFR-091
name: the drain preserves an authoritative interruption identity
status: covered
@@ -1715,16 +1715,9 @@ scenarios:
kind: failure
layer: contract
backend: shared
- # The HFR-091 × HFR-092 interaction, pinned where it bites the user. With the
- # drain's stamped ``failure_id`` authoritative and the stamp keyed by presence, a
- # ``no_terminal_result`` failure is stamped
- # ``interrupt:{run}:no_terminal_result`` while the live path keys the same failure
- # by the run id — so ``agent_message_exists`` cannot see the notification the live
- # path already persisted and the user is told twice. Neither HFR-081 (identity
- # equality, computed directly) nor HFR-091 (interruption identity survives) can
- # see it: one never runs the drain, the other uses a reason that IS in the
- # interruption set. Drives BOTH paths over one real failure and counts the durable
- # ``messages`` rows.
+ # A live Turn owns its backend failure message. Its durable Run notice remains
+ # pending until the drain observes the Turn's delivery evidence, then records a
+ # skip without replaying the same error. Separate Turns remain separate failures.
test: tests/test_harness_failure_visibility.py::test_the_drain_and_the_live_path_agree_for_a_suppressed_lane_reason
- id: HFR-094
name: a failed watch notice renders watch commands
@@ -1944,14 +1937,10 @@ scenarios:
# ``test_a_dispatch_failure_class_joins_the_per_fire_lane_and_not_the_interrupted_one`` --
# because "the pin above is an equality between two sets that both grow, so it stays
# green for a reason added correctly AND for one added to the wrong source vocabulary".
- # RETIRED IS NOT PAUSED. ``_failure_notice_body`` rendered the resume affordance for
- # every disabled watch, so a retired one read FINISHED in the lifecycle projection while
- # its notice offered ``vibe watch resume`` -- "an action that would arm a watch nobody
- # paused". Root cause is that ``enabled=0`` carries three meanings. FIX: the copy branches
- # on the ``retired_at`` column -- "the same column the projection's ``ended`` predicate
- # uses, so the copy and the badge cannot disagree" -- with a new parameterless
- # ``harness.notice.watchRetired``. A legacy row with no marker keeps the resume copy,
- # because "its history genuinely cannot prove which of the two happened".
+ # RETIRED IS NOT PAUSED. A processing-failure fallback for a normally retired Watch
+ # names event processing and omits both lifecycle copy and resume affordances: retirement
+ # did not cause the failure. A genuinely paused Watch still carries ``vibe watch resume``.
+ # Interruption notices may still explain retirement because that lifecycle is their subject.
# THE FIELD CASE IS DRIVEN END TO END, which no previous test did: every existing layer
# test stubbed one of the four steps. ``test_a_watch_that_outlives_its_delivery_target_dies_visibly``
# asserts the maintainer note's five outcomes in labelled blocks -- (a) the terminal row
@@ -1964,8 +1953,9 @@ scenarios:
# neither duplicate nor erase it. ``test_a_forever_watch_repeating_the_field_failure_notifies_once``
# takes the repetition half with a real waiter subprocess exiting 75/0/0/75 "so the LAST
# recorded cycle is the sentinel -- the state #1060's row was actually read in", and pins
- # that the sentinel never retires the watch, the projection reads ``waiting`` while health
- # reads ``failing``, and the streak still collapses to one notice.
+ # that the sentinel never retires the watch, the projection reads ``waiting`` with
+ # healthy waiter state while ``processing_health`` reads ``failing``, and the
+ # downstream streak still collapses to one notice.
# WHAT WAS FOUND ALREADY COHERENT IS RECORDED TOO, "because the plan predicted
# otherwise": ``mark_cycle_result`` already writes ``retired_at``,
# ``last_finished_at`` and ``last_event_at`` in one guarded stamp, so (c) and half of (a)
@@ -3890,6 +3880,248 @@ scenarios:
# Once the receiver has emitted Assistant text in the current generation,
# its ResultMessage is the real continuation and must settle the pending Turn.
test: tests/test_claude_agent_sessions.py::test_steered_assistant_and_result_settle_the_pending_turn
+ - id: HFR-436
+ name: Watch waiter health is independent from downstream event processing
+ status: covered
+ kind: observability
+ layer: contract
+ backend: shared
+ # A zero-exit waiter remains healthy even when the Agent Run created from its
+ # event fails. The downstream verdict is exposed as processing_health; retry
+ # codes are healthy only while an enabled forever waiter can actually retry;
+ # terminal outcomes stay failing even when their code appears in the retry set.
+ test: tests/test_harness_health_projection.py::test_watch_health_separates_waiter_from_event_processing
+ - id: HFR-437
+ name: one visible Turn failure suppresses every linked Run fallback
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The backend failure notification is the Turn's primary user-visible error.
+ # All Runs accepted by that Turn retain failed audit state without repeating it.
+ # Local persistence under suppress_delivery is not an acknowledgement, so the
+ # durable fallback remains eligible to reach a user-visible target.
+ test: tests/test_harness_failure_visibility.py::test_hfr_437_visible_turn_failure_suppresses_all_linked_run_notices
+ - id: HFR-438
+ name: one linked Run reports a missing Turn failure notification
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # If primary delivery is not acknowledged, Turn identity elects one fallback
+ # across definitions and every other linked Run records the shared outcome.
+ # Canceled or still-deferred participants cannot own notices already owed by a
+ # settled sibling, and late participants reuse the durable Turn-wide election
+ # instead of electing again from their subset. When every participant is deferred,
+ # the first failed settlement propagates its stable ownership to the rest under
+ # the same reserved SQLite writer transaction.
+ test: tests/test_harness_failure_visibility.py::test_hfr_438_missing_turn_notification_delivers_one_fallback
+ - id: HFR-439
+ name: Turn failure notification evidence reaches every linked Run settlement
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Terminal settlement copies the Turn notification identity and delivery proof
+ # into each owed notice atomically with the failed Run transition. The immutable
+ # Turn snapshot supplies the initial fallback owner; the locked participant
+ # settlement validates it against current cancellation and deferral state before
+ # any Run is written. If an Activity still owns the Run, the same evidence is first
+ # committed with its deferred terminal intent and survives into the eventual
+ # transition. Explicit delivery evidence remains authoritative for legacy Harness
+ # contexts that have no Turn token.
+ test: tests/test_scheduled_tasks.py::test_hfr_439_turn_failure_metadata_reaches_every_linked_run
+ - id: HFR-440
+ name: one sibling callback receipt suppresses the complete Turn fallback
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # A callback carries the shared terminal Turn result. Callback delivery facts
+ # are aggregated from one SQLite snapshot across every linked failed Run, so a
+ # successful sibling callback prevents the elected owner from sending again.
+ test: tests/test_harness_failure_visibility.py::test_hfr_440_one_sibling_callback_suppresses_the_whole_turn_fallback
+ - id: HFR-441
+ name: suppressed local history cannot shadow an outward receipt
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # suppress_delivery rows carry an explicit marker and are rejected as receipts.
+ # A later visible fallback sends first, then promotes the stable row under a
+ # guarded update. Local row ids never enter Run transport receipts, and a
+ # suppressed callback row is never delivery evidence.
+ test: tests/test_harness_failure_visibility.py::test_suppressed_history_cannot_shadow_a_later_visible_receipt
+ - id: HFR-442
+ name: bare Turn provenance does not enter notification ownership
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Direct error results retain their Turn id as execution provenance, but only
+ # an explicit turn_failure_notification contract admits the Turn fallback lane.
+ # Definition-level suppression therefore remains active for generic failures.
+ test: tests/test_harness_failure_visibility.py::test_hfr_442_bare_turn_provenance_does_not_enter_the_fallback_lane
+ - id: HFR-443
+ name: deferred callback participant blocks the Turn fallback
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Turn membership is read from either an active owed notice or a deferred
+ # terminal intent. A pending callback on the deferred participant therefore
+ # blocks an immediately settled sibling from sending the same result.
+ test: tests/test_harness_failure_visibility.py::test_hfr_443_deferred_sibling_callback_blocks_the_turn_fallback
+ - id: HFR-444
+ name: first in-flight waiter health remains unknown
+ status: covered
+ kind: observability
+ layer: contract
+ backend: shared
+ # A cycle start is not a waiter outcome. Until a finish, exit code, or error is
+ # recorded, the first cycle cannot project a healthy verdict.
+ test: tests/test_harness_failure_visibility.py::test_hfr_444_first_in_flight_waiter_health_remains_unknown
+ - id: HFR-445
+ name: suppressed history promotion adopts the visible target Session
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The guarded post-send promotion preserves the stable native identity while
+ # rebinding the Message row from its hidden source Session to the visible target.
+ test: tests/test_harness_failure_visibility.py::test_visible_send_promotes_the_stable_suppressed_history_row
+ - id: HFR-446
+ name: promoted history uses visible delivery order
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Promotion stamps delivered_at at the post-send commit point. Transcript
+ # ordering therefore places the stable row after content that was already
+ # visible when the hidden copy was originally created.
+ test: tests/test_harness_failure_visibility.py::test_hfr_446_promoted_receipt_uses_visible_delivery_order
+ - id: HFR-447
+ name: Turn fallback owners can persist their notice
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Immediate and deferred owner election use the exact metadata-writability
+ # predicate used by notice persistence. Malformed legacy rows still settle,
+ # but a writable participant becomes the stable fallback owner.
+ test: tests/test_harness_failure_visibility.py::test_hfr_447_fallback_owner_requires_writable_notice_metadata
+ - id: HFR-448
+ name: canceled deferred callbacks do not block a Turn fallback
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Turn-wide callback membership includes deferred participants only while
+ # they remain live. A canceled or cancel-requested parent cannot later deliver
+ # its callback, so an immediate sibling's fallback is released.
+ test: tests/test_harness_failure_visibility.py::test_hfr_448_cancel_requested_callback_does_not_block_turn_fallback
+ - id: HFR-449
+ name: canceled parents preserve armed callback evidence
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Cancellation removes an unarmed parent from Turn callback membership, but
+ # cannot revoke a child that was already accepted. Pending and delivered child
+ # outcomes continue to defer or suppress the shared fallback.
+ test: tests/test_harness_failure_visibility.py::test_hfr_449_canceled_parent_keeps_armed_callback_evidence
+ - id: HFR-450
+ name: terminal replay promotes newer Turn delivery evidence
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # A duplicate terminal event cannot re-settle the Run, but a later successful
+ # primary notification is monotonic evidence. It upgrades the existing notice
+ # without resetting attempts or fallback ownership.
+ test: tests/test_harness_failure_visibility.py::test_hfr_450_terminal_replay_promotes_new_turn_delivery_evidence
+ - id: HFR-451
+ name: Turn callback membership lookup stays bounded
+ status: covered
+ kind: performance
+ layer: contract
+ backend: shared
+ # The callback snapshot is bounded by explicit participant ids and the indexed
+ # Delivery-to-Turn ownership relation. It never searches Run metadata JSON by
+ # Turn id as history grows.
+ test: tests/test_harness_failure_visibility.py::test_hfr_451_turn_callback_lookup_uses_bounded_ownership
+ - id: HFR-452
+ name: callback children cannot own the Turn fallback
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Owner election uses the same suppression predicate as notice persistence, so
+ # a callback child whose parent already owns a notice cannot silence siblings.
+ test: tests/test_harness_failure_visibility.py::test_hfr_452_callback_children_cannot_own_a_turn_fallback
+ - id: HFR-453
+ name: callback enqueue and parent arming are atomic
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # SQLite exposes the callback child and its parent marker in one commit. A
+ # cancellation cannot open an enqueue-to-stamp window for duplicate fallback.
+ test: tests/test_harness_failure_visibility.py::test_hfr_453_callback_enqueue_arms_the_parent_in_one_transaction
+ - id: HFR-454
+ name: delivery evidence follows the routed target platform
+ status: covered
+ kind: routing
+ layer: contract
+ backend: shared
+ # A transport-only id acknowledges a real IM target but never a synthetic Avibe
+ # target, regardless of the source Session platform before delivery_override.
+ test: tests/test_backend_failure.py::BackendFailureTests::test_hfr_454_delivery_only_ack_uses_the_routed_target_platform
+ - id: HFR-455
+ name: Turn fallback excludes same-batch parent suppression
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # A parent processed before its callback child owns the Turn fallback before
+ # that new parent notice suppresses the child, independent of lexical Run ids.
+ test: tests/test_harness_failure_visibility.py::test_hfr_455_turn_owner_excludes_same_batch_parent_suppression
+ - id: HFR-456
+ name: late-canceled failed parents reject only new callbacks
+ status: covered
+ kind: cancellation
+ layer: contract
+ backend: shared
+ # The SQLite writer refuses a new failure callback after late cancellation but
+ # still arms an already-durable child as authoritative callback evidence.
+ test: tests/test_harness_failure_visibility.py::test_hfr_456_late_canceled_failed_parent_rejects_only_new_callbacks
+ - id: HFR-457
+ name: stale Turn participant ids cannot roll back valid settlement
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: shared
+ # Ownership projection and terminal writes use only Runs loaded under the
+ # settlement writer lock; stale attribution is excluded from durable provenance.
+ test: tests/test_harness_failure_visibility.py::test_hfr_457_missing_turn_participant_does_not_rollback_valid_runs
+ - id: HFR-458
+ name: steered callbacks inherit shared Turn output receipts
+ status: covered
+ kind: delivery
+ layer: contract
+ backend: shared
+ # A callback accepted into an active Turn shares the persisted result through
+ # exact Turn and output provenance even when another Run is the primary owner.
+ test: tests/test_harness_failure_visibility.py::test_hfr_458_steered_callback_uses_its_shared_turn_output_receipt
+ - id: HFR-459
+ name: deferred Turn owner election is writer-serialized
+ status: covered
+ kind: concurrency
+ layer: contract
+ backend: shared
+ # Activity completions reserve SQLite's writer slot before reading deferred
+ # participants or their owner, so one Turn cannot elect competing fallbacks.
+ test: tests/test_harness_failure_visibility.py::test_hfr_459_deferred_owner_election_reserves_writer_before_reads
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
@@ -3897,3 +4129,4 @@ plan: docs/plans/harness-session-failure-recovery.md
plans:
- docs/plans/harness-session-failure-recovery.md
- docs/plans/agent-run-zombie-settlement.md
+ - docs/plans/harness-watch-run-failure-boundary.md
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index 1fe99cff5..dc23870b1 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -272,3 +272,18 @@ observations:
the failed terminal result is the existing release action for Avibe's per-Session
runtime gate and durable Run. Timeout must perform them in that order and must
not fall through to the empty successful-result path.
+ - id: HFR-OBS-023
+ date: 2026-08-08
+ source: live Watch d5efa8fcbdc2 and its three Runs in one failed Agent Turn
+ result: confirmed
+ detail: >-
+ A Watch waiter and the Agent Turn it starts are different lifecycle owners.
+ The observed waiter exited zero, retired normally, and queued one Run, while
+ that Run and two Runs from other definitions were steered into the same Turn.
+ One backend transport failure then settled all three Runs. Per-definition
+ owed-notice ownership converted that single Turn failure into three Harness
+ failure messages and projected every successful waiter as unhealthy. The
+ durable Watch-to-Run link is necessary provenance, but failure visibility
+ belongs to the Turn and waiter health belongs to the waiter. Linked Runs need
+ only one Turn-scoped fallback when the primary backend notification cannot be
+ acknowledged; downstream processing health must remain a separate projection.
diff --git a/tests/test_backend_failure.py b/tests/test_backend_failure.py
index 3d2f0c068..00a158e06 100644
--- a/tests/test_backend_failure.py
+++ b/tests/test_backend_failure.py
@@ -28,6 +28,196 @@ def _request() -> AgentRequest:
class BackendFailureTests(unittest.IsolatedAsyncioTestCase):
+ async def test_harness_turn_notifies_live_and_carries_delivery_evidence_to_settlement(
+ self,
+ ) -> None:
+ request = _request()
+ request.context.platform_specific.update(
+ {
+ "task_execution_id": "run-watch-1",
+ "task_trigger_kind": "watch",
+ }
+ )
+ emissions = []
+
+ async def emit(context, message_type, text, **kwargs):
+ emissions.append((message_type, text, kwargs))
+ evidence = kwargs.get("delivery")
+ if message_type == "notify" and evidence is not None:
+ evidence.delivered_id = "msg-1"
+ evidence.persisted_row = {"id": "msg-1"}
+ evidence.send_returned = True
+ return "msg-1"
+ return None
+
+ auth = AsyncMock(return_value=False)
+ controller = SimpleNamespace(
+ agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=auth),
+ emit_agent_message=emit,
+ )
+
+ handled_auth = await emit_backend_failure(
+ controller,
+ request.context,
+ "codex",
+ "provider unavailable",
+ request=request,
+ )
+
+ self.assertFalse(handled_auth)
+ auth.assert_not_awaited()
+ self.assertEqual([message_type for message_type, _text, _kwargs in emissions], ["notify", "result"])
+ notify_output = emissions[0][2]["output"]
+ self.assertEqual(notify_output.idempotency_key, "backend-failure:turn:turn-1")
+ terminal_output = emissions[1][2]["output"]
+ self.assertEqual(
+ terminal_output.metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn:turn-1",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ },
+ )
+
+ async def test_run_attached_to_an_existing_turn_keeps_harness_failure_ownership(
+ self,
+ ) -> None:
+ request = _request()
+ request.context.platform_specific["accepted_agent_run_ids"] = [
+ "run-attached-1"
+ ]
+ emissions = []
+
+ async def emit(context, message_type, text, **kwargs):
+ emissions.append((message_type, kwargs))
+ evidence = kwargs.get("delivery")
+ if message_type == "notify" and evidence is not None:
+ evidence.persisted_row = {"id": "msg-attached"}
+ return "msg-attached"
+ return None
+
+ auth = AsyncMock(return_value=False)
+ controller = SimpleNamespace(
+ agent_auth_service=SimpleNamespace(maybe_emit_auth_recovery_message=auth),
+ emit_agent_message=emit,
+ )
+
+ await emit_backend_failure(
+ controller,
+ request.context,
+ "codex",
+ "stream disconnected",
+ request=request,
+ )
+
+ auth.assert_not_awaited()
+ self.assertEqual([message_type for message_type, _kwargs in emissions], ["notify", "result"])
+ self.assertEqual(
+ emissions[1][1]["output"].metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn:turn-1",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ },
+ )
+
+ async def test_suppressed_harness_notification_does_not_ack_local_message_id(
+ self,
+ ) -> None:
+ request = _request()
+ request.context.platform = "slack"
+ request.context.platform_specific.update(
+ {
+ "task_execution_id": "run-background-1",
+ "task_trigger_kind": "watch",
+ "suppress_delivery": True,
+ }
+ )
+ emissions = []
+
+ async def emit(_context, message_type, _text, **kwargs):
+ emissions.append((message_type, kwargs))
+ if message_type == "notify":
+ return "suppressed:run-background-1"
+ return None
+
+ controller = SimpleNamespace(
+ agent_auth_service=SimpleNamespace(
+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)
+ ),
+ emit_agent_message=emit,
+ )
+
+ await emit_backend_failure(
+ controller,
+ request.context,
+ "codex",
+ "stream disconnected",
+ request=request,
+ )
+
+ terminal_output = emissions[1][1]["output"]
+ self.assertEqual(
+ terminal_output.metadata["turn_failure_notification"],
+ {
+ "failure_id": "turn:turn-1",
+ "ack_evidence": None,
+ "delivered": False,
+ },
+ )
+
+ async def test_hfr_454_delivery_only_ack_uses_the_routed_target_platform(
+ self,
+ ) -> None:
+ """Transport-only ids are evidence according to where the notify was sent."""
+
+ for source, target, expected in (
+ ("avibe", "slack", True),
+ ("slack", "avibe", False),
+ ):
+ with self.subTest(source=source, target=target):
+ request = _request()
+ request.context.platform = source
+ request.context.platform_specific.update(
+ {
+ "task_execution_id": f"run-{source}-to-{target}",
+ "delivery_override": {
+ "platform": target,
+ "channel_id": f"channel-{target}",
+ },
+ }
+ )
+ emissions = []
+
+ async def emit(_context, message_type, _text, **kwargs):
+ emissions.append((message_type, kwargs))
+ evidence = kwargs.get("delivery")
+ if message_type == "notify" and evidence is not None:
+ evidence.delivered_id = f"native-{target}-id"
+ evidence.send_returned = True
+ return None
+
+ controller = SimpleNamespace(
+ agent_auth_service=SimpleNamespace(
+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False)
+ ),
+ emit_agent_message=emit,
+ )
+
+ await emit_backend_failure(
+ controller,
+ request.context,
+ "codex",
+ "stream disconnected",
+ request=request,
+ )
+
+ notification = emissions[1][1]["output"].metadata[
+ "turn_failure_notification"
+ ]
+ self.assertEqual(notification["ack_evidence"], "delivery_only")
+ self.assertIs(notification["delivered"], expected)
+
async def test_auth_recovery_owns_the_only_terminal_settlement(self) -> None:
request = _request()
controller = SimpleNamespace(
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
index 3ed9c2b1d..59cabd9e3 100644
--- a/tests/test_harness_failure_visibility.py
+++ b/tests/test_harness_failure_visibility.py
@@ -24,7 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sqlalchemy import event, select
-from core.scheduled_tasks import TaskExecutionStore
+from core.scheduled_tasks import TaskExecutionRequest, TaskExecutionStore
from storage.background import (
NOTICE_KIND_BINDING_CHANGE,
NOTICE_KIND_FAILURE,
@@ -305,10 +305,10 @@ def test_a_cancel_landing_under_record_run_output_is_not_overwritten(
assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
-def test_a_cancel_landing_under_settle_deferred_run_is_not_overwritten(
+def test_a_cancel_landing_before_deferred_owner_reservation_is_not_overwritten(
tmp_path: Path,
) -> None:
- """An Activity's deferred failure remains subordinate to a concurrent Stop."""
+ """A Stop that wins the writer reservation remains authoritative."""
sqlite, requests = _store(tmp_path)
request = requests.enqueue_agent_run(
@@ -324,14 +324,14 @@ def test_a_cancel_landing_under_settle_deferred_run_is_not_overwritten(
result_text="backend failed",
)
- listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
+ listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="BEGIN IMMEDIATE")
event.listen(sqlite.engine, "before_cursor_execute", listener)
try:
transitioned = sqlite.settle_deferred_run(request.id)
finally:
event.remove(sqlite.engine, "before_cursor_execute", listener)
- assert fired, "the interleaved cancel never fired; the race was not exercised"
+ assert fired, "the cancel never won the writer reservation"
saved = sqlite.get_run(request.id)
assert transitioned is True
assert saved["status"] == "canceled"
@@ -390,6 +390,312 @@ def test_the_cancel_cas_does_not_leave_an_uncancelled_run_unsettled(tmp_path: Pa
assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
+def test_turn_output_batch_locks_before_re_electing_a_canceled_fallback_owner(
+ tmp_path: Path,
+) -> None:
+ """One locked snapshot owns election and every participant's terminal write."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-owner-a")
+ _task(sqlite, "watch-owner-b")
+ runs = [
+ requests.enqueue_task_run(definition_id)
+ for definition_id in ("watch-owner-a", "watch-owner-b")
+ ]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ assert sqlite.cancel_run(runs[0].id)
+
+ statements: list[str] = []
+
+ def _capture_statement(conn, cursor, statement, parameters, context, executemany):
+ statements.append(statement.strip().upper())
+
+ event.listen(sqlite.engine, "before_cursor_execute", _capture_statement)
+ try:
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": "turn-shared",
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-shared",
+ "delivered": False,
+ "fallback_run_id": runs[0].id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _capture_statement)
+
+ lock_index = statements.index("BEGIN IMMEDIATE")
+ participant_read_index = next(
+ index
+ for index, statement in enumerate(statements)
+ if statement.startswith("SELECT") and "FROM AGENT_RUNS" in statement
+ )
+ assert lock_index < participant_read_index
+ assert sqlite.get_run(runs[0].id)["status"] == "canceled"
+ assert sqlite.get_run(runs[1].id)["status"] == "failed"
+ notice = sqlite.owed_failure_notice(runs[1].id)
+ assert notice["turn_fallback_run_id"] == runs[1].id
+
+
+def test_turn_output_batch_prefers_an_immediately_settled_fallback_owner(
+ tmp_path: Path,
+) -> None:
+ """A running Activity cannot own notices that its terminal sibling owes now."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-immediate-owner-a")
+ _task(sqlite, "watch-immediate-owner-b")
+ runs = [
+ requests.enqueue_task_run(definition_id)
+ for definition_id in ("watch-immediate-owner-a", "watch-immediate-owner-b")
+ ]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ deferred, immediate = sorted(runs, key=lambda run: run.id)
+
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": "turn-immediate-owner",
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-immediate-owner",
+ "delivered": False,
+ "fallback_run_id": deferred.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[deferred.id],
+ )
+
+ assert sqlite.get_run(deferred.id)["status"] == "running"
+ assert sqlite.get_run(immediate.id)["status"] == "failed"
+ assert sqlite.owed_failure_notice(immediate.id)["turn_fallback_run_id"] == immediate.id
+ deferred_metadata = sqlite.get_run(deferred.id)["result_payload"][
+ "deferred_terminal_metadata"
+ ]
+ assert (
+ deferred_metadata["turn_failure_notification"]["fallback_run_id"]
+ == immediate.id
+ )
+
+
+def test_all_deferred_turn_runs_elect_and_propagate_the_first_stable_owner(
+ tmp_path: Path,
+) -> None:
+ """A canceled deferred candidate cannot strand the Turn's only fallback."""
+
+ sqlite, requests = _store(tmp_path)
+ definitions = [f"watch-deferred-owner-{index}" for index in range(3)]
+ for definition_id in definitions:
+ _task(sqlite, definition_id)
+ runs = [requests.enqueue_task_run(definition_id) for definition_id in definitions]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": "turn-all-deferred",
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-all-deferred",
+ "delivered": False,
+ "fallback_run_id": runs[0].id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[run.id for run in runs],
+ )
+ for run in runs:
+ metadata = sqlite.get_run(run.id)["result_payload"][
+ "deferred_terminal_metadata"
+ ]
+ assert "fallback_run_id" not in metadata["turn_failure_notification"]
+
+ assert sqlite.cancel_run(runs[0].id)
+ assert sqlite.settle_deferred_run(runs[0].id)
+ assert sqlite.get_run(runs[0].id)["status"] == "canceled"
+
+ assert sqlite.settle_deferred_run(runs[1].id)
+ first_notice = sqlite.owed_failure_notice(runs[1].id)
+ assert first_notice["turn_fallback_run_id"] == runs[1].id
+ propagated = sqlite.get_run(runs[2].id)["result_payload"][
+ "deferred_terminal_metadata"
+ ]
+ assert (
+ propagated["turn_failure_notification"]["fallback_run_id"] == runs[1].id
+ )
+
+ assert sqlite.settle_deferred_run(runs[2].id)
+ second_notice = sqlite.owed_failure_notice(runs[2].id)
+ assert second_notice["turn_fallback_run_id"] == runs[1].id
+
+
+def test_hfr_459_deferred_owner_election_reserves_writer_before_reads(
+ tmp_path: Path,
+) -> None:
+ """Independent Activity releases serialize before choosing a Turn owner."""
+
+ sqlite, requests = _store(tmp_path)
+ definitions = ["watch-deferred-lock-a", "watch-deferred-lock-b"]
+ for definition_id in definitions:
+ _task(sqlite, definition_id)
+ runs = [requests.enqueue_task_run(definition_id) for definition_id in definitions]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ turn_id = "turn-deferred-owner-lock"
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[run.id for run in runs],
+ )
+
+ statements: list[str] = []
+
+ def _capture_statement(conn, cursor, statement, parameters, context, executemany):
+ statements.append(statement.strip().upper())
+
+ event.listen(sqlite.engine, "before_cursor_execute", _capture_statement)
+ try:
+ assert sqlite.settle_deferred_run(runs[0].id)
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _capture_statement)
+
+ lock_index = statements.index("BEGIN IMMEDIATE")
+ first_run_read = next(
+ index
+ for index, statement in enumerate(statements)
+ if statement.startswith("SELECT") and "FROM AGENT_RUNS" in statement
+ )
+ assert lock_index < first_run_read
+ first_notice = sqlite.owed_failure_notice(runs[0].id)
+ assert first_notice["turn_fallback_run_id"] == runs[0].id
+ assert sqlite.settle_deferred_run(runs[1].id)
+ second_notice = sqlite.owed_failure_notice(runs[1].id)
+ assert second_notice["turn_fallback_run_id"] == runs[0].id
+
+
+def test_hfr_447_fallback_owner_requires_writable_notice_metadata(
+ tmp_path: Path,
+) -> None:
+ """Owner election and notice persistence share one eligibility predicate."""
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ definitions = ["watch-bad-owner", "watch-valid-owner"]
+ for definition_id in definitions:
+ _task(sqlite, definition_id)
+ runs = sorted(
+ (requests.enqueue_task_run(definition_id) for definition_id in definitions),
+ key=lambda run: run.id,
+ )
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ malformed, valid = runs
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == malformed.id)
+ .values(metadata_json="{not-json")
+ )
+
+ turn_id = "turn-writable-owner"
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": malformed.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ )
+
+ assert sqlite.get_run(malformed.id)["status"] == "failed"
+ assert sqlite.owed_failure_notice(malformed.id) is None
+ assert sqlite.owed_failure_notice(valid.id)["turn_fallback_run_id"] == valid.id
+
+ deferred_definitions = ["watch-bad-deferred-owner", "watch-valid-deferred-owner"]
+ for definition_id in deferred_definitions:
+ _task(sqlite, definition_id)
+ deferred_runs = sorted(
+ (
+ requests.enqueue_task_run(definition_id)
+ for definition_id in deferred_definitions
+ ),
+ key=lambda run: run.id,
+ )
+ for run in deferred_runs:
+ assert requests.claim(run.id) is not None
+ malformed_deferred, valid_deferred = deferred_runs
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == malformed_deferred.id)
+ .values(metadata_json="[]")
+ )
+
+ deferred_turn_id = "turn-writable-deferred-owner"
+ sqlite.record_turn_run_outputs(
+ [run.id for run in deferred_runs],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": deferred_turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{deferred_turn_id}",
+ "delivered": False,
+ "fallback_run_id": malformed_deferred.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[run.id for run in deferred_runs],
+ )
+
+ assert sqlite.settle_deferred_run(malformed_deferred.id)
+ assert sqlite.owed_failure_notice(malformed_deferred.id) is None
+ pending_metadata = sqlite.get_run(valid_deferred.id)["result_payload"][
+ "deferred_terminal_metadata"
+ ]
+ assert "fallback_run_id" not in pending_metadata["turn_failure_notification"]
+ assert sqlite.settle_deferred_run(valid_deferred.id)
+ assert (
+ sqlite.owed_failure_notice(valid_deferred.id)["turn_fallback_run_id"]
+ == valid_deferred.id
+ )
+
+
# --- group 2: the owed-notice drain ---------------------------------------
#
# The policy decisions are tested against ``core.failure_notices.decide`` directly:
@@ -1746,6 +2052,65 @@ def test_a_failed_watch_notice_renders_watch_commands(tmp_path: Path) -> None:
assert "ci waiter" in body, f"the watch's own name must survive the lookup: {body}"
+ ("outcome", "headline_key"),
+ [
+ ("event", "harness.notice.watchProcessingFailed"),
+ ("waiter_failure", "harness.notice.watchFailureReportFailed"),
+ ],
+)
+def test_watch_notice_copy_preserves_the_waiter_outcome(
+ tmp_path: Path,
+ outcome: str,
+ headline_key: str,
+) -> None:
+ """A failed reporting Turn cannot turn a waiter failure into an event."""
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+ from storage.background import WATCH_HOOK_OUTCOME_METADATA_KEY
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _watch(sqlite, "watch-copy", name="CI waiter")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ run = requests.enqueue_hook_send(
+ session_key="slack::channel::C1",
+ prompt="report the Watch outcome",
+ run_type="watch",
+ definition_id="watch-copy",
+ metadata={WATCH_HOOK_OUTCOME_METADATA_KEY: outcome},
+ )
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(
+ claimed,
+ ok=False,
+ error="Agent report failed",
+ task_id="watch-copy",
+ )
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(
+ platform_settings_managers={},
+ session_turn_gate=None,
+ )
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ body = service._failure_notice_body(
+ sqlite.get_run(run.id),
+ sqlite.owed_failure_notice(run.id),
+ )
+
+ assert i18n_t(headline_key, "en").split("{")[0] in body
+ if outcome == "waiter_failure":
+ assert "detected an event" not in body
+
+
def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> None:
"""The task-side twin of the retired-watch copy fix — FINISHED IS NOT PAUSED.
@@ -1980,35 +2345,14 @@ def test_the_duplicate_short_circuit_reports_its_receipt(tmp_path: Path) -> None
assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
-def test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung() -> None:
- """HFR-075 — the dedup receipt has to satisfy the STRICTEST ack source there is.
-
- The receipt above is the general claim; this is the one consumer for which it is
- load-bearing rather than convenient. A workbench rung may acknowledge on a
- durable persisted receipt and on nothing else (``LADDER_ACK_SOURCES``), so if the
- duplicate short-circuit reported its found row as anything weaker than
- ``receipt`` — a bare ``delivered_id``, say — then the exact case the idempotency
- key exists for would be unserviceable on avibe: a crash between persisting the
- message and acknowledging the notice would find the row, decline to re-send,
- report nothing the policy accepts, and then re-send forever on other rungs or
- dead-letter a notice the user demonstrably already has.
-
- Driven through the real dispatcher against an avibe context, then handed to the
- real predicate, because the claim spans the two modules: what the short-circuit
- fills in, and what the ladder is willing to ack on.
- """
+def test_suppressed_duplicate_short_circuit_is_local_history_not_a_receipt() -> None:
+ """A background Session's persisted row proves no outward delivery."""
from unittest.mock import patch
import core.message_dispatcher as dispatcher_module
- from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, DeliveryEvidence
+ from core.delivery_evidence import DeliveryEvidence
from core.message_output import MessageOutput
- from core.scheduled_tasks import (
- ACK_SOURCE_PERSISTED_RECEIPT,
- ScheduledTaskService,
- failure_notice_ack_source,
- parse_scope_id,
- )
from modules.im import MessageContext
from tests.test_message_dispatcher_scheduled import _StubController
@@ -2017,13 +2361,12 @@ def test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung() -> None:
dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
context = MessageContext(
user_id="scheduled",
- channel_id="proj-notice",
- platform="avibe",
+ channel_id="C123",
+ platform="slack",
platform_specific={
- "platform": "avibe",
- "agent_session_id": "sesDup",
"task_trigger_kind": "scheduled",
- "task_execution_id": "run-dup",
+ "task_execution_id": "run-background",
+ "suppress_delivery": True,
},
)
evidence = DeliveryEvidence()
@@ -2033,63 +2376,353 @@ def test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung() -> None:
dispatcher.emit_agent_message(
context,
"notify",
- "your task failed",
+ "your background task failed",
output=MessageOutput(
completes_turn=False,
completes_run=False,
- idempotency_key="backend-failure:failure:run-dup",
+ idempotency_key="backend-failure:failure:run-background",
),
delivery=evidence,
)
)
- assert returned and "backend-failure:failure:run-dup" in returned
- assert controller.im_client.sent == [], "the row already exists; nothing may be re-sent"
-
- target = parse_scope_id("avibe::project::proj-notice")
- assert failure_notice_ack_source(target) == ACK_SOURCE_PERSISTED_RECEIPT, (
- "the premise: this target class accepts nothing but a receipt"
- )
- assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
- assert ScheduledTaskService._rung_acknowledges(target, evidence) is True, (
- "a found row must acknowledge a workbench rung, or a crash-then-retry there "
- "can never settle"
- )
- # And the rejection annotation stays off a rung that was accepted: an ack that
- # also carried a "no persisted receipt" error would report a lie on the notice.
- assert evidence.error is None
-
+ assert returned and "backend-failure:failure:run-background" in returned
+ assert controller.im_client.sent == []
+ assert evidence.ack_evidence is None
-def test_a_raising_delivery_consumes_an_attempt_instead_of_retrying_forever(
- tmp_path: Path,
- monkeypatch,
-) -> None:
- """HFR-076 — an exception must not escape before ``attempts`` is persisted.
- ``_deliver_one_failure_notice`` computed the attempt number, then awaited
- delivery, then wrote the result. An exception from any ladder rung escaped
- between the second and third step, so nothing was persisted and the next 2 s
- tick recomputed the SAME attempt number and raised again — an unbounded retry
- loop, which is precisely what the backoff exists to prevent.
+def test_suppressed_history_cannot_shadow_a_later_visible_receipt() -> None:
+ """HFR-441 — local history cannot satisfy the stable outward identity."""
- The live case is auth recovery (see the bypass test below), but the bound has
- to hold for ANY raising rung, so this test raises directly.
- """
+ from unittest.mock import patch
- from types import SimpleNamespace
+ import core.message_dispatcher as dispatcher_module
+ from core.delivery_evidence import DeliveryEvidence
+ from core.message_output import MessageOutput
+ from modules.im import MessageContext
- import core.scheduled_tasks as scheduled_tasks
- from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+ from tests.test_message_dispatcher_scheduled import _StubController
- sqlite, requests = _store(tmp_path)
- _task(sqlite, "task-raise", deliver_key="slack::channel::C1")
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- store._sqlite = sqlite
- store.load()
+ controller = _StubController()
+ dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
+ persisted: dict[str, dict[str, Any]] = {}
+ persisted_versions: list[dict[str, Any]] = []
+
+ def _lookup(_context, native_message_id):
+ return persisted.get(str(native_message_id))
+
+ def _persist(
+ _context,
+ canonical_type,
+ text,
+ *,
+ metadata=None,
+ native_message_id=None,
+ **_kwargs,
+ ):
+ row = {
+ "id": f"row-{len(persisted) + 1}",
+ "type": canonical_type,
+ "text": text,
+ "metadata": dict(metadata or {}),
+ "native_message_id": native_message_id,
+ }
+ persisted[str(native_message_id)] = row
+ persisted_versions.append(row)
+ return row
- run = requests.enqueue_task_run("task-raise")
- claimed = requests.claim(run.id)
- requests.complete(claimed, ok=False, error="boom", task_id="task-raise")
+ output = MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="backend-failure:failure:shared",
+ )
+ suppressed = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={"suppress_delivery": True},
+ )
+ visible = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ )
+ evidence = DeliveryEvidence()
+
+ with (
+ patch.object(dispatcher_module, "agent_message_exists", side_effect=_lookup),
+ patch.object(dispatcher_module, "persist_agent_message", side_effect=_persist),
+ ):
+ asyncio.run(
+ dispatcher.emit_agent_message(
+ suppressed,
+ "notify",
+ "local background failure",
+ output=output,
+ )
+ )
+ asyncio.run(
+ dispatcher.emit_agent_message(
+ visible,
+ "notify",
+ "visible durable fallback",
+ output=output,
+ delivery=evidence,
+ )
+ )
+
+ assert len(controller.im_client.sent) == 1
+ assert evidence.delivered is True
+ assert len(persisted) == 1, "local history preserves the stable output identity"
+ assert persisted_versions[0]["metadata"]["delivery_suppressed"] is True
+ assert "delivery_suppressed" not in persisted_versions[1]["metadata"]
+
+
+def test_visible_send_promotes_the_stable_suppressed_history_row(tmp_path: Path) -> None:
+ """HFR-445 — promotion keeps identity and adopts the visible target Session."""
+
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ sqlite, _requests = _store(tmp_path)
+ _callback_session(sqlite)
+ now = "2026-07-27T00:00:00+00:00"
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses-suppressed-source",
+ scope_id=None,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="suppressed-source",
+ native_session_id="native-suppressed-source",
+ status="active",
+ visibility="background",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ local = messages_service.append(
+ conn,
+ scope_id=None,
+ session_id="ses-suppressed-source",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="notify",
+ text="local history",
+ metadata={"delivery_suppressed": True, "run_id": "run-promote"},
+ native_message_id="agent-output:codex:run-promote:failure",
+ )
+ promoted = messages_service.promote_suppressed_native_message(
+ conn,
+ platform="avibe",
+ scope_id=None,
+ session_id="ses-callback-target",
+ native_message_id="agent-output:codex:run-promote:failure",
+ message_type="notify",
+ text="visible fallback",
+ metadata={"run_id": "run-promote"},
+ )
+
+ assert promoted is not None
+ assert promoted["id"] == local["id"]
+ assert promoted["session_id"] == "ses-callback-target"
+ assert promoted["text"] == "visible fallback"
+ assert promoted["metadata"] == {"run_id": "run-promote"}
+
+
+def test_hfr_446_promoted_receipt_uses_visible_delivery_order(tmp_path: Path) -> None:
+ """Promotion orders the stable row by its visible send, not hidden creation."""
+
+ from storage import messages_service
+ from storage.models import agent_sessions
+
+ sqlite, _requests = _store(tmp_path)
+ _callback_session(sqlite)
+ now = "2026-07-27T00:00:00+00:00"
+ instants = iter(
+ [
+ "2026-07-27T00:00:01.000000Z",
+ "2026-07-27T00:00:02.000000Z",
+ "2026-07-27T00:00:03.000000Z",
+ ]
+ )
+ with sqlite.engine.begin() as conn, pytest.MonkeyPatch.context() as patch:
+ patch.setattr(messages_service, "_utc_now_iso", lambda: next(instants))
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses-order-source",
+ scope_id=None,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="order-source",
+ native_session_id="native-order-source",
+ status="active",
+ visibility="background",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ hidden = messages_service.append(
+ conn,
+ scope_id=None,
+ session_id="ses-order-source",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="notify",
+ text="hidden failure",
+ metadata={"delivery_suppressed": True, "run_id": "run-order"},
+ native_message_id="agent-output:codex:run-order:failure",
+ )
+ newer = messages_service.append(
+ conn,
+ scope_id=None,
+ session_id="ses-callback-target",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="notify",
+ text="already visible",
+ )
+ promoted = messages_service.promote_suppressed_native_message(
+ conn,
+ platform="avibe",
+ scope_id=None,
+ session_id="ses-callback-target",
+ native_message_id="agent-output:codex:run-order:failure",
+ message_type="notify",
+ text="visible failure",
+ metadata={"run_id": "run-order"},
+ )
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id="ses-callback-target",
+ types={"notify"},
+ tail=True,
+ )["messages"]
+
+ assert promoted is not None
+ assert promoted["id"] == hidden["id"]
+ assert promoted["delivered_at"] == "2026-07-27T00:00:03.000000Z"
+ assert [message["id"] for message in transcript] == [newer["id"], hidden["id"]]
+
+
+def test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung() -> None:
+ """HFR-075 — the dedup receipt has to satisfy the STRICTEST ack source there is.
+
+ The receipt above is the general claim; this is the one consumer for which it is
+ load-bearing rather than convenient. A workbench rung may acknowledge on a
+ durable persisted receipt and on nothing else (``LADDER_ACK_SOURCES``), so if the
+ duplicate short-circuit reported its found row as anything weaker than
+ ``receipt`` — a bare ``delivered_id``, say — then the exact case the idempotency
+ key exists for would be unserviceable on avibe: a crash between persisting the
+ message and acknowledging the notice would find the row, decline to re-send,
+ report nothing the policy accepts, and then re-send forever on other rungs or
+ dead-letter a notice the user demonstrably already has.
+
+ Driven through the real dispatcher against an avibe context, then handed to the
+ real predicate, because the claim spans the two modules: what the short-circuit
+ fills in, and what the ladder is willing to ack on.
+ """
+
+ from unittest.mock import patch
+
+ import core.message_dispatcher as dispatcher_module
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, DeliveryEvidence
+ from core.message_output import MessageOutput
+ from core.scheduled_tasks import (
+ ACK_SOURCE_PERSISTED_RECEIPT,
+ ScheduledTaskService,
+ failure_notice_ack_source,
+ parse_scope_id,
+ )
+ from modules.im import MessageContext
+
+ from tests.test_message_dispatcher_scheduled import _StubController
+
+ controller = _StubController()
+ dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="proj-notice",
+ platform="avibe",
+ platform_specific={
+ "platform": "avibe",
+ "agent_session_id": "sesDup",
+ "task_trigger_kind": "scheduled",
+ "task_execution_id": "run-dup",
+ },
+ )
+ evidence = DeliveryEvidence()
+
+ with patch.object(dispatcher_module, "agent_message_exists", return_value=True):
+ returned = asyncio.run(
+ dispatcher.emit_agent_message(
+ context,
+ "notify",
+ "your task failed",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="backend-failure:failure:run-dup",
+ ),
+ delivery=evidence,
+ )
+ )
+
+ assert returned and "backend-failure:failure:run-dup" in returned
+ assert controller.im_client.sent == [], "the row already exists; nothing may be re-sent"
+
+ target = parse_scope_id("avibe::project::proj-notice")
+ assert failure_notice_ack_source(target) == ACK_SOURCE_PERSISTED_RECEIPT, (
+ "the premise: this target class accepts nothing but a receipt"
+ )
+ assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
+ assert ScheduledTaskService._rung_acknowledges(target, evidence) is True, (
+ "a found row must acknowledge a workbench rung, or a crash-then-retry there "
+ "can never settle"
+ )
+ # And the rejection annotation stays off a rung that was accepted: an ack that
+ # also carried a "no persisted receipt" error would report a lie on the notice.
+ assert evidence.error is None
+
+
+def test_a_raising_delivery_consumes_an_attempt_instead_of_retrying_forever(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-076 — an exception must not escape before ``attempts`` is persisted.
+
+ ``_deliver_one_failure_notice`` computed the attempt number, then awaited
+ delivery, then wrote the result. An exception from any ladder rung escaped
+ between the second and third step, so nothing was persisted and the next 2 s
+ tick recomputed the SAME attempt number and raised again — an unbounded retry
+ loop, which is precisely what the backoff exists to prevent.
+
+ The live case is auth recovery (see the bypass test below), but the bound has
+ to hold for ANY raising rung, so this test raises directly.
+ """
+
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-raise", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ run = requests.enqueue_task_run("task-raise")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-raise")
async def _raising_emit(controller, context, backend, diagnostic, **kwargs):
raise RuntimeError("auth prompt exploded")
@@ -5793,7 +6426,13 @@ def _callback_session(
)
-def _persist_callback_result(sqlite_store, run_id: str, *, text: str) -> None:
+def _persist_callback_result(
+ sqlite_store,
+ run_id: str,
+ *,
+ text: str,
+ delivery_suppressed: bool = False,
+) -> None:
"""Materialize the durable message receipt that a callback success requires."""
from storage import messages_service
@@ -5808,7 +6447,10 @@ def _persist_callback_result(sqlite_store, run_id: str, *, text: str) -> None:
source="agent",
message_type="result",
text=text,
- metadata={"run_id": run_id},
+ metadata={
+ "run_id": run_id,
+ **({"delivery_suppressed": True} if delivery_suppressed else {}),
+ },
)
@@ -6207,6 +6849,43 @@ def test_owed_notice_takes_over_when_callback_receipt_is_in_a_hidden_session(
assert sqlite.owed_failure_notice("run-cb-hidden")["state"] == "sent"
+def test_suppressed_callback_history_is_not_visible_delivery_evidence(
+ tmp_path: Path,
+) -> None:
+ """A foreground Session does not make a suppress_delivery row visible."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb-suppressed", deliver_key="slack::channel::C1")
+ _callback_session(sqlite, visibility="foreground")
+ _callback_run(sqlite, "run-cb-suppressed", "task-cb-suppressed", status="pending")
+ callback = requests.enqueue_agent_run(
+ message="persist without outward delivery",
+ source_kind="callback",
+ parent_run_id="run-cb-suppressed",
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status(
+ "run-cb-suppressed",
+ status="sent",
+ callback_run_id=callback.id,
+ )
+ assert requests.claim(callback.id) is not None
+ sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="local callback history",
+ terminal_status="succeeded",
+ )
+ _persist_callback_result(
+ sqlite,
+ callback.id,
+ text="local callback history",
+ delivery_suppressed=True,
+ )
+
+ assert sqlite.run_callback_state("run-cb-suppressed") == "failed"
+
+
def test_skip_reason_writer_cannot_erase_a_terminal_notice_from_its_write_gap(
tmp_path: Path,
) -> None:
@@ -6547,188 +7226,1036 @@ def test_the_drain_preserves_an_authoritative_interruption_identity(tmp_path: Pa
controller, _dispatcher, touched = _live_turn_dispatcher()
sqlite, requests = _store(tmp_path)
- _task(sqlite, "task-interrupt-drain", deliver_key="slack::channel::C123")
- run = requests.enqueue_task_run("task-interrupt-drain")
- requests.claim(run.id)
- assert "restarted" in RUN_INTERRUPTION_REASONS
- sqlite.settle_run_terminal(
+ _task(sqlite, "task-interrupt-drain", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run("task-interrupt-drain")
+ requests.claim(run.id)
+ assert "restarted" in RUN_INTERRUPTION_REASONS
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="interrupted by a restart",
+ metadata={"interrupt_reason": "restarted"},
+ )
+
+ expected_failure_id = f"interrupt:{run.id}:restarted"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["failure_id"] == expected_failure_id
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ emissions = _spy_emissions(controller)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
+ visible = [item for item in emissions if item["type"] == "notify"]
+ assert len(visible) == 1
+ assert visible[0]["output"].idempotency_key == f"backend-failure:{expected_failure_id}", (
+ "the drain's interruption identity collapsed into the ordinary failure's"
+ )
+
+ # And on the durable row, which is what the dedup lookup and the D1 notice's
+ # survival actually depend on.
+ rows = _persisted_messages()
+ assert len(rows) == 1
+ assert rows[0]["native_message_id"].endswith(f"backend-failure:{expected_failure_id}")
+ assert f'"failure_id": "{expected_failure_id}"' in rows[0]["metadata_json"]
+ assert touched == []
+
+
+def test_a_suppressed_lane_reason_never_takes_the_interruption_identity_or_copy(
+ tmp_path: Path,
+) -> None:
+ """HFR-092 — ``interrupt_reason`` presence is not the interruption lane.
+
+ ``interrupt_reason`` is the general marker for "terminalized by something other
+ than its own backend result", and most values it carries are ordinary per-fire
+ verdicts: ``no_terminal_result``, ``refused_concurrent_turn``,
+ ``transport_unavailable``, ``queue_hold_expired``. Those recur on every fire and
+ belong in the SUPPRESSED failure lane — which is exactly what
+ ``failure_notices.is_interruption`` says, by membership in
+ ``RUN_INTERRUPTION_REASONS``.
+
+ Two other places asked the question by PRESENCE instead:
+
+ * the stamp (``_owed_failure_notice_for_transition``) minted
+ ``interrupt:{run}:{reason}`` for any non-empty reason, and
+ * the copy (``_failure_notice_body``) rendered the "was interrupted, nothing is
+ wrong with the definition itself" headline for any non-empty reason.
+
+ Both are wrong for the commonest failures, and the identity half is now
+ load-bearing: the drain's ``failure_id`` is AUTHORITATIVE (HFR-091), so an id
+ the live path never used is an id the dedup cannot match — one duplicate
+ notification per suppressed-lane failure. The copy half tells the user their
+ definition is fine when it is the definition that is broken.
+ """
+
+ from types import SimpleNamespace
+
+ from core import failure_notices
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-suppressed", name="daily report", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ run = requests.enqueue_task_run("task-suppressed")
+ requests.claim(run.id)
+ assert "no_terminal_result" not in RUN_INTERRUPTION_REASONS
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="the turn ended without dispatching an agent",
+ metadata={"interrupt_reason": "no_terminal_result"},
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["interrupt_reason"] == "no_terminal_result", (
+ "the reason itself is still recorded — it is a copy selector, not a lane"
+ )
+ # The lane, from the one predicate that decides it.
+ assert failure_notices.is_interruption(notice) is False
+ assert notice["failure_id"] == run.id, (
+ "a suppressed-lane failure must carry the identity the live path uses, or the "
+ "authoritative replay duplicates a notification already delivered"
+ )
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = lambda key, **kwargs: key
+
+ body = service._failure_notice_body(sqlite.get_run(run.id), notice)
+ assert "harness.notice.failed" in body
+ assert "harness.notice.interrupted" not in body, (
+ "a recurring per-fire verdict must not be reported as an out-of-band interruption"
+ )
+
+
+def test_the_drain_and_the_live_path_agree_for_a_suppressed_lane_reason(
+ tmp_path: Path,
+) -> None:
+ """HFR-093 — live delivery is primary and the durable drain remains a fallback."""
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-suppressed-dedup", deliver_key="slack::channel::C123")
+ runs = []
+ for index in range(2):
+ run = requests.enqueue_task_run("task-suppressed-dedup")
+ requests.claim(run.id)
+ sqlite.record_run_output(
+ run.id,
+ output_id="terminal",
+ text="",
+ terminal_status="failed",
+ error="backend failed",
+ provenance={
+ "turn_id": f"turn-{index}",
+ "turn_failure_notification": {
+ "failure_id": f"turn:turn-{index}",
+ "delivered": True,
+ "ack_evidence": "receipt",
+ "fallback_run_id": run.id,
+ },
+ },
+ )
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+ runs.append(run)
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert [sqlite.owed_failure_notice(run.id)["state"] for run in runs] == [
+ "skipped",
+ "skipped",
+ ]
+ assert controller.im_client.sent == [], "the fallback drain repeated a live Turn notification"
+
+
+def test_legacy_harness_delivery_evidence_suppresses_the_durable_fallback(
+ tmp_path: Path,
+) -> None:
+ """A pre-turn-token Harness receipt remains authoritative delivery evidence."""
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-legacy-delivery", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run("watch-legacy-delivery")
+ assert requests.claim(run.id) is not None
+ sqlite.record_run_output(
+ run.id,
+ output_id="terminal",
+ text="",
+ terminal_status="failed",
+ error="backend failed",
+ provenance={
+ "turn_failure_notification": {
+ "failure_id": run.id,
+ "delivered": True,
+ "ack_evidence": "delivery_only",
+ }
+ },
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["turn_id"] is None
+ assert notice["turn_notification_delivered"] is True
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice(run.id)["state"] == "skipped"
+ assert controller.im_client.sent == []
+
+
+def _settle_linked_turn_failures(sqlite, runs, *, delivered: bool) -> None:
+ fallback_run_id = min(run.id for run in runs)
+ for run in runs:
+ sqlite.record_run_output(
+ run.id,
+ output_id="terminal",
+ text="",
+ terminal_status="failed",
+ error="stream disconnected",
+ provenance={
+ "turn_id": "turn-shared-failure",
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-shared-failure",
+ "delivered": delivered,
+ "ack_evidence": "receipt" if delivered else None,
+ "fallback_run_id": fallback_run_id,
+ },
+ },
+ )
+
+
+def test_hfr_437_visible_turn_failure_suppresses_all_linked_run_notices(
+ tmp_path: Path,
+) -> None:
+ """One acknowledged backend error is enough, regardless of Run provenance."""
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-source-a", deliver_key="slack::channel::C123")
+ _task(sqlite, "watch-source-b", deliver_key="slack::channel::C123")
+ runs = [requests.enqueue_task_run(definition) for definition in ("watch-source-a", "watch-source-b")]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ _settle_linked_turn_failures(sqlite, runs, delivered=True)
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert controller.im_client.sent == []
+ assert {sqlite.owed_failure_notice(run.id)["state"] for run in runs} == {"skipped"}
+ assert {sqlite.get_run(run.id)["status"] for run in runs} == {"failed"}
+
+
+def test_hfr_438_missing_turn_notification_delivers_one_fallback(tmp_path: Path) -> None:
+ """A lost primary elects one Run fallback, not one fallback per definition."""
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-source-a", deliver_key="slack::channel::C123")
+ _task(sqlite, "watch-source-b", deliver_key="slack::channel::C123")
+ runs = [requests.enqueue_task_run(definition) for definition in ("watch-source-a", "watch-source-b")]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ _settle_linked_turn_failures(sqlite, runs, delivered=False)
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(controller.im_client.sent) == 1
+ notices = {run.id: sqlite.owed_failure_notice(run.id) for run in runs}
+ assert notices[min(notices)]["state"] == "sent"
+ assert {notice["state"] for run_id, notice in notices.items() if run_id != min(notices)} == {
+ "skipped"
+ }
+
+
+def test_hfr_440_one_sibling_callback_suppresses_the_whole_turn_fallback(
+ tmp_path: Path,
+) -> None:
+ """A callback reports the shared Turn result, not only its parent Run."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-callback-a", deliver_key="slack::channel::C123")
+ _task(sqlite, "watch-callback-b", deliver_key="slack::channel::C123")
+ _callback_session(sqlite)
+ owner_id = "run-turn-owner"
+ callback_parent_id = "run-turn-callback"
+ notice = {
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "turn:turn-with-callback",
+ "turn_id": "turn-with-callback",
+ "turn_fallback_run_id": owner_id,
+ "turn_participant_run_ids": [owner_id, callback_parent_id],
+ }
+ _pending_failure(
+ sqlite,
+ owner_id,
+ "watch-callback-a",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice=notice,
+ )
+ _callback_run(
+ sqlite,
+ callback_parent_id,
+ "watch-callback-b",
+ status="pending",
+ )
+ sqlite.update_owed_failure_notice(
+ callback_parent_id,
+ failure_id="turn:turn-with-callback",
+ turn_id="turn-with-callback",
+ turn_fallback_run_id=owner_id,
+ turn_participant_run_ids=[owner_id, callback_parent_id],
+ )
+ callback = requests.enqueue_agent_run(
+ message="deliver the shared Turn result",
+ source_kind="callback",
+ parent_run_id=callback_parent_id,
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status(
+ callback_parent_id,
+ status="sent",
+ callback_run_id=callback.id,
+ )
+ assert requests.claim(callback.id) is not None
+ sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="shared Turn callback delivered",
+ terminal_status="succeeded",
+ )
+ _persist_callback_result(sqlite, callback.id, text="shared Turn callback delivered")
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import core.scheduled_tasks as scheduled_tasks
+
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == []
+ for run_id in (owner_id, callback_parent_id):
+ stored = sqlite.owed_failure_notice(run_id)
+ assert stored["state"] == "skipped"
+ assert stored["skip_reason"] == "delivered_by_callback"
+
+
+def test_hfr_443_deferred_sibling_callback_blocks_the_turn_fallback(
+ tmp_path: Path,
+) -> None:
+ """A deferred participant remains part of the Turn callback snapshot."""
+
+ from sqlalchemy import update as sa_update
+
+ import core.scheduled_tasks as scheduled_tasks
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-immediate-notice", deliver_key="slack::channel::C123")
+ _task(sqlite, "watch-deferred-callback", deliver_key="slack::channel::C123")
+ _callback_session(sqlite)
+ immediate = requests.enqueue_task_run("watch-immediate-notice")
+ deferred = requests.enqueue_task_run("watch-deferred-callback")
+ for run in (immediate, deferred):
+ assert requests.claim(run.id) is not None
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == deferred.id)
+ .values(
+ callback_session_id="ses-callback-target",
+ callback_status="pending",
+ )
+ )
+
+ turn_id = "turn-deferred-callback"
+ sqlite.record_turn_run_outputs(
+ [immediate.id, deferred.id],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": deferred.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[deferred.id],
+ )
+
+ assert sqlite.get_run(deferred.id)["status"] == "running"
+ assert (
+ sqlite.turn_callback_state(
+ turn_id,
+ participant_run_ids=[immediate.id, deferred.id],
+ )
+ == "pending"
+ )
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == []
+ assert sqlite.owed_failure_notice(immediate.id)["state"] == "pending"
+
+
+def test_hfr_448_cancel_requested_callback_does_not_block_turn_fallback(
+ tmp_path: Path,
+) -> None:
+ """A stopped deferred participant no longer owns callback membership."""
+
+ from sqlalchemy import update as sa_update
+
+ import core.scheduled_tasks as scheduled_tasks
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-cancel-callback-owner", deliver_key="slack::channel::C123")
+ _task(sqlite, "watch-cancel-callback-deferred", deliver_key="slack::channel::C123")
+ _callback_session(sqlite)
+ immediate = requests.enqueue_task_run("watch-cancel-callback-owner")
+ deferred = requests.enqueue_task_run("watch-cancel-callback-deferred")
+ for run in (immediate, deferred):
+ assert requests.claim(run.id) is not None
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == deferred.id)
+ .values(
+ callback_session_id="ses-callback-target",
+ callback_status="pending",
+ )
+ )
+
+ turn_id = "turn-cancel-requested-callback"
+ sqlite.record_turn_run_outputs(
+ [immediate.id, deferred.id],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": immediate.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[deferred.id],
+ )
+
+ assert sqlite.cancel_run(deferred.id)
+ assert sqlite.get_run(deferred.id)["cancel_requested"] is True
+ assert (
+ sqlite.turn_callback_state(
+ turn_id,
+ participant_run_ids=[immediate.id, deferred.id],
+ )
+ is None
+ )
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == [f"turn:{turn_id}"]
+ assert sqlite.owed_failure_notice(immediate.id)["state"] == "sent"
+
+
+def test_hfr_449_canceled_parent_keeps_armed_callback_evidence(
+ tmp_path: Path,
+) -> None:
+ """Cancellation removes unarmed parents, not callback work already accepted."""
+
+ sqlite, requests = _store(tmp_path)
+ _callback_session(sqlite)
+
+ def _parent_with_callback(turn_id: str, *, delivered: bool) -> tuple[Any, Any]:
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ definition_id = f"watch-{turn_id}"
+ _task(sqlite, definition_id)
+ parent = requests.enqueue_task_run(definition_id)
+ assert requests.claim(parent.id) is not None
+ sqlite.record_turn_run_outputs(
+ [parent.id],
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": parent.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ )
+ callback = requests.enqueue_agent_run(
+ message="deliver the Turn result",
+ source_kind="callback",
+ parent_run_id=parent.id,
+ session_id="ses-callback-target",
+ )
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == parent.id)
+ .values(callback_session_id="ses-callback-target")
+ )
+ sqlite.update_callback_status(
+ parent.id,
+ status="sent",
+ callback_run_id=callback.id,
+ )
+ if delivered:
+ assert requests.claim(callback.id) is not None
+ sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="callback delivered",
+ terminal_status="succeeded",
+ )
+ _persist_callback_result(sqlite, callback.id, text="callback delivered")
+ assert sqlite.cancel_run(parent.id)
+ return parent, callback
+
+ pending_parent, _pending_callback = _parent_with_callback(
+ "turn-canceled-pending-callback", delivered=False
+ )
+ delivered_parent, _delivered_callback = _parent_with_callback(
+ "turn-canceled-delivered-callback", delivered=True
+ )
+
+ assert (
+ sqlite.turn_callback_state(
+ "turn-canceled-pending-callback",
+ participant_run_ids=[pending_parent.id],
+ )
+ == "pending"
+ )
+ assert (
+ sqlite.turn_callback_state(
+ "turn-canceled-delivered-callback",
+ participant_run_ids=[delivered_parent.id],
+ )
+ == "sent"
+ )
+
+
+def test_hfr_450_terminal_replay_promotes_new_turn_delivery_evidence(
+ tmp_path: Path,
+) -> None:
+ """A same-Turn replay upgrades its notice without resetting drain progress."""
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "watch-delivery-replay")
+ run = requests.enqueue_task_run("watch-delivery-replay")
+ assert requests.claim(run.id) is not None
+ turn_id = "turn-delivery-replay"
+ provenance = {
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": run.id,
+ },
+ }
+ sqlite.record_turn_run_outputs(
+ [run.id],
+ output_id="terminal",
+ text="",
+ provenance=provenance,
+ terminal_status="failed",
+ error="stream disconnected",
+ )
+ sqlite.update_owed_failure_notice(run.id, attempts=2)
+
+ replay = sqlite.record_run_output(
run.id,
+ output_id="terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": True,
+ "ack_evidence": "delivery_only",
+ "fallback_run_id": run.id,
+ },
+ },
terminal_status="failed",
- error="interrupted by a restart",
- metadata={"interrupt_reason": "restarted"},
+ error="stream disconnected",
)
- expected_failure_id = f"interrupt:{run.id}:restarted"
notice = sqlite.owed_failure_notice(run.id)
- assert notice["failure_id"] == expected_failure_id
-
- service = _drain_service(tmp_path, controller, sqlite, requests)
- emissions = _spy_emissions(controller)
-
- asyncio.run(service._drain_failure_notices())
-
- assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
- visible = [item for item in emissions if item["type"] == "notify"]
- assert len(visible) == 1
- assert visible[0]["output"].idempotency_key == f"backend-failure:{expected_failure_id}", (
- "the drain's interruption identity collapsed into the ordinary failure's"
- )
+ assert replay["recorded"] is False
+ assert replay["terminal_transition"] is False
+ assert replay["delivery_evidence_merged"] is True
+ assert notice["attempts"] == 2
+ assert notice["turn_notification_delivered"] is True
+ assert notice["turn_notification_ack_evidence"] == "delivery_only"
- # And on the durable row, which is what the dedup lookup and the D1 notice's
- # survival actually depend on.
- rows = _persisted_messages()
- assert len(rows) == 1
- assert rows[0]["native_message_id"].endswith(f"backend-failure:{expected_failure_id}")
- assert f'"failure_id": "{expected_failure_id}"' in rows[0]["metadata_json"]
- assert touched == []
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+ assert delivered == []
+ assert sqlite.owed_failure_notice(run.id)["state"] == "skipped"
-def test_a_suppressed_lane_reason_never_takes_the_interruption_identity_or_copy(
+def test_hfr_451_turn_callback_lookup_uses_bounded_ownership(
tmp_path: Path,
) -> None:
- """HFR-092 — ``interrupt_reason`` presence is not the interruption lane.
+ """Turn callback reads use Run ids and indexed Delivery ownership, never JSON scans."""
- ``interrupt_reason`` is the general marker for "terminalized by something other
- than its own backend result", and most values it carries are ordinary per-fire
- verdicts: ``no_terminal_result``, ``refused_concurrent_turn``,
- ``transport_unavailable``, ``queue_hold_expired``. Those recur on every fire and
- belong in the SUPPRESSED failure lane — which is exactly what
- ``failure_notices.is_interruption`` says, by membership in
- ``RUN_INTERRUPTION_REASONS``.
+ sqlite, _requests = _store(tmp_path)
+ _pending_failure(
+ sqlite,
+ "run-bounded-callback",
+ "watch-bounded-callback",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "turn:turn-bounded-callback",
+ "turn_id": "turn-bounded-callback",
+ "turn_fallback_run_id": "run-bounded-callback",
+ "turn_participant_run_ids": ["run-bounded-callback"],
+ },
+ )
+ statements: list[tuple[str, Any]] = []
- Two other places asked the question by PRESENCE instead:
+ def _capture_statement(conn, cursor, statement, parameters, context, executemany):
+ if "callback_parent" in statement:
+ statements.append((statement, parameters))
- * the stamp (``_owed_failure_notice_for_transition``) minted
- ``interrupt:{run}:{reason}`` for any non-empty reason, and
- * the copy (``_failure_notice_body``) rendered the "was interrupted, nothing is
- wrong with the definition itself" headline for any non-empty reason.
+ event.listen(sqlite.engine, "before_cursor_execute", _capture_statement)
+ try:
+ sqlite.turn_callback_state(
+ "turn-bounded-callback",
+ participant_run_ids=["run-bounded-callback"],
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _capture_statement)
- Both are wrong for the commonest failures, and the identity half is now
- load-bearing: the drain's ``failure_id`` is AUTHORITATIVE (HFR-091), so an id
- the live path never used is an id the dedup cannot match — one duplicate
- notification per suppressed-lane failure. The copy half tells the user their
- definition is fine when it is the definition that is broken.
- """
+ assert len(statements) == 1
+ statement, parameters = statements[0]
+ normalized_statement = statement.upper()
+ assert "CALLBACK_PARENT.METADATA_JSON" not in normalized_statement
+ assert "CALLBACK_PARENT.RESULT_PAYLOAD_JSON" not in normalized_statement
+ assert "MESSAGE_DELIVERIES.TURN_ID" in normalized_statement
+ assert "CALLBACK_PARENT.ID IN" in normalized_statement
+ with sqlite.engine.connect() as conn:
+ plan = conn.exec_driver_sql(
+ f"EXPLAIN QUERY PLAN {statement}",
+ parameters,
+ ).all()
+ plan_text = " ".join(str(row[-1]) for row in plan)
+ assert "message_deliveries_turn" in plan_text
+ assert "sqlite_autoindex_agent_runs_1" in plan_text
- from types import SimpleNamespace
- from core import failure_notices
- from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+def test_hfr_452_callback_children_cannot_own_a_turn_fallback(
+ tmp_path: Path,
+) -> None:
+ """Owner election applies every suppression used by the notice writer."""
sqlite, requests = _store(tmp_path)
- _task(sqlite, "task-suppressed", name="daily report", deliver_key="slack::channel::C1")
- store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
- store._sqlite = sqlite
- store.load()
+ parent = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-callback-parent",
+ request_type="agent_run",
+ message="original callback parent",
+ )
+ )
+ assert requests.claim(parent.id) is not None
+ sqlite.record_run_output(
+ parent.id,
+ output_id="parent-terminal",
+ text="",
+ terminal_status="failed",
+ error="parent failed",
+ )
+ assert sqlite.owed_failure_notice(parent.id) is not None
- run = requests.enqueue_task_run("task-suppressed")
- requests.claim(run.id)
- assert "no_terminal_result" not in RUN_INTERRUPTION_REASONS
- sqlite.settle_run_terminal(
- run.id,
+ callback_child = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-a-callback-child",
+ request_type="agent_run",
+ message="callback child",
+ source_kind="callback",
+ parent_run_id=parent.id,
+ )
+ )
+ sibling = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-b-fallback-owner",
+ request_type="agent_run",
+ message="ordinary sibling",
+ )
+ )
+ assert requests.claim(callback_child.id) is not None
+ assert requests.claim(sibling.id) is not None
+ turn_id = "turn-callback-child-owner"
+
+ sqlite.record_turn_run_outputs(
+ [callback_child.id, sibling.id],
+ output_id="turn-terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": callback_child.id,
+ },
+ },
terminal_status="failed",
- error="the turn ended without dispatching an agent",
- metadata={"interrupt_reason": "no_terminal_result"},
+ error="stream disconnected",
)
- notice = sqlite.owed_failure_notice(run.id)
- assert notice["interrupt_reason"] == "no_terminal_result", (
- "the reason itself is still recorded — it is a copy selector, not a lane"
+ assert sqlite.owed_failure_notice(callback_child.id) is None
+ assert (
+ sqlite.owed_failure_notice(sibling.id)["turn_fallback_run_id"]
+ == sibling.id
)
- # The lane, from the one predicate that decides it.
- assert failure_notices.is_interruption(notice) is False
- assert notice["failure_id"] == run.id, (
- "a suppressed-lane failure must carry the identity the live path uses, or the "
- "authoritative replay duplicates a notification already delivered"
+
+
+def test_hfr_453_callback_enqueue_arms_the_parent_in_one_transaction(
+ tmp_path: Path,
+) -> None:
+ """A durable callback child is never visible without its parent marker."""
+
+ sqlite, requests = _store(tmp_path)
+ parent = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-atomic-callback-parent",
+ request_type="agent_run",
+ message="parent",
+ callback_session_id="ses-callback-target",
+ callback_status="pending",
+ )
)
+ statements: list[str] = []
+ commits: list[int] = []
- service = ScheduledTaskService.__new__(ScheduledTaskService)
- service.store = store
- service.request_store = requests
- service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
- service._t = lambda key, **kwargs: key
+ def _capture_statement(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement:
+ statements.append(statement.upper())
- body = service._failure_notice_body(sqlite.get_run(run.id), notice)
- assert "harness.notice.failed" in body
- assert "harness.notice.interrupted" not in body, (
- "a recurring per-fire verdict must not be reported as an out-of-band interruption"
+ def _capture_commit(conn):
+ commits.append(1)
+
+ event.listen(sqlite.engine, "before_cursor_execute", _capture_statement)
+ event.listen(sqlite.engine, "commit", _capture_commit)
+ try:
+ callback = requests.enqueue_agent_run(
+ message="deliver callback",
+ source_kind="callback",
+ source_actor="run-atomic-callback-parent:terminal:failed",
+ parent_run_id=parent.id,
+ callback_parent_to_arm=parent.id,
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _capture_statement)
+ event.remove(sqlite.engine, "commit", _capture_commit)
+
+ stored_parent = sqlite.get_run(parent.id)
+ assert stored_parent["callback_status"] == "sent"
+ assert stored_parent["callback_run_id"] == callback.id
+ assert sqlite.get_run(callback.id)["parent_run_id"] == parent.id
+ assert commits == [1]
+ insert_position = next(
+ index
+ for index, statement in enumerate(statements)
+ if statement.startswith("INSERT INTO AGENT_RUNS")
)
+ parent_update_position = next(
+ index
+ for index, statement in enumerate(statements)
+ if statement.startswith("UPDATE AGENT_RUNS")
+ and "CALLBACK_RUN_ID" in statement
+ )
+ assert insert_position < parent_update_position
-def test_the_drain_and_the_live_path_agree_for_a_suppressed_lane_reason(
+def test_hfr_455_turn_owner_excludes_same_batch_parent_suppression(
tmp_path: Path,
) -> None:
- """HFR-093 — recurring live failures enter the durable policy before delivery.
+ """A child cannot own when its earlier parent acquires a notice in the batch."""
- Two consecutive executions fail for the same definition. Each backend reports
- its failure live, but that path owns settlement only; the owed-notice drain owns
- visible delivery and can therefore send the first failure while suppressing the
- rest of the streak. Delivering before settlement would produce two rows before
- the drain had any opportunity to classify the streak.
- """
+ sqlite, requests = _store(tmp_path)
+ parent = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-b-callback-parent",
+ request_type="agent_run",
+ message="parent",
+ )
+ )
+ callback_child = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-a-callback-child",
+ request_type="agent_run",
+ message="callback child",
+ source_kind="callback",
+ parent_run_id=parent.id,
+ )
+ )
+ assert requests.claim(parent.id) is not None
+ assert requests.claim(callback_child.id) is not None
+ turn_id = "turn-parent-before-callback-child"
+
+ sqlite.record_turn_run_outputs(
+ [parent.id, callback_child.id],
+ output_id="turn-terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": callback_child.id,
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
+ )
- from core.backend_failure import emit_backend_failure
- from core.scheduled_tasks import parse_session_key
+ parent_notice = sqlite.owed_failure_notice(parent.id)
+ assert parent_notice["turn_fallback_run_id"] == parent.id
+ assert sqlite.owed_failure_notice(callback_child.id) is None
- _migrated_state_db()
- controller, _dispatcher, _touched = _live_turn_dispatcher()
+
+def test_hfr_456_late_canceled_failed_parent_rejects_only_new_callbacks(
+ tmp_path: Path,
+) -> None:
+ """Late cancellation blocks new failure callbacks but preserves accepted evidence."""
sqlite, requests = _store(tmp_path)
- _task(sqlite, "task-suppressed-dedup", deliver_key="slack::channel::C123")
- runs = []
- for _index in range(2):
- run = requests.enqueue_task_run("task-suppressed-dedup")
- requests.claim(run.id)
- sqlite.settle_run_terminal(
- run.id,
+
+ def failed_parent(run_id: str) -> TaskExecutionRequest:
+ parent = requests.enqueue(
+ TaskExecutionRequest(
+ id=run_id,
+ request_type="agent_run",
+ message="parent",
+ callback_session_id="ses-callback-target",
+ callback_status="pending",
+ )
+ )
+ assert requests.claim(parent.id) is not None
+ sqlite.record_run_output(
+ parent.id,
+ output_id=f"{run_id}-terminal",
+ text="",
terminal_status="failed",
- error="backend failed",
+ error="parent failed",
)
- assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
- runs.append(run)
+ assert sqlite.cancel_run(parent.id)
+ return parent
- service = _drain_service(tmp_path, controller, sqlite, requests)
+ rejected_parent = failed_parent("run-canceled-callback-parent")
+ rejected_actor = f"{rejected_parent.id}:terminal:failed"
+ rejected = requests.enqueue_agent_run(
+ message="new callback",
+ source_kind="callback",
+ source_actor=rejected_actor,
+ parent_run_id=rejected_parent.id,
+ callback_parent_to_arm=rejected_parent.id,
+ )
+ assert rejected is None
+ assert (
+ requests.find_callback_run(
+ parent_run_id=rejected_parent.id,
+ source_actor=rejected_actor,
+ )
+ is None
+ )
- target = parse_session_key("slack::channel::C123")
- for run in runs:
- live_context = asyncio.run(
- service._build_context(
- target,
- delivery_target=target,
- execution_id=run.id,
- task_id="task-suppressed-dedup",
- trigger_kind="scheduled",
- )
+ armed_parent = failed_parent("run-armed-callback-parent")
+ armed_actor = f"{armed_parent.id}:terminal:failed"
+ existing = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-existing-callback-child",
+ request_type="agent_run",
+ message="accepted callback",
+ source_kind="callback",
+ source_actor=armed_actor,
+ parent_run_id=armed_parent.id,
)
- asyncio.run(
- emit_backend_failure(
- controller,
- live_context,
- "harness",
- "backend failed",
- display_text="the live notice",
- )
+ )
+ recovered = requests.enqueue_agent_run(
+ message="accepted callback",
+ source_kind="callback",
+ source_actor=armed_actor,
+ parent_run_id=armed_parent.id,
+ callback_parent_to_arm=armed_parent.id,
+ )
+ assert recovered is not None
+ assert recovered.id == existing.id
+ stored_parent = sqlite.get_run(armed_parent.id)
+ assert stored_parent["callback_status"] == "sent"
+ assert stored_parent["callback_run_id"] == existing.id
+
+
+def test_hfr_457_missing_turn_participant_does_not_rollback_valid_runs(
+ tmp_path: Path,
+) -> None:
+ """A stale attribution id is excluded before ownership and settlement."""
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-valid-turn-participant",
+ request_type="agent_run",
+ message="valid participant",
)
- live_rows = [
- row for row in _persisted_messages() if "backend-failure:" in (row["native_message_id"] or "")
- ]
- assert live_rows == [], (
- "Harness live emitters settle only; visible delivery belongs to the durable "
- f"notice policy: {live_rows}"
+ )
+ assert requests.claim(run.id) is not None
+ turn_id = "turn-with-stale-participant"
+
+ results = sqlite.record_turn_run_outputs(
+ ["run-missing-turn-participant", run.id],
+ output_id="turn-terminal",
+ text="",
+ provenance={
+ "turn_id": turn_id,
+ "turn_failure_notification": {
+ "failure_id": f"turn:{turn_id}",
+ "delivered": False,
+ "fallback_run_id": "run-missing-turn-participant",
+ },
+ },
+ terminal_status="failed",
+ error="stream disconnected",
)
- asyncio.run(service._drain_failure_notices())
+ assert list(results) == [run.id]
+ assert sqlite.get_run(run.id)["status"] == "failed"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["turn_fallback_run_id"] == run.id
+ assert notice["turn_participant_run_ids"] == [run.id]
- rows = [
- row for row in _persisted_messages() if "backend-failure:" in (row["native_message_id"] or "")
- ]
- assert len(rows) == 1, (
- "one recurring failure streak must produce one durable notification, got "
- f"{[row['native_message_id'] for row in rows]}"
+
+def test_hfr_458_steered_callback_uses_its_shared_turn_output_receipt(
+ tmp_path: Path,
+) -> None:
+ """A callback need not be the primary Run named by its persisted result."""
+
+ from storage import messages_service
+
+ sqlite, requests = _store(tmp_path)
+ _callback_session(sqlite)
+ parent = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-shared-receipt-parent",
+ request_type="agent_run",
+ message="parent",
+ callback_session_id="ses-callback-target",
+ )
+ )
+ callback = requests.enqueue(
+ TaskExecutionRequest(
+ id="run-shared-receipt-callback",
+ request_type="agent_run",
+ message="callback",
+ source_kind="callback",
+ parent_run_id=parent.id,
+ session_id="ses-callback-target",
+ )
+ )
+ for run in (parent, callback):
+ assert requests.claim(run.id) is not None
+ sqlite.update_callback_status(
+ parent.id,
+ status="sent",
+ callback_run_id=callback.id,
+ )
+ turn_id = "turn-steered-callback-receipt"
+ output_id = "steered-terminal-output"
+ sqlite.record_turn_run_outputs(
+ [callback.id],
+ output_id=output_id,
+ text="callback delivered",
+ provenance={"turn_id": turn_id, "run_id": "run-primary-human-turn"},
+ terminal_status="succeeded",
+ )
+ with sqlite.engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id="ses-callback-target",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="callback delivered",
+ metadata={
+ "turn_id": turn_id,
+ "run_id": "run-primary-human-turn",
+ "output_id": output_id,
+ },
+ )
+
+ assert sqlite.run_callback_state(parent.id) == "sent"
+
+
[email protected]("turn_notification", [None, {}], ids=["absent", "empty"])
+def test_hfr_442_bare_turn_provenance_does_not_enter_the_fallback_lane(
+ tmp_path: Path,
+ turn_notification: dict[str, Any] | None,
+) -> None:
+ """A direct error result has a Turn id but no notification ownership contract."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-direct-error", deliver_key="slack::channel::C123")
+ runs = [requests.enqueue_task_run("task-direct-error") for _ in range(2)]
+ for run in runs:
+ assert requests.claim(run.id) is not None
+ provenance: dict[str, Any] = {"turn_id": "turn-direct-error"}
+ if turn_notification is not None:
+ provenance["turn_failure_notification"] = turn_notification
+ sqlite.record_turn_run_outputs(
+ [run.id for run in runs],
+ output_id="terminal",
+ text="question tool is disabled",
+ terminal_status="failed",
+ error="question tool is disabled",
+ provenance=provenance,
)
- assert rows[0]["native_message_id"].endswith(f"backend-failure:{runs[0].id}")
- assert sqlite.owed_failure_notice(runs[0].id)["state"] == "sent"
- assert sqlite.owed_failure_notice(runs[1].id)["state"] == "skipped"
+
+ notices = [sqlite.owed_failure_notice(run.id) for run in runs]
+ assert all(notice["turn_id"] is None for notice in notices)
+ assert all(notice["turn_fallback_run_id"] is None for notice in notices)
def test_the_index_migration_and_the_query_use_the_same_expressions(tmp_path: Path) -> None:
@@ -7626,8 +9153,8 @@ def test_brief_task_payload_carries_last_error(capsys) -> None:
assert entry["last_error"] == "unresolvable session binding"
-def test_a_watch_reports_health_on_the_same_terms_as_a_task(capsys) -> None:
- """HFR-090 — a watch whose hook fails nightly is as invisible as a task.
+def test_a_watch_reports_processing_health_separately_from_waiter_health(capsys) -> None:
+ """HFR-090 — a failed hook stays visible without blaming the waiter.
``_enrich_definitions`` computes health for both definition types, so the only
thing that decided whether it reached a surface was the projection allowlist.
@@ -7668,8 +9195,31 @@ def test_a_watch_reports_health_on_the_same_terms_as_a_task(capsys) -> None:
store.close()
entry = json.loads(capsys.readouterr().out)["definitions"][0]
- assert entry["health"] == "failing"
- assert entry["consecutive_failures"] == 1
+ assert entry["health"] == "unknown", "a never-run waiter has no success evidence"
+ assert entry["consecutive_failures"] == 0
+ assert entry["processing_health"] == "failing"
+ assert entry["processing_consecutive_failures"] == 1
+
+
+def test_hfr_444_first_in_flight_waiter_health_remains_unknown(tmp_path: Path) -> None:
+ """Starting a cycle is not evidence that its waiter succeeded."""
+
+ sqlite, _requests = _store(tmp_path)
+ _watch(
+ sqlite,
+ "watch-first-cycle",
+ last_started_at="2026-08-08T05:00:00+00:00",
+ last_finished_at=None,
+ last_exit_code=None,
+ last_error=None,
+ )
+
+ projected = sqlite.get_watch("watch-first-cycle")
+
+ assert projected is not None
+ assert projected["health"] == "unknown"
+ assert projected["consecutive_failures"] == 0
+ assert projected["recent_failures"] == 0
def test_storage_interruption_reasons_mirror_the_settlement_vocabulary() -> None:
@@ -9955,7 +11505,15 @@ def test_an_unmapped_interruption_reason_renders_a_localized_fallback(
)
-def _settled_run(sqlite, definition_id: str, run_id: str, *, status: str, at: str) -> None:
+def _settled_run(
+ sqlite,
+ definition_id: str,
+ run_id: str,
+ *,
+ status: str,
+ at: str,
+ metadata: dict | None = None,
+) -> None:
"""One already-settled run of *definition_id*, stamped at *at*."""
sqlite.enqueue_run(
@@ -9967,6 +11525,7 @@ def _settled_run(sqlite, definition_id: str, run_id: str, *, status: str, at: st
"error": "boom" if status == "failed" else None,
"created_at": at,
"completed_at": at,
+ "metadata": metadata or {},
}
)
@@ -10413,8 +11972,8 @@ def test_a_watch_that_outlives_its_delivery_target_dies_visibly(
The four steps, asserted in the order the failure happens:
(c) the terminal timestamps agree with each other and survive a fresh read;
- (a) the row reads FINISHED, never paused, and its health says failing on both the
- projection and the CLI payload a coding agent actually parses;
+ (a) the row reads FINISHED, never paused, its waiter stays healthy, and its event
+ processing says failing on both the projection and the CLI payload;
(b) the run settled ``failed`` naming the delivery failure, the notice carries the
structured class ``delivery_target_missing``, and the DEFINITION's
``last_error``/``last_exit_code`` still describe the healthy waiter — the
@@ -10522,15 +12081,22 @@ def test_a_watch_that_outlives_its_delivery_target_dies_visibly(
assert not (projected["enabled"] is False and projected.get("retired_at") in (None, "")), (
f"``enabled=0`` with no retirement marker is the ambiguous state: {projected}"
)
- assert projected["health"] == "failing", (
- f"a watch whose only delivery failed is not healthy: {projected}"
+ assert projected["health"] == "healthy", (
+ f"the waiter exited zero, so downstream delivery cannot poison it: {projected}"
+ )
+ assert projected["processing_health"] == "failing", (
+ f"the failed follow-up must remain visible on its own axis: {projected}"
)
# The CLI payload too, not only the store projection: a coding agent driving this
# runtime reads ``vibe watch show``, and #1060 was discovered by a human running
# ``vibe watch list`` for an unrelated reason. The two must agree.
assert cli.cmd_watch_show(watch.id) == 0
shown = json.loads(capsys.readouterr().out)["definition"]
- assert (shown["health"], shown["lifecycle_state"]) == ("failing", "finished"), (
+ assert (shown["health"], shown["processing_health"], shown["lifecycle_state"]) == (
+ "healthy",
+ "failing",
+ "finished",
+ ), (
f"the CLI payload must carry the same verdict as the projection: {shown}"
)
@@ -10603,8 +12169,11 @@ def test_a_watch_that_outlives_its_delivery_target_dies_visibly(
assert i18n_t("harness.notice.class.deliveryTargetMissing", "en") in body, (
f"and name the class, not only the raw error line: {body!r}"
)
- assert i18n_t("harness.notice.watchRetired", "en") in body, (
- f"a retired watch's copy has to say it finished: {body!r}"
+ assert i18n_t("harness.notice.watchProcessingFailed", "en").split("{")[0] in body, (
+ f"the fallback must identify event processing rather than waiter failure: {body!r}"
+ )
+ assert i18n_t("harness.notice.watchRetired", "en") not in body, (
+ f"normal one-shot retirement is unrelated to the processing failure: {body!r}"
)
assert i18n_t("harness.notice.watchPaused", "en").split("{")[0].strip() not in body, (
"and must NOT offer ``vibe watch resume`` for a watch that retired — that is "
@@ -10760,9 +12329,12 @@ def test_a_forever_watch_repeating_the_field_failure_notifies_once(
assert projected["lifecycle_state"] == "waiting", (
f"the watch is still armed, so it is not finished: {projected}"
)
- assert projected["health"] == "failing", (
- "…and still failing: a repeating delivery failure is exactly the history the "
- f"health badge exists to report: {projected}"
+ assert projected["health"] == "healthy", (
+ f"retry exit 75 is a healthy waiter outcome, not a failure: {projected}"
+ )
+ assert projected["processing_health"] == "failing", (
+ "the repeating delivery failure belongs to processing history instead: "
+ f"{projected}"
)
# ONE canonical notice for the streak, keyed to the FIRST failed run.
@@ -11081,11 +12653,17 @@ def test_a_disabled_watchs_notice_copy_distinguishes_retired_from_paused(
service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
retired_copy = i18n_t("harness.notice.watchRetired", language)
+ processing_copy = i18n_t("harness.notice.watchProcessingFailed", language).split("{")[0]
# The command, not the whole sentence: that is the part a user could act on, and
# the part that must not appear for a watch nobody paused.
resume_command = "vibe watch resume"
def _body(definition_id: str, **watch_fields) -> str:
+ from storage.background import (
+ WATCH_HOOK_OUTCOME_EVENT,
+ WATCH_HOOK_OUTCOME_METADATA_KEY,
+ )
+
_watch(sqlite, definition_id, enabled=False, **watch_fields)
_settled_run(
sqlite,
@@ -11093,6 +12671,7 @@ def test_a_disabled_watchs_notice_copy_distinguishes_retired_from_paused(
f"run-{definition_id}",
status="failed",
at="2026-07-27T03:00:00+00:00",
+ metadata={WATCH_HOOK_OUTCOME_METADATA_KEY: WATCH_HOOK_OUTCOME_EVENT},
)
return service._failure_notice_body(
sqlite.get_run(f"run-{definition_id}"),
@@ -11100,7 +12679,10 @@ def test_a_disabled_watchs_notice_copy_distinguishes_retired_from_paused(
)
retired = _body("watch-retired", retired_at="2026-07-27T03:00:00+00:00", mode="once")
- assert retired_copy in retired, f"a retired watch must say it finished: {retired!r}"
+ assert processing_copy in retired
+ assert retired_copy not in retired, (
+ f"normal one-shot retirement is unrelated to event processing failure: {retired!r}"
+ )
assert resume_command not in retired, (
"and must not offer to resume something that was never paused — the copy has to "
f"agree with the FINISHED lifecycle state: {retired!r}"
diff --git a/tests/test_harness_health_projection.py b/tests/test_harness_health_projection.py
index 6b9484cf5..add777965 100644
--- a/tests/test_harness_health_projection.py
+++ b/tests/test_harness_health_projection.py
@@ -40,6 +40,9 @@ PROJECTED_FIELDS = (
"health",
"consecutive_failures",
"recent_failures",
+ "processing_health",
+ "processing_consecutive_failures",
+ "processing_recent_failures",
"lifecycle_state",
"lifecycle_detail",
)
@@ -195,9 +198,18 @@ def test_task_and_watch_mutations_return_the_enriched_projection(capsys) -> None
assert show(definition_id) == 0
shown = _definition(capsys)
- assert shown["health"] == "failing", f"{label}: the seeded streak is not visible at all"
+ if label.startswith("watch"):
+ assert shown["health"] == "unknown", f"{label}: an unobserved waiter was guessed healthy"
+ assert shown["processing_health"] == "failing", (
+ f"{label}: the seeded downstream streak is not visible at all"
+ )
+ assert shown["processing_consecutive_failures"] == 2, (
+ f"{label}: downstream processing lost the streak"
+ )
+ else:
+ assert shown["health"] == "failing", f"{label}: the seeded streak is not visible at all"
+ assert shown["consecutive_failures"] == 2, f"{label} lost the streak"
assert _projected(payload) == _projected(shown), f"{label} disagrees with show"
- assert payload["consecutive_failures"] == 2, f"{label} lost the streak"
task_store = _FailureSeedingTaskStore()
add_args = _parse(
@@ -271,3 +283,151 @@ def test_task_and_watch_mutations_return_the_enriched_projection(capsys) -> None
assert cli.cmd_watch_update(_parse(["watch", "update", watch_id, "--name", "renamed"])) == 0
_assert_matches_show("watch update", _definition(capsys), cli.cmd_watch_show, watch_id)
+
+
+def test_watch_health_separates_waiter_from_event_processing(tmp_path, monkeypatch) -> None:
+ """HFR-436 — provenance does not create one shared health lifecycle."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ watch_store = ManagedWatchStore()
+ watch = watch_store.add_watch(
+ name="successful waiter",
+ session_key="slack::channel::C123",
+ command=[],
+ shell_command="true",
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ sqlite = SQLiteBackgroundTaskStore()
+ try:
+ unobserved = sqlite.get_watch(watch.id)
+ finally:
+ sqlite.close()
+ assert unobserved is not None and unobserved["health"] == "unknown"
+ assert watch_store.mark_cycle_start(watch.id)
+ assert watch_store.mark_cycle_result(
+ watch.id,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=True,
+ )
+ _seed_failed_runs(watch.id, request_type="watch")
+
+ sqlite = SQLiteBackgroundTaskStore()
+ try:
+ projected = sqlite.get_watch(watch.id)
+ finally:
+ sqlite.close()
+
+ assert projected is not None
+ assert projected["last_error"] is None
+ assert projected["health"] == "healthy"
+ assert projected["consecutive_failures"] == 0
+ assert projected["processing_health"] == "failing"
+ assert projected["processing_consecutive_failures"] == 2
+
+
+def test_once_watch_retry_exit_is_a_terminal_waiter_failure(tmp_path, monkeypatch) -> None:
+ """Retry codes are healthy only while a forever Watch can actually retry."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ watch_store = ManagedWatchStore()
+ watch = watch_store.add_watch(
+ name="one attempt",
+ session_key="slack::channel::C123",
+ command=[],
+ shell_command="exit 75",
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ assert watch_store.mark_cycle_start(watch.id)
+ assert watch_store.mark_cycle_result(
+ watch.id,
+ exit_code=75,
+ error="watch command exited with status 75",
+ disable=True,
+ )
+
+ sqlite = SQLiteBackgroundTaskStore()
+ try:
+ projected = sqlite.get_watch(watch.id)
+ finally:
+ sqlite.close()
+
+ assert projected is not None
+ assert projected["lifecycle_state"] == "finished"
+ assert projected["health"] == "failing"
+ assert projected["consecutive_failures"] == 1
+
+
+def test_forever_watch_retry_health_requires_an_enabled_definition(
+ tmp_path,
+ monkeypatch,
+) -> None:
+ """The same retry code becomes failing when the Watch retires."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ watch_store = ManagedWatchStore()
+ watch = watch_store.add_watch(
+ name="bounded retries",
+ session_key="slack::channel::C123",
+ command=[],
+ shell_command="exit 75",
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=60,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ )
+ assert watch_store.mark_cycle_start(watch.id)
+ assert watch_store.mark_cycle_result(
+ watch.id,
+ exit_code=75,
+ error="retry later",
+ disable=False,
+ )
+
+ sqlite = SQLiteBackgroundTaskStore()
+ try:
+ retrying = sqlite.get_watch(watch.id)
+ finally:
+ sqlite.close()
+ assert retrying is not None
+ assert retrying["enabled"] is True
+ assert retrying["health"] == "healthy"
+
+ assert watch_store.mark_cycle_start(watch.id)
+ assert watch_store.mark_cycle_result(
+ watch.id,
+ exit_code=75,
+ error="retry budget exhausted",
+ disable=True,
+ )
+ sqlite = SQLiteBackgroundTaskStore()
+ try:
+ retired = sqlite.get_watch(watch.id)
+ finally:
+ sqlite.close()
+ assert retired is not None
+ assert retired["enabled"] is False
+ assert retired["lifecycle_state"] == "finished"
+ assert retired["health"] == "failing"
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 9749c0849..268ae72bd 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -9,6 +9,7 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.delivery_evidence import DeliveryEvidence
from core.message_output import (
MessageOutput,
contained_teardown_output_for,
@@ -145,6 +146,89 @@ class _StubController:
class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
+ def test_terminal_snapshot_elects_fallback_after_excluding_canceled_runs(self):
+ controller = _StubController(platform="slack")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "turn_token": "turn-fallback",
+ "accepted_agent_run_ids": ["run-a", "run-b"],
+ },
+ )
+ output = MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ metadata={
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-fallback",
+ "delivered": False,
+ }
+ },
+ )
+ store = mock.Mock()
+ store.get_run.side_effect = lambda run_id: {
+ "run-a": {"id": "run-a", "status": "canceled"},
+ "run-b": {"id": "run-b", "status": "running"},
+ }.get(run_id)
+
+ with mock.patch(
+ "core.message_dispatcher.SQLiteBackgroundTaskStore",
+ return_value=store,
+ ):
+ enriched = dispatcher._output_with_turn_fallback_owner(context, output)
+
+ self.assertEqual(
+ enriched.metadata["turn_failure_notification"]["fallback_run_id"],
+ "run-b",
+ )
+ store.close.assert_called_once_with()
+
+ def test_terminal_recording_delegates_owner_election_to_the_atomic_store_batch(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController(platform="slack"))
+ store = mock.Mock()
+ store.get_run.side_effect = AssertionError(
+ "the dispatcher must not snapshot participant state outside the batch"
+ )
+ output = MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ idempotency_key="terminal-output",
+ metadata={
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-fallback",
+ "delivered": False,
+ "fallback_run_id": "run-a",
+ }
+ },
+ )
+
+ dispatcher._record_agent_run_terminal_for_ids(
+ store=store,
+ run_ids=["run-a", "run-b"],
+ text="",
+ message_id=None,
+ terminal_status="failed",
+ terminal_error="stream disconnected",
+ output_semantics=output,
+ provenance=dict(output.metadata),
+ )
+
+ store.record_turn_run_outputs.assert_called_once_with(
+ ["run-a", "run-b"],
+ output_id="terminal-output",
+ text="",
+ message_id=None,
+ sequence=None,
+ provenance=output.metadata,
+ terminal_status="failed",
+ error="stream disconnected",
+ deferred_run_ids=[],
+ )
+ store.get_run.assert_not_called()
+
async def test_detached_stale_result_delivers_without_mutating_newer_turn(self):
controller = _StubController(platform="slack")
controller.agent_service = type(
@@ -905,14 +989,55 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
user_id="U1", channel_id="C1", platform="slack",
platform_specific={"suppress_delivery": True},
)
+ evidence = DeliveryEvidence()
with mock.patch(
"core.message_dispatcher.persist_agent_message",
return_value={"id": "msg-background"},
) as persist:
- message_id = await dispatcher.emit_agent_message(context, "result", "private output")
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "private output",
+ delivery=evidence,
+ )
persist.assert_called_once()
self.assertEqual(message_id, "msg-background")
self.assertEqual(controller.im_client.sent_messages, [])
+ self.assertIsNone(evidence.ack_evidence)
+
+ async def test_suppressed_history_id_is_not_recorded_as_run_delivery(self):
+ controller = _StubController(platform="slack")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._record_suppressed_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "suppress_delivery": True,
+ "task_trigger_kind": "scheduled",
+ "task_execution_id": "run-background",
+ },
+ )
+ with mock.patch(
+ "core.message_dispatcher.persist_agent_message",
+ return_value={"id": "msg-local-history"},
+ ):
+ returned = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "private output",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="stable-output",
+ ),
+ )
+
+ self.assertEqual(returned, "msg-local-history")
+ self.assertIsNone(
+ dispatcher._record_suppressed_agent_run_terminal_result.call_args.args[2]
+ )
async def test_suppressed_result_records_folded_footer(self):
"""A suppressed Web result keeps structured UI metrics while its run
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 624988a5f..62902b327 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -2742,7 +2742,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-1", "private output", "suppressed:run-1", "succeeded"),
+ ("record", "run-1", "private output", None, "succeeded"),
("close",),
],
)
@@ -2776,7 +2776,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-agent", "private agent output", "suppressed:run-agent", "succeeded"),
+ ("record", "run-agent", "private agent output", None, "succeeded"),
("close",),
],
)
@@ -2851,9 +2851,9 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-1", "private agent output", "suppressed:run-1", "succeeded"),
- ("record", "run-2", "private agent output", "suppressed:run-1", "succeeded"),
- ("record", "run-3", "private agent output", "suppressed:run-1", "succeeded"),
+ ("record", "run-1", "private agent output", None, "succeeded"),
+ ("record", "run-2", "private agent output", None, "succeeded"),
+ ("record", "run-3", "private agent output", None, "succeeded"),
("close",),
],
)
@@ -2893,8 +2893,8 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-1", "private agent output", "suppressed:run-1", "succeeded"),
- ("record", "run-3", "private agent output", "suppressed:run-1", "succeeded"),
+ ("record", "run-1", "private agent output", None, "succeeded"),
+ ("record", "run-3", "private agent output", None, "succeeded"),
("close",),
],
)
@@ -3087,7 +3087,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(
calls,
[
- ("record", "run-agent", "final result", "suppressed:run-agent", "succeeded"),
+ ("record", "run-agent", "final result", None, "succeeded"),
("close",),
],
)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index b4f930235..56269a2fe 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -6734,6 +6734,174 @@ def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(
} == {"steer"}
+def test_hfr_439_turn_failure_metadata_reaches_every_linked_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The failed transition and its Turn notification evidence commit together."""
+
+ 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")
+ ]
+ 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-one-error",
+ outcome="failed",
+ settled_by="terminal_result",
+ evidence_kind="terminal_result",
+ evidence={
+ "settles_run": True,
+ "terminal_error": "stream disconnected",
+ "output_provenance": {
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-one-error",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ }
+ },
+ },
+ )
+
+ expected_owner = min(request.id for request in requests)
+ for request in requests:
+ row = request_store.get_run(request.id)
+ assert row is not None and row["status"] == "failed"
+ assert row["metadata"]["turn_id"] == "turn-one-error"
+ notice = request_store.sqlite_backend.owed_failure_notice(request.id)
+ assert notice["failure_id"] == "turn:turn-one-error"
+ assert notice["turn_id"] == "turn-one-error"
+ assert notice["turn_notification_delivered"] is True
+ assert notice["turn_notification_ack_evidence"] == "receipt"
+ assert notice["turn_fallback_run_id"] == expected_owner
+
+
+def test_turn_fallback_owner_excludes_a_canceled_participant(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A canceled Run keeps its audit state but cannot own the only fallback."""
+
+ 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")
+ ]
+ for request in requests:
+ assert request_store.claim(request.id) is not None
+ canceled_id = min(request.id for request in requests)
+ assert request_store.cancel_run(canceled_id)
+
+ 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-canceled-owner",
+ outcome="failed",
+ settled_by="terminal_result",
+ evidence_kind="terminal_result",
+ evidence={
+ "settles_run": True,
+ "terminal_error": "stream disconnected",
+ "output_provenance": {
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-canceled-owner",
+ "delivered": False,
+ }
+ },
+ },
+ )
+
+ eligible_id = next(request.id for request in requests if request.id != canceled_id)
+ assert request_store.get_run(canceled_id)["status"] == "canceled"
+ notice = request_store.sqlite_backend.owed_failure_notice(eligible_id)
+ assert notice["turn_fallback_run_id"] == eligible_id
+
+
+def test_late_turn_settlement_reuses_all_durable_participants(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A late accepted Run cannot elect a second owner from only its subset."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ settle = Mock()
+ manager = SessionTurnManager(
+ SimpleNamespace(
+ scheduled_task_service=SimpleNamespace(
+ settle_agent_runs_from_terminal_turn=settle
+ )
+ )
+ )
+ manager.accepted_agent_run_ids_for_turn = lambda _turn_id: [
+ "run-initial",
+ "run-late",
+ ]
+ turn = {
+ "id": "turn-late-owner",
+ "terminal_outcome": "failed",
+ "settled_by": "terminal_result",
+ "terminal_evidence_kind": "terminal_result",
+ "terminal_evidence_json": json.dumps(
+ {
+ "settles_run": True,
+ "output_provenance": {
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-late-owner",
+ "fallback_run_id": "run-initial",
+ }
+ },
+ }
+ ),
+ }
+
+ manager._settle_agent_run_ids_from_terminal_turn(["run-late"], turn)
+
+ settle.assert_called_once()
+ assert settle.call_args.args[0] == ["run-initial", "run-late"]
+
+
+def test_hfr_439_deferred_run_preserves_turn_failure_metadata(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """An Activity delay cannot turn a shared Turn failure into a new Run failure."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(message="participant", agent_name="codex")
+ assert request_store.claim(request.id) is not None
+ metadata = {
+ "turn_id": "turn-deferred-error",
+ "turn_failure_notification": {
+ "failure_id": "turn:turn-deferred-error",
+ "ack_evidence": "receipt",
+ "delivered": True,
+ "fallback_run_id": request.id,
+ },
+ }
+
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="failed",
+ error="stream disconnected",
+ metadata=metadata,
+ )
+ assert request_store.sqlite_backend.settle_deferred_run(request.id)
+
+ notice = request_store.sqlite_backend.owed_failure_notice(request.id)
+ assert notice["failure_id"] == "turn:turn-deferred-error"
+ assert notice["turn_id"] == "turn-deferred-error"
+ assert notice["turn_notification_delivered"] is True
+ assert notice["turn_fallback_run_id"] == request.id
+
+
def test_historical_conflated_sent_callback_stays_inert_on_startup(
tmp_path: Path,
monkeypatch,
diff --git a/tests/test_watches.py b/tests/test_watches.py
index c926559ce..cee32ab2e 100644
--- a/tests/test_watches.py
+++ b/tests/test_watches.py
@@ -38,7 +38,12 @@ from core.watches import (
_ManagedWatchRuntimeWorkHandler,
_StaleWorkerRecovery,
)
-from storage.background import SQLiteBackgroundTaskStore
+from storage.background import (
+ WATCH_HOOK_OUTCOME_EVENT,
+ WATCH_HOOK_OUTCOME_METADATA_KEY,
+ WATCH_HOOK_OUTCOME_WAITER_FAILURE,
+ SQLiteBackgroundTaskStore,
+)
TEST_MARKER = "test-watch-worker"
TEST_FINGERPRINT = fingerprint_process_marker(TEST_MARKER)
@@ -646,6 +651,10 @@ def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path:
# which scheduled_tasks dispatches like a hook_send but tags as trigger_kind="watch".
assert pending[0].request_type == "watch"
assert pending[0].prompt == "The waiter finished.\n\nwaiter output"
+ assert (
+ pending[0].metadata[WATCH_HOOK_OUTCOME_METADATA_KEY]
+ == WATCH_HOOK_OUTCOME_EVENT
+ )
assert saved is not None
assert saved.enabled is False
assert saved.last_exit_code == 0
@@ -989,6 +998,10 @@ def test_managed_watch_service_turns_spawn_error_into_failed_cycle(tmp_path: Pat
assert len(pending) == 1
assert "stopped because the waiter exited with code 1" in pending[0].prompt
assert "fix the waiter or its dependencies" in pending[0].prompt
+ assert (
+ pending[0].metadata[WATCH_HOOK_OUTCOME_METADATA_KEY]
+ == WATCH_HOOK_OUTCOME_WAITER_FAILURE
+ )
@pytest.mark.parametrize("use_shell", [False, True], ids=["exec", "shell"])
diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsx
index 1b761575f..eaa2d7646 100644
--- a/ui/src/components/workbench/HarnessPage.test.tsx
+++ b/ui/src/components/workbench/HarnessPage.test.tsx
@@ -18,6 +18,7 @@ import type {
import {
DetailSession,
HealthBadge,
+ ProcessingHealthBadge,
RunDetail,
RunTriggerChip,
TaskDetail,
@@ -435,6 +436,34 @@ describe('HealthBadge', () => {
});
});
+describe('ProcessingHealthBadge', () => {
+ it('names a failed Watch follow-up without reporting the waiter as failed', () => {
+ const row = watch({
+ health: 'healthy',
+ consecutive_failures: 0,
+ recent_failures: 0,
+ processing_health: 'failing',
+ processing_consecutive_failures: 2,
+ processing_recent_failures: 2,
+ });
+
+ expect(render(<HealthBadge row={row} />)).toBe('');
+ const html = render(<ProcessingHealthBadge row={row} />);
+ expect(html).toContain(`>${i18n.t('harness.processingHealth.failing')} 2<`);
+ expect(html).toContain('text-pink');
+ });
+
+ it('stays quiet when event processing is healthy', () => {
+ expect(render(<ProcessingHealthBadge row={watch({ processing_health: 'healthy' })} />)).toBe('');
+ });
+
+ it('surfaces an unreadable downstream verdict without inventing a count', () => {
+ const html = render(<ProcessingHealthBadge row={watch({ processing_health: 'unknown' })} />);
+ expect(html).toContain(`>${i18n.t('harness.processingHealth.unknown')}<`);
+ expect(html).toContain('text-muted');
+ });
+});
+
describe('TaskKindBadge', () => {
it('marks a command task, so the list distinguishes it from a message task', () => {
const label = i18n.t('harness.taskKind.command');
@@ -779,6 +808,19 @@ describe('WatchDetail runtime', () => {
else expect(html).not.toContain('process exited');
if (expected.pid) expect(html).toContain(expected.pid);
});
+
+ it('keeps unknown event-processing health visible in the detail pane', () => {
+ const html = render(
+ <WatchDetail
+ watch={watch({ processing_health: 'unknown' })}
+ onToggleEnabled={() => undefined}
+ pending={false}
+ />,
+ );
+
+ expect(html).toContain(`>${i18n.t('harness.detail.eventProcessing')}<`);
+ expect(html).toContain(`>${i18n.t('harness.processingHealth.unknown')}<`);
+ });
});
describe('RunTriggerChip', () => {
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 3f8f918bc..8c60437d3 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -64,6 +64,7 @@ import {
definitionActiveCount,
definitionChipLabel,
definitionHealth,
+ definitionProcessingHealth,
definitionRowLine,
definitionRowTitle,
definitionStatusCount,
@@ -1051,6 +1052,35 @@ export const HealthBadge: React.FC<{ row: HarnessTask | HarnessWatch }> = ({ row
);
};
+const visibleProcessingHealth = (row: HarnessWatch) => {
+ const health = definitionProcessingHealth(row);
+ return health === 'failing' || health === 'degraded' || health === 'unknown' ? health : null;
+};
+
+export const ProcessingHealthBadge: React.FC<{ row: HarnessWatch }> = ({ row }) => {
+ const { t } = useTranslation();
+ const health = visibleProcessingHealth(row);
+ if (!health) return null;
+ const count =
+ health === 'unknown'
+ ? 0
+ : health === 'failing'
+ ? row.processing_consecutive_failures || 0
+ : row.processing_recent_failures || 0;
+ return (
+ <Badge
+ variant="secondary"
+ className={clsx(
+ 'shrink-0 font-mono text-[9px] uppercase',
+ health === 'failing' ? 'text-pink' : health === 'degraded' ? 'text-amber' : 'text-muted',
+ )}
+ >
+ {t(`harness.processingHealth.${health}`)}
+ {count > 1 ? ` ${count}` : ''}
+ </Badge>
+ );
+};
+
// What a task *does*, when that is not the default. A command task runs a
// subprocess instead of prompting an Agent, and nothing else on the row says so:
// the schedule chip, the state dot and the second line read identically for both
@@ -1135,6 +1165,7 @@ const DefinitionRow: React.FC<DefinitionRowProps> = ({
</Badge>
)}
<HealthBadge row={row} />
+ {kind === 'watch' && <ProcessingHealthBadge row={row as HarnessWatch} />}
</div>
<div className="flex min-w-0 items-center gap-2 text-[11px] text-muted">
{line.alert && <AlertTriangle className={clsx('size-3 shrink-0', ALERT_CLASS[line.alert])} />}
@@ -1598,6 +1629,11 @@ export const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggle
</div>
</DetailField>
)}
+ {visibleProcessingHealth(watch) && (
+ <DetailField label={t('harness.detail.eventProcessing')}>
+ <ProcessingHealthBadge row={watch} />
+ </DetailField>
+ )}
<DetailField label={t('harness.detail.id')}>
<code className="font-mono text-[11px] text-muted">{watch.id}</code>
</DetailField>
diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.ts
index d906586c6..eab4ab26e 100644
--- a/ui/src/components/workbench/harnessLifecycle.ts
+++ b/ui/src/components/workbench/harnessLifecycle.ts
@@ -330,6 +330,9 @@ export type HarnessDefinitionFacts = {
health?: HarnessDefinitionHealth | string | null;
consecutive_failures?: number | null;
recent_failures?: number | null;
+ processing_health?: HarnessDefinitionHealth | string | null;
+ processing_consecutive_failures?: number | null;
+ processing_recent_failures?: number | null;
// Command-task fields (also present on a watch, which has always run a
// command). ``/api/harness/tasks`` serves the raw store row, so these arrive
// exactly as ``_scheduled_task_from_row`` writes them: ``shell_command`` as a
@@ -357,6 +360,11 @@ export function definitionHealth(row: HarnessDefinitionFacts): HarnessDefinition
return value && HEALTH_STATES.has(value) ? (value as HarnessDefinitionHealth) : null;
}
+export function definitionProcessingHealth(row: HarnessDefinitionFacts): HarnessDefinitionHealth | null {
+ const value = row.processing_health;
+ return value && HEALTH_STATES.has(value) ? (value as HarnessDefinitionHealth) : null;
+}
+
const WHITESPACE_RUN = /\s+/g;
// One uniform row title for a task or a watch (§4.3): its name, else the first
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index c8b3098ae..ca12ed408 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1340,6 +1340,11 @@ export type HarnessDefinitionState = {
// the window at all. Both age out on their own; neither is acknowledgment state.
consecutive_failures: number;
recent_failures: number;
+ // Watches separate waiter health above from the Agent Runs created by events.
+ // Tasks omit these because their execution is already the definition health.
+ processing_health?: HarnessDefinitionHealth | null;
+ processing_consecutive_failures?: number;
+ processing_recent_failures?: number;
};
export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 9f8f2d881..20587d484 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2955,6 +2955,7 @@
"mode": "Mode",
"followUp": "Follow-up message",
"runtime": "Runtime",
+ "eventProcessing": "Event processing",
"lastError": "Last error",
"type": "Type",
"triggeredBy": "Triggered by",
@@ -3042,6 +3043,11 @@
"degraded": "degraded",
"unknown": "health unknown"
},
+ "processingHealth": {
+ "failing": "processing failed",
+ "degraded": "recent processing failure",
+ "unknown": "processing status unknown"
+ },
"lifecycle": {
"running": "Running",
"waiting": "Waiting",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e31314364..a00b6d4b0 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2955,6 +2955,7 @@
"mode": "模式",
"followUp": "跟进消息",
"runtime": "运行时",
+ "eventProcessing": "事件处理",
"lastError": "上次错误",
"type": "类型",
"triggeredBy": "触发来源",
@@ -3042,6 +3043,11 @@
"degraded": "近期失败",
"unknown": "状态未知"
},
+ "processingHealth": {
+ "failing": "处理失败",
+ "degraded": "近期处理失败",
+ "unknown": "处理状态未知"
+ },
"lifecycle": {
"running": "运行中",
"waiting": "等待中",
diff --git a/vibe/cli.py b/vibe/cli.py
index 81ba38784..b7ab5c4c1 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -1980,6 +1980,11 @@ _DEFINITION_FAILURE_FIELDS = (
"health",
"consecutive_failures",
"recent_failures",
+ # Watches keep waiter health above and expose their downstream Agent Run
+ # history independently. Tasks omit these keys.
+ "processing_health",
+ "processing_consecutive_failures",
+ "processing_recent_failures",
# The one field that says WHY, dropped from the brief list payload before.
"last_error",
)
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 4d4e3f75a..0584c176e 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -91,6 +91,9 @@
},
"notice": {
"failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",
+ "watchProcessingFailed": "[Avibe Harness] Watch \"{name}\" detected an event, but Agent processing failed.",
+ "watchFailureReportFailed": "[Avibe Harness] Watch \"{name}\" stopped because its waiter failed, but the Agent could not report that failure.",
+ "watchFollowUpFailed": "[Avibe Harness] Watch \"{name}\" follow-up Agent processing failed.",
"interrupted": "[Avibe Harness] Scheduled work \"{name}\" was interrupted ({reason}). Nothing is wrong with the definition itself.",
"commandLine": "Command: {command}",
"error": "Error: {error}",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index ac49bb3e3..bd64dc888 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -91,6 +91,9 @@
},
"notice": {
"failed": "[Avibe Harness] 后台任务「{name}」执行失败。",
+ "watchProcessingFailed": "[Avibe Harness] Watch「{name}」已检测到事件,但 Agent 处理失败。",
+ "watchFailureReportFailed": "[Avibe Harness] Watch「{name}」因 waiter 失败而停止,但 Agent 未能报告该故障。",
+ "watchFollowUpFailed": "[Avibe Harness] Watch「{name}」的后续 Agent 处理失败。",
"interrupted": "[Avibe Harness] 后台任务「{name}」被中断({reason}),任务本身没有问题。",
"commandLine": "命令:{command}",
"error": "错误:{error}",