The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): surface silent turn stalls with a bounded turn-liveness watchdog (#95548, #95663)
Finn7630fe7abe37ae5
diff --git a/agent/turn_liveness.py b/agent/turn_liveness.pynew file mode 100644index 00000000000..ce2070aecb6--- /dev/null+++ b/agent/turn_liveness.py@@ -0,0 +1,292 @@+"""Turn liveness watchdog (#95548): force-abort turns that stall silently.++A conversation turn can stall mid-flight (observed in #95548 between+"model returned tool_calls" and tool execution, after a slow model+response + desktop WS disconnect) with no error logged, no further+progress, and the durable session turn lease kept renewing — so nothing+ever force-aborts the turn and the session stays stuck until the process+is killed.++This module owns the watchdog policy end to end:++* configuration — :func:`resolve_turn_liveness_settings` reads the+ ``agent.turn_liveness`` section of config.yaml and validates it;+* state machine — :class:`TurnLivenessWatchdog` samples the agent's+ activity clock and drives the stall decision;+* thread mechanics — the polling loop, stop handling, and the stall+ commit point.++``AIAgent.run_conversation`` (``run_agent.py``) keeps only the smallest+integration seam: it resolves the settings, supplies the commit and+deactivate callbacks that own turn-lease state, and starts the thread+next to the durable lease refresher.++Config surface (config.yaml)::++ agent:+ turn_liveness:+ timeout_s: 600.0 # idle bound; <= 0 disables the watchdog+ poll_s: 15.0 # sampling interval (seconds)++Both values are validated. A non-numeric typo, ``NaN``, or ``Inf`` logs a+warning and falls back to the documented default — it never crashes+startup, and a bogus value can never silently disable the watchdog+(``NaN``) or freeze the watcher thread (``Inf`` poll).++Race safety (#95663 review): the watchdog samples the activity clock and+binds the abort decision to the observed ``(generation, timestamp)``+pair. The commit callback revalidates that pair under the *same* lock+``AIAgent._touch_activity`` uses to stamp the clock, so a turn that+resumed while the stall was being logged/emitted is never hard-cancelled+— it continues and its lease keeps renewing. Round-3 carried the+revalidated generation into ``AIAgent.interrupt``+(``require_generation``). Round-4 makes that generation an actual+cancellation claim consumed at the final mutation edge: ``interrupt``+reserves the claim under the activity lock, ``_touch_activity``+invalidates the reservation the instant real progress lands, and the+claim survives every blocking boundary, including the compression+commit fence. Round-6 consumes the claim and publishes the first+observable interrupt state in ONE activity-lock critical section, so a+turn that resumes can only ever interleave before that section (the+reservation is invalidated and the abort declines) or after it (the+interrupt already committed under the lock) — never between "claim+consumed" and "state published". A turn that resumes anywhere in the+window is never hard-cancelled, and an exceptional interrupt path+declines the abort fail-closed instead of mutating interrupt state.+"""++from __future__ import annotations++import logging+import math+import threading+import time+from typing import Any, Callable, Dict, NamedTuple, Optional, Tuple++logger = logging.getLogger(__name__)++DEFAULT_TURN_LIVENESS_TIMEOUT_S = 600.0+DEFAULT_TURN_LIVENESS_POLL_S = 15.0+MIN_TURN_LIVENESS_POLL_S = 0.01++_CONFIG_TIMEOUT_KEY = "agent.turn_liveness.timeout_s"+_CONFIG_POLL_KEY = "agent.turn_liveness.poll_s"+++class ActivitySnapshot(NamedTuple):+ """One observation of the activity clock, bound to an abort decision.++ ``generation`` + ``activity_ts`` uniquely identify the observed stamp.+ The commit callback must revalidate this pair under the lock shared+ with ``AIAgent._touch_activity``; if it no longer matches, the+ observation is stale and the abort must be declined.+ """++ generation: int+ activity_ts: Optional[float]+ idle_seconds: float+++def _warn_invalid_value(key: str, raw: Any, default: float) -> None:+ logger.warning(+ "Invalid %s in config.yaml: %r — falling back to default %.1f.",+ key,+ raw,+ default,+ )+++def _resolve_finite_seconds(raw: Any, *, default: float, key: str) -> float:+ """Coerce one duration knob, rejecting typos, NaN and Inf.++ A non-numeric value must not raise into durable-turn startup, and a+ non-finite value must not silently change behavior (``NaN`` would+ disable the timeout via the ``> 0`` comparison; ``Inf`` would freeze+ the poll loop in ``Event.wait``).+ """+ try:+ value = float(raw)+ except (TypeError, ValueError):+ _warn_invalid_value(key, raw, default)+ return default+ if not math.isfinite(value):+ _warn_invalid_value(key, raw, default)+ return default+ return value+++def resolve_turn_liveness_settings(+ config: Optional[Dict[str, Any]] = None,+) -> Tuple[Optional[float], float]:+ """Resolve ``(timeout_s, poll_s)`` from the ``agent.turn_liveness`` section.++ Precedence: explicit config.yaml value wins over the default; any+ invalid value (typo, NaN, Inf, non-positive poll) falls back to the+ default with a warning. ``timeout_s <= 0`` is the documented opt-out+ and yields ``(None, poll_s)`` — the caller then never arms the+ watchdog. The resolver never raises.+ """+ section: Dict[str, Any] = {}+ if isinstance(config, dict):+ agent_cfg = config.get("agent")+ if isinstance(agent_cfg, dict):+ raw_section = agent_cfg.get("turn_liveness")+ if isinstance(raw_section, dict):+ section = raw_section+ elif raw_section is not None:+ _warn_invalid_value(+ "agent.turn_liveness", raw_section, DEFAULT_TURN_LIVENESS_TIMEOUT_S+ )++ timeout_s = _resolve_finite_seconds(+ section.get("timeout_s", DEFAULT_TURN_LIVENESS_TIMEOUT_S),+ default=DEFAULT_TURN_LIVENESS_TIMEOUT_S,+ key=_CONFIG_TIMEOUT_KEY,+ )+ poll_s = _resolve_finite_seconds(+ section.get("poll_s", DEFAULT_TURN_LIVENESS_POLL_S),+ default=DEFAULT_TURN_LIVENESS_POLL_S,+ key=_CONFIG_POLL_KEY,+ )+ if poll_s <= 0:+ _warn_invalid_value(_CONFIG_POLL_KEY, poll_s, DEFAULT_TURN_LIVENESS_POLL_S)+ poll_s = DEFAULT_TURN_LIVENESS_POLL_S+ # <= 0 is the documented opt-out, not an error.+ if timeout_s <= 0:+ timeout_s = None+ return timeout_s, poll_s+++class TurnLivenessWatchdog:+ """Sampled-idle watchdog thread bound to one conversation turn.++ ``run_agent.py`` owns the turn-lease state (stop event, turn-active+ flag, interrupt plumbing); this class only reads the activity clock+ and calls back at the stall commit point. All synchronization with+ ``AIAgent._touch_activity`` goes through ``activity_lock``, which+ must be the SAME lock the agent stamps its activity clock with.+ """++ def __init__(+ self,+ agent: Any,+ *,+ session_id: str,+ timeout_s: float,+ poll_s: float,+ stop_event: threading.Event,+ activity_lock: threading.Lock,+ is_turn_active: Callable[[], bool],+ commit_abort: Callable[[ActivitySnapshot, str], bool],+ deactivate_turn: Callable[[], None],+ ) -> None:+ self._agent = agent+ self._session_id = session_id+ self._timeout_s = float(timeout_s)+ self._poll_s = max(MIN_TURN_LIVENESS_POLL_S, float(poll_s))+ self._stop_event = stop_event+ self._activity_lock = activity_lock+ self._is_turn_active = is_turn_active+ self._commit_abort = commit_abort+ self._deactivate_turn = deactivate_turn++ def make_thread(self) -> threading.Thread:+ """Build the (not yet started) watcher thread.++ ``run_agent.py`` creates the watchdog before the turn begins but+ starts the thread at turn entry, right after the turn-active flag+ and the activity clock are stamped.+ """+ return threading.Thread(+ target=self._watch,+ name="turn-liveness-watchdog",+ daemon=True,+ )++ def start(self) -> threading.Thread:+ """Spawn the watcher thread and return it (already running)."""+ thread = self.make_thread()+ thread.start()+ return thread++ def _watch(self) -> None:+ while not self._stop_event.wait(self._poll_s):+ snapshot = self._sample()+ if snapshot is None:+ # Turn is no longer active; nothing to watch.+ return+ if snapshot.idle_seconds < self._timeout_s:+ continue+ self._surface_stall(snapshot)+ # Commit point: bind the abort to the sampled generation/ts+ # and revalidate under the lock shared with `_touch_activity`.+ # If progress resumed while the stall was being surfaced, the+ # turn continues and this loop resumes sampling — the lease+ # keeps renewing. The commit also carries the revalidated+ # generation into the interrupt path, which reserves it as a+ # claim, survives every blocking boundary (compression+ # fence), and consumes it at the final mutation edge+ # immediately before publication (#95663 round-4) — progress+ # landing anywhere in that window declines the abort.+ if not self._commit_abort(snapshot, self._abort_message(snapshot)):+ continue+ # Stop renewing the durable lease: a wedge the hard interrupt+ # cannot unwind must not keep the lease alive forever (the+ # issue's "lease keeps renewing" masking). The TTL expiry then+ # lets stale-turn cleanup reclaim the row.+ self._deactivate_turn()+ return++ def _sample(self) -> Optional[ActivitySnapshot]:+ with self._activity_lock:+ if not self._is_turn_active():+ return None+ generation = getattr(+ self._agent, "_turn_liveness_activity_generation", 0+ )+ activity_ts = getattr(self._agent, "_last_activity_ts", None)+ now = time.time()+ if activity_ts is None:+ idle_seconds = 0.0+ else:+ idle_seconds = max(0.0, now - activity_ts)+ return ActivitySnapshot(+ generation=generation,+ activity_ts=activity_ts,+ idle_seconds=idle_seconds,+ )++ def _abort_message(self, snapshot: ActivitySnapshot) -> str:+ return (+ f"Turn made no progress for {int(snapshot.idle_seconds)}s; "+ "aborting to release the session."+ )++ def _surface_stall(self, snapshot: ActivitySnapshot) -> None:+ """Log the stall loudly and emit a UI-visible warning.++ The lock is deliberately NOT held here: acting on the observation+ happens at the commit point, after this surface window, where the+ observed generation/timestamp is revalidated.+ """+ session_id = getattr(self._agent, "session_id", None) or self._session_id+ last_desc = getattr(self._agent, "_last_activity_desc", None)+ logger.error(+ "Turn liveness watchdog fired for session %s: "+ "no progress for %.1fs (last activity: %r). "+ "Force-aborting the turn and stopping lease renewal (#95548).",+ session_id,+ snapshot.idle_seconds,+ last_desc,+ )+ emit_warning = getattr(self._agent, "_emit_warning", None)+ if not callable(emit_warning):+ return+ try:+ emit_warning(+ "⚠️ This turn stopped making progress "+ f"({int(snapshot.idle_seconds)}s without activity); "+ "aborting it so the session can recover."+ )+ except Exception:+ logger.debug("Failed to emit turn liveness warning", exc_info=True)diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex be5b02fdcdc..ea3ef6cefc0 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -391,6 +391,20 @@ DEFAULT_CONFIG = {# ``false`` keeps the historical strict-provider behavior (Mistral,# Groq, Cerebras reject the field with HTTP 400)."reasoning_echo": False,+ # Turn liveness watchdog (#95548): a turn that shows no observable+ # progress (activity-clock idle, never touched by lease renewal) for+ # `timeout_s` seconds is logged loudly, force-interrupted so the UI+ # can retry it, and its durable turn lease stops renewing so TTL+ # expiry lets stale-turn cleanup reclaim the session even when the+ # hard interrupt cannot unwind a wedged frame. `timeout_s` <= 0+ # disables the watchdog; `poll_s` is the sampling interval. Invalid+ # values (typo, NaN, Inf, non-positive poll) warn and fall back to+ # the default instead of crashing startup or silently disabling the+ # watchdog. See agent/turn_liveness.py.+ "turn_liveness": {+ "timeout_s": 600.0,+ "poll_s": 15.0,+ },},"terminal": {diff --git a/run_agent.py b/run_agent.pyindex 34712ec919c..d8501e0ed2f 100644--- a/run_agent.py+++ b/run_agent.py@@ -3403,7 +3403,8 @@ class AIAgent:*,hard_cancel: bool = False,tool_reason: Optional[str] = None,- ) -> None:+ require_generation: Optional[int] = None,+ ) -> bool:"""Request the agent to interrupt its current tool-calling loop.@@ -3421,6 +3422,27 @@ class AIAgent:atomic signal even while ordinary interrupts are masked.tool_reason: Trusted fixed category safe to expose in tool output.Arbitrary diagnostic or caller text belongs in message.+ require_generation: Optional activity-generation claim (#95663+ round-3/round-4/round-6 review). When set, the+ interrupt is published only if the turn's activity+ generation still equals this value at the final+ mutation edge. The claim is RESERVED under the+ activity lock — ``_touch_activity`` invalidates the+ reservation the instant real progress lands —+ survives every blocking boundary in between+ (including the compression commit fence), and is+ CONSUMED in ONE lock critical section together with+ the first observable publication+ (``_interrupt_requested`` / ``_interrupt_message`` /+ ``_tool_interrupt_reason`` and the hard-cancel+ event). If the turn resumed in the window, the call+ abandons itself without publishing anything (no+ flag, no hard-cancel event, no tool signal).++ Returns:+ True when the interrupt was published, False when a+ ``require_generation`` claim no longer matched the live activity+ clock and the call was abandoned without publishing.Example (CLI):# In a separate input thread:@@ -3432,29 +3454,94 @@ class AIAgent:if session_has_running_agent:running_agent.interrupt(new_message.text)"""+ if require_generation is not None:+ # Round-4 (#95663): RESERVE the abort's generation claim under+ # the SAME lock `_touch_activity` stamps the clock with. Real+ # progress invalidates the reservation the instant it lands,+ # and the claim is CONSUMED at the final mutation edge — after+ # every blocking boundary — in ONE critical section with the+ # first observable publication (#95663 round-6). A resumed turn+ # therefore abandons the abort instead of being hard-cancelled+ # by a stale proof.+ with self._liveness_activity_lock():+ if (+ getattr(self, "_turn_liveness_activity_generation", 0)+ != require_generation+ ):+ return False+ self._turn_liveness_abort_claim = require_generation+# A hard stop and redirect share one lock so /stop cannot race with an# accepted correction and accidentally turn itself into a retry.def _admit_hard_cancel() -> None:- event = getattr(self, "_hard_interrupt_requested", None)- if event is None:- return+ # Cancel any pending compression commit, or wait for an+ # in-flight commit to finish. This call deliberately publishes+ # NOTHING observable: the generation claim and the first+ # interrupt state (including the hard-stop event) commit+ # together at the final mutation edge below (#95663 round-6).fence = vars(self).get("_active_compression_commit_fence")cancel_before_commit = getattr(type(fence), "cancel_before_commit", None)if callable(cancel_before_commit):try:- # This sets the Event while holding the same lock used by- # begin_commit(). If commit already won, it waits for that- # tracked mutation to finish before publishing the stop.- cancel_before_commit(fence, event)- return+ # Marks the fence cancelled (or waits out an already+ # started commit) without setting the hard-stop Event,+ # which is published only at the final claim edge.+ cancel_before_commit(fence)except Exception:logger.debug("Compression hard-cancel fence admission failed",exc_info=True,)- event.set()++ def _publish_interrupt_state() -> None:+ self._interrupt_requested = True+ self._interrupt_message = message+ self._tool_interrupt_reason = tool_interrupt_reason+ if hard_cancel:+ _hard_event = getattr(+ self, "_hard_interrupt_requested", None+ )+ if _hard_event is not None:+ _hard_event.set()++ def _consume_claim_and_publish_first_state() -> bool:+ # Final mutation edge (#95663 round-6): when a generation claim+ # is in play, claim consumption and the FIRST observable+ # interrupt publication are ONE activity-lock critical section.+ # Round-4 consumed the claim under the lock, released it, and+ # only then assigned+ # `_interrupt_requested` / `_interrupt_message` /+ # `_tool_interrupt_reason` — a turn that resumed in that+ # consume→publication window (real progress, generation G+1)+ # was still hard-cancelled by an already-consumed claim. Now+ # the abort's commit point and its first publication share the+ # lock `_touch_activity` stamps the clock with, so the+ # generation winner is total: either the claim survives and+ # the interrupt state commits under the lock BEFORE any later+ # activity stamp, or the stamp landed first and the abort+ # declines without publishing anything.+ if require_generation is None:+ # No claim to race the activity clock against: publish+ # exactly as round-4 did, WITHOUT touching the liveness+ # lock. ``AIAgent`` stand-ins used by unrelated suites+ # (e.g. the start-order gate `_Stub`) do not carry the+ # liveness seam, and an unconditional+ # ``_liveness_activity_lock()`` acquisition here+ # regressed them (AttributeError caught by round-6+ # exact-head CI).+ _publish_interrupt_state()+ return True+ with self._liveness_activity_lock():+ if (+ getattr(self, "_turn_liveness_abort_claim", None)+ != require_generation+ ):+ return False+ self._turn_liveness_abort_claim = None+ _publish_interrupt_state()+ return True# Keep tool cancellation attribution separate from _interrupt_message:# ordinary interrupts may carry the user's full next message, which@@ -3468,18 +3555,20 @@ class AIAgent:_redirect_lock = getattr(self, "_pending_redirect_lock", None)if _redirect_lock is not None:with _redirect_lock:- self._interrupt_requested = True- self._interrupt_message = message- self._tool_interrupt_reason = tool_interrupt_reason+ # The (potentially blocking) compression fence runs BEFORE+ # the atomic claim/publication edge (#95663 round-6); the+ # redirect lock is still held across the fence, exactly as+ # before, so /stop cannot race with an accepted correction.if hard_cancel:_admit_hard_cancel()+ if not _consume_claim_and_publish_first_state():+ return Falseself._pending_redirect = Noneelse:- self._interrupt_requested = True- self._interrupt_message = message- self._tool_interrupt_reason = tool_interrupt_reasonif hard_cancel:_admit_hard_cancel()+ if not _consume_claim_and_publish_first_state():+ return Falseself._pending_redirect = None# Codex app-server owns its model/tool loop and watches a private@@ -3558,6 +3647,7 @@ class AIAgent:logger.debug("Failed to propagate interrupt to child agent: %s", e)if not self.quiet_mode:print("\n⚡ Interrupt requested" + (f": '{message[:40]}...'" if message and len(message) > 40 else f": '{message}'" if message else ""))+ return Truedef hard_interrupt(self,@@ -4192,6 +4282,22 @@ class AIAgent:from agent.agent_runtime_helpers import apply_pending_steer_to_tool_resultsreturn apply_pending_steer_to_tool_results(self, messages, num_tool_msgs)+ def _liveness_activity_lock(self) -> "threading.Lock":+ """Shared lock for the activity clock and its generation counter.++ ``_touch_activity`` stamps the clock under this lock; the turn+ liveness watchdog (``agent/turn_liveness.py``) samples and commits+ under the same lock, so a stall observation can never abort a turn+ that resumed between the sample and the commit (#95663 review).+ Created lazily so ``AIAgent.__new__``-based test doubles keep+ working.+ """+ _lock = getattr(self, "_turn_liveness_activity_lock", None)+ if _lock is None:+ _lock = threading.Lock()+ self._turn_liveness_activity_lock = _lock+ return _lock+def _touch_activity(self,desc: str,@@ -4201,6 +4307,12 @@ class AIAgent:) -> None:"""Update the last-activity timestamp and description (thread-safe).+ The clock stamp is synchronized on ``_liveness_activity_lock`` and+ bumps a monotonic generation counter, so concurrent readers (the+ turn liveness watchdog, #95548) can bind their stall observation to+ the exact ``(generation, timestamp)`` pair they sampled and+ revalidate it at the commit point.+Also bridges to the kanban board's heartbeat fields when thisprocess is a dispatcher-spawned worker (HERMES_KANBAN_TASK set),so the dispatcher watchdog doesn't reclaim an actively-running@@ -4224,9 +4336,27 @@ class AIAgent:reset_session_activity_persist_window,)- self._last_activity_ts = time.time()- self._last_activity_desc = bound_activity_description(desc)- self._last_activity_provenance = normalize_activity_provenance(provenance)+ # Lazy per-instance lock (inline so bare doubles like+ # types.SimpleNamespace fixtures keep working — see+ # tests/run_agent/test_session_activity_persist.py).+ _clock_lock = getattr(self, "_turn_liveness_activity_lock", None)+ if _clock_lock is None:+ _clock_lock = threading.Lock()+ self._turn_liveness_activity_lock = _clock_lock+ with _clock_lock:+ self._turn_liveness_activity_generation = (+ getattr(self, "_turn_liveness_activity_generation", 0) + 1+ )+ self._last_activity_ts = time.time()+ self._last_activity_desc = bound_activity_description(desc)+ self._last_activity_provenance = normalize_activity_provenance(provenance)+ # Round-4 (#95663): real progress invalidates any reserved+ # abort claim. A watchdog interrupt that is still in flight+ # (e.g. parked inside the compression commit fence) must+ # abandon itself at the final mutation edge instead of+ # publishing against a generation the turn has already left+ # behind.+ self._turn_liveness_abort_claim = Noneif os.environ.get("HERMES_KANBAN_TASK"):try:from tools.kanban_tools import (@@ -8859,6 +8989,7 @@ class AIAgent:durable_turn_lease = Nonedurable_turn_lease_stop = Nonedurable_turn_lease_thread = None+ durable_turn_liveness_thread = Nonedurable_turn_lease_activity_lock = threading.Lock()durable_turn_lease_turn_active = Falsedurable_turn_lease_interrupt_message = None@@ -9070,22 +9201,141 @@ class AIAgent:getattr(self, "_session_turn_lease_refresh_interval", 60.0))- def _refresh_durable_turn_lease() -> None:- def _interrupt_turn(message: str) -> None:- nonlocal durable_turn_lease_interrupt_message- with durable_turn_lease_activity_lock:- if (- durable_turn_lease_stop.is_set()- or not durable_turn_lease_turn_active- ):- return- durable_turn_lease_interrupt_message = message- try:- self.interrupt(message, hard_cancel=True)- except Exception:- self._interrupt_requested = True- self._interrupt_message = message+ # ── Turn liveness watchdog (#95548) ─────────────────────+ # The durable lease refresher keeps the lease alive for as+ # long as the turn runs, so lease renewal is NOT evidence of+ # progress. A turn that stalls silently (observed #95548: no+ # tool execution, no API call, no persisted message for 9++ # minutes after a slow model response + desktop WS+ # disconnect) would otherwise renew its lease forever, look+ # "active", and never be force-aborted.+ #+ # The watchdog policy (config resolution, sampling state+ # machine, thread mechanics) lives in agent/turn_liveness.py;+ # this block is only the integration seam: resolve the+ # config.yaml settings, wire the commit/deactivate callbacks+ # that own turn-lease state, and start the thread.+ try:+ from hermes_cli.config import (+ load_config_readonly as _liveness_load_config,+ )+ _liveness_config = _liveness_load_config() or {}+ except Exception:+ _liveness_config = {}+ from agent import turn_liveness++ _liveness_timeout, _liveness_poll = (+ turn_liveness.resolve_turn_liveness_settings(_liveness_config)+ )++ def _interrupt_turn(message: str) -> None:+ nonlocal durable_turn_lease_interrupt_message+ with durable_turn_lease_activity_lock:+ if (+ durable_turn_lease_stop.is_set()+ or not durable_turn_lease_turn_active+ ):+ return+ durable_turn_lease_interrupt_message = message+ try:+ self.interrupt(message, hard_cancel=True)+ except Exception:+ self._interrupt_requested = True+ self._interrupt_message = message++ def _commit_turn_liveness_abort(+ snapshot: "turn_liveness.ActivitySnapshot",+ message: str,+ ) -> bool:+ """Commit point for the watchdog's stall observation.++ Revalidates the observed ``(generation, timestamp)`` pair+ under the SAME lock ``_touch_activity`` stamps the clock+ with, so a turn that resumed while the stall was being+ logged/emitted is never hard-cancelled (#95663 review):+ it continues and its lease keeps renewing. Returns False+ when the observation is stale (watchdog keeps sampling)+ or the turn is already winding down.++ Round-3 (#95663): the revalidated generation is carried+ into the interrupt path as a claim+ (``require_generation``); ``interrupt`` reserves it,+ consumes it and publishes the first interrupt state in+ ONE activity-lock critical section (round-6) and+ abandons the abort when it went stale.++ Round-4 (#95663): if ``interrupt`` raises, the abort+ declines FAIL-CLOSED — the exceptional path must not+ convert the inability to validate/publish the claim+ through the normal path into unconditional interrupt+ authority. No interrupt state is mutated here; the+ watchdog keeps sampling while the turn (which may have+ resumed) continues.+ """+ nonlocal durable_turn_lease_interrupt_message+ with self._liveness_activity_lock():+ current_generation = getattr(+ self, "_turn_liveness_activity_generation", 0+ )+ if (+ current_generation,+ getattr(self, "_last_activity_ts", None),+ ) != (snapshot.generation, snapshot.activity_ts):+ return False+ with durable_turn_lease_activity_lock:+ if (+ durable_turn_lease_stop.is_set()+ or not durable_turn_lease_turn_active+ ):+ return False+ try:+ published = self.interrupt(+ message,+ hard_cancel=True,+ require_generation=current_generation,+ )+ except Exception:+ # Round-4 (#95663): fail closed. An exceptional+ # interrupt path must not turn the inability to+ # validate/publish the generation claim into+ # unconditional abort authority — declining keeps+ # the watchdog sampling while the turn (which may+ # have resumed) continues.+ logger.debug(+ "Turn liveness abort interrupt raised; "+ "declining the abort",+ exc_info=True,+ )+ published = False+ if published is False:+ # The generation claim went stale between the+ # revalidation above and the hammer: real progress+ # landed in the window, so the abort abandons itself+ # and the watchdog keeps sampling while the turn+ # (and its lease) continue.+ return False+ with durable_turn_lease_activity_lock:+ durable_turn_lease_interrupt_message = message+ return True++ def _deactivate_turn_after_liveness_abort() -> None:+ """Stop lease renewal after a committed liveness abort.++ A wedge the hard interrupt cannot unwind must not keep+ the lease alive forever (the issue's "lease keeps+ renewing" masking); TTL expiry then lets stale-turn+ cleanup reclaim the row.+ """+ nonlocal durable_turn_lease_turn_active+ with durable_turn_lease_activity_lock:+ durable_turn_lease_stop.set()+ durable_turn_lease_turn_active = False+ def _turn_is_active() -> bool:+ with durable_turn_lease_activity_lock:+ return durable_turn_lease_turn_active++ def _refresh_durable_turn_lease() -> None:while not durable_turn_lease_stop.wait(_lease_refresh_interval):try:if not _turn_db.refresh_session_turn_lease(@@ -9126,6 +9376,20 @@ class AIAgent:name="session-turn-lease-refresh",daemon=True,)+ if _liveness_timeout is not None:+ durable_turn_liveness_thread = (+ turn_liveness.TurnLivenessWatchdog(+ self,+ session_id=getattr(self, "session_id", None) or session_id,+ timeout_s=_liveness_timeout,+ poll_s=_liveness_poll,+ stop_event=durable_turn_lease_stop,+ activity_lock=self._liveness_activity_lock(),+ is_turn_active=_turn_is_active,+ commit_abort=_commit_turn_liveness_abort,+ deactivate_turn=_deactivate_turn_after_liveness_abort,+ ).make_thread()+ )relay_lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(@@ -9173,7 +9437,19 @@ class AIAgent:if durable_turn_lease_thread is not None:with durable_turn_lease_activity_lock:durable_turn_lease_turn_active = True+ # Stamp the activity clock at turn entry (#95663+ # review): a real agent keeps ``_last_activity_ts``+ # across turns (idle time between turns is normal —+ # ``_reset_activity_labels_after_turn`` preserves+ # it by design), so without this stamp the liveness+ # watchdog would measure idle from the PREVIOUS+ # turn and force-abort a just-started turn on its+ # first poll whenever the agent had been idle longer+ # than the watchdog bound.+ self._touch_activity("starting new turn")durable_turn_lease_thread.start()+ if durable_turn_liveness_thread is not None:+ durable_turn_liveness_thread.start()result = run_conversation(self,user_message,@@ -9242,11 +9518,15 @@ class AIAgent:)finally:_stop_durable_turn_lease_refresher()- if (- durable_turn_lease_thread is not None- and durable_turn_lease_thread.is_alive()+ for _durable_thread in (+ durable_turn_lease_thread,+ durable_turn_liveness_thread,):- durable_turn_lease_thread.join(timeout=1.0)+ if (+ _durable_thread is not None+ and _durable_thread.is_alive()+ ):+ _durable_thread.join(timeout=1.0)# Clear any interrupt the refresher may have fired between# the inner stop and this join. Must run AFTER join so a# late interrupt does not survive into the next turn.diff --git a/tests/agent/test_turn_liveness.py b/tests/agent/test_turn_liveness.pynew file mode 100644index 00000000000..43dd0e5e4ec--- /dev/null+++ b/tests/agent/test_turn_liveness.py@@ -0,0 +1,139 @@+"""Unit coverage for agent/turn_liveness.py config resolution (#95548/#95663).++AGENTS.md rejects new non-secret ``HERMES_*`` env knobs: the watchdog's+behavioral settings live in ``agent.turn_liveness`` in config.yaml, and the+resolver must validate them — a typo must never crash durable-turn startup,+and NaN/Inf must never silently disable the timeout or freeze the watcher+thread.+"""++from __future__ import annotations++import logging++from agent.turn_liveness import (+ DEFAULT_TURN_LIVENESS_POLL_S,+ DEFAULT_TURN_LIVENESS_TIMEOUT_S,+ resolve_turn_liveness_settings,+)+++def test_defaults_when_config_missing_or_unset():+ # No config at all.+ assert resolve_turn_liveness_settings(None) == (+ DEFAULT_TURN_LIVENESS_TIMEOUT_S,+ DEFAULT_TURN_LIVENESS_POLL_S,+ )+ assert resolve_turn_liveness_settings({}) == (+ DEFAULT_TURN_LIVENESS_TIMEOUT_S,+ DEFAULT_TURN_LIVENESS_POLL_S,+ )+ # Section present but keys absent.+ assert resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {}}}+ ) == (DEFAULT_TURN_LIVENESS_TIMEOUT_S, DEFAULT_TURN_LIVENESS_POLL_S)+++def test_precedence_explicit_values_win_over_defaults():+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": 30, "poll_s": 5}}}+ )+ assert timeout == 30.0+ assert poll == 5.0+++def test_precedence_numeric_strings_accepted():+ # YAML may hand back strings; numeric coercion is part of the contract.+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": "45", "poll_s": "2.5"}}}+ )+ assert timeout == 45.0+ assert poll == 2.5+++def test_timeout_zero_is_documented_opt_out():+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": 0, "poll_s": 15}}}+ )+ assert timeout is None+ assert poll == 15.0+ # Negative is the same documented "disabled" path.+ assert resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": -1}}}+ )[0] is None+++def test_typo_does_not_crash_and_falls_back_to_default(caplog):+ # The old raw float() env parsing raised ValueError into durable-turn+ # startup on a typo. The resolver must warn + default instead.+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": "oops", "poll_s": "typo"}}}+ )+ assert timeout == DEFAULT_TURN_LIVENESS_TIMEOUT_S+ assert poll == DEFAULT_TURN_LIVENESS_POLL_S+ assert len(caplog.records) == 2+ assert all("agent.turn_liveness" in r.getMessage() for r in caplog.records)+++def test_nan_timeout_falls_back_to_default_not_disabled(caplog):+ # float("nan") > 0 is False, so the old code silently disabled the+ # watchdog on NaN. The resolver must reject it and keep the default.+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": float("nan")}}}+ )+ assert timeout == DEFAULT_TURN_LIVENESS_TIMEOUT_S # NOT None+ assert poll == DEFAULT_TURN_LIVENESS_POLL_S+ assert len(caplog.records) == 1+++def test_inf_poll_falls_back_to_default_not_frozen_watcher(caplog):+ # float("inf") poll made Event.wait(inf) hang the watcher thread+ # forever. The resolver must reject it.+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ timeout, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"poll_s": float("inf")}}}+ )+ assert timeout == DEFAULT_TURN_LIVENESS_TIMEOUT_S+ assert poll == DEFAULT_TURN_LIVENESS_POLL_S+ assert len(caplog.records) == 1+++def test_inf_timeout_falls_back_to_default(caplog):+ # inf timeout would never fire (idle < inf always true) — silent+ # disablement. Rejected.+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ timeout, _ = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"timeout_s": float("inf")}}}+ )+ assert timeout == DEFAULT_TURN_LIVENESS_TIMEOUT_S+ assert len(caplog.records) == 1+++def test_non_positive_poll_falls_back_to_default(caplog):+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ _, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"poll_s": 0}}}+ )+ assert poll == DEFAULT_TURN_LIVENESS_POLL_S+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ _, poll = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": {"poll_s": -3}}}+ )+ assert poll == DEFAULT_TURN_LIVENESS_POLL_S+++def test_malformed_sections_fall_back_to_defaults(caplog):+ # Non-dict `agent` or non-dict `turn_liveness` must not raise.+ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ result = resolve_turn_liveness_settings({"agent": "nonsense"})+ assert result == (DEFAULT_TURN_LIVENESS_TIMEOUT_S, DEFAULT_TURN_LIVENESS_POLL_S)++ with caplog.at_level(logging.WARNING, logger="agent.turn_liveness"):+ result = resolve_turn_liveness_settings(+ {"agent": {"turn_liveness": "nonsense"}}+ )+ assert result == (DEFAULT_TURN_LIVENESS_TIMEOUT_S, DEFAULT_TURN_LIVENESS_POLL_S)+ # The malformed section itself is surfaced as a warning.+ assert len(caplog.records) >= 1diff --git a/tests/run_agent/test_turn_liveness_watchdog.py b/tests/run_agent/test_turn_liveness_watchdog.pynew file mode 100644index 00000000000..d1896401769--- /dev/null+++ b/tests/run_agent/test_turn_liveness_watchdog.py@@ -0,0 +1,764 @@+"""Turn liveness watchdog (#95548): force-abort turns that stall silently.++Regression coverage for the gateway turn hang reported in #95548: a turn can+stall in the middle (observed between "model returned tool_calls" and tool+execution) with no error logged, no further progress, and the durable turn+lease kept renewing — so nothing ever force-aborts it and the session is+stuck until the gateway process is killed.++The fix adds a turn liveness watchdog next to the durable lease refresher in+``AIAgent.run_conversation`` (policy lives in ``agent/turn_liveness.py``).+It keys off the agent's activity clock (``_last_activity_ts`` — the #72039+single progress source, which lease renewal never touches). When a turn+shows no observable progress for the configured bound+(``agent.turn_liveness.timeout_s`` in config.yaml), it:++1. logs the stall loudly (surface instead of silent blocking),+2. force-interrupts the turn so it unwinds as an interrupted turn,+3. stops lease renewal so the durable lease lapses and stale-turn cleanup+ can reclaim the session even if the hard interrupt cannot unwind a+ truly wedged loop.++The abort is bound to the sampled ``(activity_generation, timestamp)`` pair+and revalidated at the commit point under the lock shared with+``_touch_activity`` (#95663 review): a turn that resumes while the stall is+being surfaced continues running and its lease keeps renewing.+"""++from __future__ import annotations++import logging+import threading+import time++import pytest++from run_agent import AIAgent+++class _DB:+ def __init__(self, session_exists=True, acquire_result=True):+ self.events = []+ self.refresh_times = []+ self.session_exists = session_exists+ self.acquire_result = acquire_result++ def get_session(self, session_id):+ return {"id": session_id} if self.session_exists else None++ def acquire_session_turn_lease(self, session_id, holder, **kwargs):+ self.events.append(("acquire", session_id, holder))+ on_wait = kwargs.get("on_wait")+ if on_wait is not None and self.acquire_result is False:+ on_wait(0.0)+ return self.acquire_result++ def resolve_resume_session_id(self, session_id):+ self.events.append(("resolve", session_id))+ return session_id++ def get_messages_as_conversation(self, session_id, **kwargs):+ self.events.append(("reload", session_id, kwargs))+ return [{"role": "user", "content": "durable latest"}]++ def refresh_session_turn_lease(self, session_id, holder, **kwargs):+ self.events.append(("refresh", session_id, holder))+ self.refresh_times.append(time.time())+ return True++ def release_session_turn_lease(self, session_id, holder):+ self.events.append(("release", session_id, holder))+++class _BlockingCommitFence:+ """Controllable compression commit fence for the round-4 witness.++ ``cancel_before_commit`` parks the interrupt thread AFTER it has passed+ the internal ``require_generation`` comparison, simulating the unbounded+ compression-commit wait. The test resumes the turn (``_touch_activity``)+ while the hammer is parked and then releases the fence; a correct+ interrupt must abandon itself without publishing anything.+ """++ def __init__(self):+ self.entered = threading.Event()+ self.release = threading.Event()+ self.calls = 0++ def cancel_before_commit(self, cancel_event=None):+ # The round-3 code passes the hard-stop Event; the round-4 code+ # passes nothing (publication moved to the final claim edge).+ # Accept both so the same witness is valid across the transition.+ self.calls += 1+ self.entered.set()+ assert self.release.wait(10.0), "fence was never released"+ return True+++class _ParkingReleaseLock:+ """Activity-lock wrapper that parks the releasing thread at one exact+ release boundary, so a test can deterministically land real activity+ on a competing thread in the precise window under test (#95663+ round-6 review: the consume→publication boundary).++ ``park_on_release=N`` parks the thread that performs the Nth release+ AFTER the inner lock has actually been released — so the competing+ thread can immediately acquire and stamp the clock while the parked+ thread has not yet executed its next statement.+ """++ def __init__(self, inner):+ self._inner = inner+ self.park_on_release = None+ self.release_count = 0+ self.parked = threading.Event()+ self.release_park = threading.Event()++ def __enter__(self):+ return self._inner.__enter__()++ def __exit__(self, *exc_info):+ result = self._inner.__exit__(*exc_info)+ self.release_count += 1+ if (+ self.park_on_release is not None+ and self.release_count == self.park_on_release+ ):+ self.parked.set()+ assert self.release_park.wait(10.0), (+ "parked activity-lock release was never released"+ )+ return result+++def _agent_with_db(db, *, session_id="stalled-session", platform="desktop"):+ agent = AIAgent.__new__(AIAgent)+ agent.session_id = session_id+ agent.platform = platform+ agent.model = "test-model"+ agent._session_db = db+ agent._session_db_created = True+ agent._persist_disabled = False+ agent._parent_session_id = None+ agent._relay_pending_turn_id = None+ agent._reset_activity_labels_after_turn = lambda: None+ agent._conversation_root_id = lambda: session_id+ agent.log_prefix = ""+ agent._vprint = lambda *a, **k: None+ agent.status_callback = None+ agent._interrupt_requested = False+ agent._interrupt_message = None+ agent._pending_redirect = None+ agent._execution_thread_id = None+ agent._interrupt_thread_signal_pending = False+ agent._hard_interrupt_requested = threading.Event()+ agent._active_children_lock = threading.Lock()+ agent._active_children = set()+ agent.quiet_mode = True+ # A real cached agent entering a new turn holds the activity clock+ # from its PREVIOUS turn: `_reset_activity_labels_after_turn` keeps+ # `_last_activity_ts` across turns by design, so an agent that sat+ # idle longer than the watchdog bound (user walked away, came back,+ # sent a message) enters with a STALE clock. `AIAgent.run_conversation`+ # stamps the clock at turn entry (#95663 review), so the watchdog+ # measures idle from THIS turn's start — mirror that reality: stale+ # entry clock, fresh measurement after the wrapper's turn-entry stamp.+ agent._last_activity_ts = time.time() - 1000.0+ agent._last_activity_desc = "previous turn (idle)"+ agent._session_turn_lease_refresh_interval = 60.0+ return agent+++def watchdog_config(monkeypatch):+ """Arm the watchdog fast through config.yaml — the only supported surface.++ `agent.turn_liveness` is the config authority the watchdog resolves+ (AGENTS.md rejects new non-secret HERMES_* env knobs); the resolver in+ agent/turn_liveness.py validates the values and the env is never read.+ """+ import hermes_cli.config as config_module++ monkeypatch.setattr(+ config_module,+ "load_config_readonly",+ lambda: {+ "agent": {+ "turn_liveness": {"timeout_s": 0.3, "poll_s": 0.05},+ }+ },+ )+ return monkeypatch+++def _run_turn(agent, inner_loop, monkeypatch):+ """Drive AIAgent.run_conversation with a fake inner conversation loop."""+ from agent import conversation_loop as loop_module++ monkeypatch.setattr(loop_module, "run_conversation", inner_loop)+ return AIAgent.run_conversation(+ agent,+ "new message",+ conversation_history=[{"role": "user", "content": "stale"}],+ )+++def test_watchdog_force_aborts_silently_stalled_turn(watchdog_config, monkeypatch, caplog):+ """A turn with zero observable progress past the bound is surfaced and+ force-aborted as an interrupted turn instead of hanging forever."""+ db = _DB()+ agent = _agent_with_db(db)++ interrupt_seen = {}+ t_start = time.time()++ def stalled_loop(_agent, _message, _system, history, *_args, **_kwargs):+ # Simulate the #95548 zombie: the loop makes no progress and never+ # touches the activity clock. It only notices the watchdog's+ # hard interrupt (real wedges may not even do that — see the lease+ # test below).+ while not _agent._interrupt_requested:+ if time.time() - t_start > 10:+ break+ time.sleep(0.005)+ interrupt_seen["at"] = time.time()+ interrupt_seen["message"] = _agent._interrupt_message+ return {+ "final_response": "aborted",+ "messages": history,+ "api_calls": 0,+ "completed": False,+ "interrupted": True,+ }++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, stalled_loop, monkeypatch)++ elapsed = time.time() - t_start++ # The turn was surfaced as interrupted, not hung.+ assert result["interrupted"] is True+ assert result["final_response"] == "aborted"+ # The watchdog fired before our 10s outer bound, and after the 0.3s idle+ # bound (poll interval makes the exact fire instant approximate).+ assert 0.2 <= elapsed < 10.0+ # The stall was logged loudly with the session named.+ assert any(+ "Turn liveness watchdog fired" in record.getMessage()+ and "stalled-session" in record.getMessage()+ for record in caplog.records+ )+ # The interrupt message tells the UI why the turn ended.+ assert agent._interrupt_message is None # cleared by the wrapper's finally+ assert "no progress" in (interrupt_seen.get("message") or "") # watchdog fired+ # The durable lease was released on the interrupted exit path.+ assert db.events[-1][0] == "release"+ assert db.events[-1][1] == "stalled-session"+++def test_watchdog_does_not_fire_while_turn_still_making_progress(+ watchdog_config, monkeypatch, caplog+):+ """A turn that keeps touching the activity clock (API waits, stream+ tokens, tool heartbeats, tool completions) is never force-aborted, and+ the lease keeps renewing normally."""+ db = _DB()+ agent = _agent_with_db(db)+ # Fast lease refresh so the test can prove renewal stayed alive.+ agent._session_turn_lease_refresh_interval = 0.05+ t_start = time.time()++ def busy_loop(_agent, _message, _system, history, *_args, **_kwargs):+ # Keep making progress well past the 0.3s idle bound.+ while time.time() - t_start < 0.6:+ _agent._touch_activity("test tick")+ time.sleep(0.02)+ return {+ "final_response": "done",+ "messages": history,+ "api_calls": 1,+ "completed": True,+ }++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, busy_loop, monkeypatch)++ assert result["completed"] is True+ assert result.get("interrupted") is not True+ assert agent._interrupt_requested is False+ assert not any(+ "Turn liveness watchdog fired" in record.getMessage()+ for record in caplog.records+ )+ # The lease refresher ran during the turn — renewal is orthogonal to the+ # watchdog and continued while the turn was alive.+ assert len(db.refresh_times) >= 1+++def test_watchdog_stops_lease_renewal_when_interrupt_cannot_unwind_wedge(+ watchdog_config, monkeypatch+):+ """The issue's 'lease keeps renewing' masking: even when the hard+ interrupt cannot immediately unwind the loop (a truly wedged frame), the+ watchdog stops renewing the durable lease so TTL expiry lets stale-turn+ cleanup reclaim the session."""+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.05+ t_start = time.time()+ fire_ts = {}++ def wedged_loop(_agent, _message, _system, history, *_args, **_kwargs):+ # Notice the interrupt but keep "wedging" (no activity) for another+ # half second — simulating a blocked frame the interrupt cannot free+ # immediately.+ while not _agent._interrupt_requested:+ if time.time() - t_start > 10:+ break+ time.sleep(0.005)+ fire_ts["at"] = time.time()+ while time.time() - fire_ts["at"] < 0.5:+ time.sleep(0.005)+ return {+ "final_response": "recovered",+ "messages": history,+ "api_calls": 0,+ "completed": True,+ }++ result = _run_turn(agent, wedged_loop, monkeypatch)+ assert result["completed"] is True+ assert time.time() - t_start < 10.0++ # The watchdog fired during the wedge.+ assert "at" in fire_ts+ # Once the watchdog fired, lease renewal stopped: refreshes cadence at+ # 0.05s would have produced ~8 more events in the 0.5s post-fire wedge if+ # renewal had continued. Tolerate only in-flight refreshes racing the+ # stop (<= 0.15s window).+ late_refreshes = [+ t for t in db.refresh_times if t > fire_ts["at"] + 0.15+ ]+ assert late_refreshes == [], (+ f"lease renewal continued after watchdog fired: {len(late_refreshes)} "+ "post-fire refreshes"+ )+ # The lease row was still released when the turn finally unwound.+ assert [e[0] for e in db.events][-1] == "release"+++def test_watchdog_declines_abort_when_activity_resumes_during_warning(+ watchdog_config, monkeypatch, caplog+):+ """#95663 review race: the watchdog sampled a stale activity clock, then+ the turn resumed while the stall was being logged/emitted — before the+ abort commits. The commit point revalidates the observed+ (generation, timestamp) pair under the lock shared with+ `_touch_activity`, so the turn continues and its lease keeps renewing+ instead of being hard-cancelled mid-recovery."""+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.05+ resume_event = threading.Event()+ touched_event = threading.Event()+ t_start = time.time()+ interrupt_seen = {}++ def stalled_then_resumed_loop(_agent, _message, _system, history, *_a, **_k):+ # Stall (zero activity) until the watchdog surfaces the stall. The+ # warning delivery itself is what unblocks the wedge: the turn+ # resumes DURING the warning window, before the commit point.+ assert resume_event.wait(10.0)+ _agent._touch_activity("turn resumed")+ touched_event.set()+ # Keep the turn alive a while so lease renewal is observable.+ while time.time() - t_start < 0.8:+ _agent._touch_activity("still alive")+ time.sleep(0.02)+ # Capture DURING the turn — the wrapper's finally clears any+ # interrupt after the loop returns, so post-run assertions on the+ # agent's interrupt state cannot prove the abort never happened.+ interrupt_seen["requested"] = _agent._interrupt_requested+ interrupt_seen["message"] = _agent._interrupt_message+ return {+ "final_response": "recovered",+ "messages": history,+ "api_calls": 1,+ "completed": True,+ }++ def blocking_warning(_message):+ # Mirrors _emit_warning: the stall warning is being delivered when+ # the turn resumes. Hold the window open until the resumed activity+ # has definitively landed on the clock, so the commit revalidation+ # runs against the new generation.+ resume_event.set()+ assert touched_event.wait(10.0)++ agent._emit_warning = blocking_warning++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, stalled_then_resumed_loop, monkeypatch)++ assert time.time() - t_start < 10.0+ # The turn resumed and completed normally — it was NOT hard-cancelled+ # mid-flight (the commit point declined the stale observation).+ assert result["completed"] is True+ assert result.get("interrupted") is not True+ assert interrupt_seen.get("requested") is False, (+ f"turn was hard-interrupted while resumed: {interrupt_seen!r}"+ )+ # The stall was still surfaced loudly (so the regression isn't a+ # vacuous pass from the watchdog never sampling)…+ assert any(+ "Turn liveness watchdog fired" in record.getMessage()+ and "stalled-session" in record.getMessage()+ for record in caplog.records+ )+ # …and the lease kept renewing through the resumed turn.+ assert len(db.refresh_times) >= 1+ assert db.events[-1][0] == "release"+++def test_watchdog_declines_abort_when_activity_resumes_after_revalidation(+ watchdog_config, monkeypatch, caplog+):+ """#95663 round-3 review race: the commit point revalidates the observed+ (generation, timestamp) pair under the activity lock and then releases+ it before the hard interrupt. Real progress landing in that+ post-revalidation window published a new generation yet was still+ hard-cancelled by the already-authorized abort. The abort now carries+ its revalidated generation into the interrupt path, which re-compares+ it against the live clock at the last instant before the hammer and+ abandons the stale claim — the turn continues and its lease keeps+ renewing."""+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.05+ t_start = time.time()+ interrupt_seen = {}+ injected = {"count": 0}++ real_interrupt = agent.interrupt++ def intercepting_interrupt(+ message=None,+ *,+ hard_cancel=False,+ tool_reason=None,+ require_generation=None,+ ):+ # Deterministically land real progress in the exact+ # post-revalidation / pre-interrupt window: every abort hammer+ # attempt is preceded by a fresh activity stamp on the clock.+ injected["count"] += 1+ agent._touch_activity("resumed after revalidation")+ if require_generation is not None:+ return real_interrupt(+ message,+ hard_cancel=hard_cancel,+ tool_reason=tool_reason,+ require_generation=require_generation,+ )+ return real_interrupt(+ message, hard_cancel=hard_cancel, tool_reason=tool_reason+ )++ agent.interrupt = intercepting_interrupt++ def stalled_loop(_agent, _message, _system, history, *_args, **_kwargs):+ # Stall without touching the clock: the watchdog fires and tries to+ # abort; the interceptor above injects the resumed activity at the+ # commit's hammer point. Keep the turn alive long enough for the+ # abort decision to play out and record whether the interrupt was+ # ever published.+ while time.time() - t_start < 1.0:+ if _agent._interrupt_requested:+ interrupt_seen["requested"] = True+ break+ time.sleep(0.005)+ # Capture DURING the turn — the wrapper's finally clears interrupt+ # state after the loop returns.+ if "requested" not in interrupt_seen:+ interrupt_seen["requested"] = _agent._interrupt_requested+ interrupt_seen["message"] = _agent._interrupt_message+ return {+ "final_response": "recovered",+ "messages": history,+ "api_calls": 1,+ "completed": True,+ }++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, stalled_loop, monkeypatch)++ assert time.time() - t_start < 10.0+ # The window was really hit: the interceptor's injected activity ran.+ assert injected["count"] >= 1+ # The turn resumed and completed normally — the stale abort claim was+ # abandoned instead of hard-cancelling the resumed turn.+ assert result["completed"] is True+ assert result.get("interrupted") is not True+ assert interrupt_seen.get("requested") is False, (+ f"turn was hard-interrupted although activity resumed after "+ f"revalidation: {interrupt_seen!r}"+ )+ # The stall was still surfaced loudly…+ assert any(+ "Turn liveness watchdog fired" in record.getMessage()+ and "stalled-session" in record.getMessage()+ for record in caplog.records+ )+ # …and the lease kept renewing through the resumed turn.+ assert len(db.refresh_times) >= 1+ assert db.events[-1][0] == "release"+++def test_watchdog_declines_abort_when_activity_resumes_inside_interrupt_publication(+ watchdog_config, monkeypatch, caplog+):+ """#95663 round-4 review race: the generation claim must survive every+ blocking boundary inside ``interrupt()`` — including the compression+ commit fence — and be consumed at the final mutation edge, immediately+ before the first observable publication.++ The witness parks ``interrupt()`` inside a controllable+ ``cancel_before_commit`` AFTER its internal generation comparison+ passed, resumes the turn with real progress (``_touch_activity``+ publishes generation G+1) while the hammer is parked, then releases the+ fence. The abort must abandon itself: no ``_interrupt_requested`` flag,+ no hard-cancel event, no tool signal, and the turn's lease keeps+ renewing.+ """+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.05+ fence = _BlockingCommitFence()+ agent._active_compression_commit_fence = fence+ t_start = time.time()+ published = {"requested": False, "hard_event": False, "tool_signal": False}++ def stalled_then_resumed_loop(_agent, _message, _system, history, *_a, **_k):+ # Stall (zero activity) until the watchdog's abort attempt is parked+ # inside the compression fence — i.e. AFTER interrupt() passed its+ # internal generation comparison. Then resume with real progress+ # while the hammer is mid-flight.+ assert fence.entered.wait(10.0), "interrupt never reached the fence"+ _agent._touch_activity("resumed inside interrupt publication window")+ fence.release.set()+ # Keep the turn making REAL progress while observing whether the+ # parked interrupt published anything. Continuous activity also+ # guarantees no NEW legitimate watchdog decision can fire, so any+ # publication observed here is attributable to the stale attempt.+ deadline = time.time() + 1.0+ while time.time() < deadline:+ _agent._touch_activity("still alive")+ if _agent._interrupt_requested or _agent._hard_interrupt_requested.is_set():+ break+ time.sleep(0.02)+ published["requested"] = _agent._interrupt_requested+ published["hard_event"] = _agent._hard_interrupt_requested.is_set()+ published["tool_signal"] = _agent._interrupt_thread_signal_pending+ published["message"] = _agent._interrupt_message+ return {+ "final_response": "recovered",+ "messages": history,+ "api_calls": 1,+ "completed": True,+ }++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, stalled_then_resumed_loop, monkeypatch)++ assert time.time() - t_start < 10.0+ # The window was really hit: the interrupt entered the fence exactly+ # once — the stale attempt declined and no retry ever fired.+ assert fence.calls == 1, f"unexpected fence admissions: {fence.calls}"+ # The resumed turn completed normally — the stale claim was abandoned+ # at the final mutation edge without publishing any interrupt state.+ assert result["completed"] is True+ assert result.get("interrupted") is not True+ assert published["requested"] is False, (+ f"_interrupt_requested published against stale generation: {published!r}"+ )+ assert published["hard_event"] is False, (+ f"hard-cancel event published against stale generation: {published!r}"+ )+ assert published["tool_signal"] is False, (+ f"tool interrupt signal published against stale generation: {published!r}"+ )+ assert published["message"] is None+ # The stall was still surfaced loudly…+ assert any(+ "Turn liveness watchdog fired" in record.getMessage()+ and "stalled-session" in record.getMessage()+ for record in caplog.records+ )+ # …and the lease kept renewing through the resumed turn.+ assert len(db.refresh_times) >= 1+ assert db.events[-1][0] == "release"+++def test_watchdog_declines_abort_when_interrupt_publish_raises(+ watchdog_config, monkeypatch, caplog+):+ """#95663 round-4 review: the exceptional interrupt path must not+ convert an unvalidated generation claim into direct interrupt-flag+ mutation. When ``interrupt()`` raises, the abort declines fail-closed —+ no ``_interrupt_requested`` / ``_interrupt_message`` is set, the+ watchdog keeps sampling, and the turn's lease keeps renewing.+ """+ db = _DB()+ agent = _agent_with_db(db)+ agent._session_turn_lease_refresh_interval = 0.05+ t_start = time.time()+ raised = {"count": 0}+ seen = {"requested": False, "message": None}++ def raising_interrupt(+ message=None,+ *,+ hard_cancel=False,+ tool_reason=None,+ require_generation=None,+ ):+ raised["count"] += 1+ raise RuntimeError("synthetic interrupt publication failure")++ agent.interrupt = raising_interrupt++ def stalled_loop(_agent, _message, _system, history, *_args, **_kwargs):+ # Stall so the watchdog fires; every abort attempt raises inside+ # interrupt(). Run a fixed window while recording whether the+ # exception fallback published interrupt state anyway.+ while time.time() - t_start < 1.0:+ seen["requested"] = _agent._interrupt_requested+ seen["message"] = _agent._interrupt_message+ if _agent._interrupt_requested:+ break+ time.sleep(0.005)+ seen["requested"] = _agent._interrupt_requested+ seen["message"] = _agent._interrupt_message+ return {+ "final_response": "recovered",+ "messages": history,+ "api_calls": 1,+ "completed": True,+ }++ with caplog.at_level(logging.ERROR, logger="agent.turn_liveness"):+ result = _run_turn(agent, stalled_loop, monkeypatch)++ assert time.time() - t_start < 10.0+ # The exceptional abort attempt really happened inside the window.+ assert raised["count"] >= 1+ # The turn completed without being interrupted…+ assert result["completed"] is True+ assert result.get("interrupted") is not True+ # …and the exception fallback published NOTHING: fail-closed, no flag,+ # no message.+ assert seen["requested"] is False, (+ f"exception fallback mutated interrupt state: {seen!r}"+ )+ assert seen["message"] is None+ # The stall was surfaced loudly (the watchdog really fired)…+ assert any(+ "Turn liveness watchdog fired" in record.getMessage()+ and "stalled-session" in record.getMessage()+ for record in caplog.records+ )+ # …and the lease kept renewing because the abort was declined.+ assert len(db.refresh_times) >= 1+ assert db.events[-1][0] == "release"+++def test_interrupt_consumes_claim_and_publishes_first_state_atomically():+ """#95663 round-6 review race: claim consumption and the first+ interrupt publication must be ONE activity-lock critical section.++ The round-4 tree consumed the generation claim under the activity+ lock, released it, and only then published ``_interrupt_requested``+ / ``_interrupt_message`` / ``_tool_interrupt_reason`` — so a turn+ that resumed in that window (real progress, G+1) was still+ hard-cancelled by the already-consumed claim. This witness parks+ the interrupt thread exactly at the claim-publication boundary (the+ Nth activity-lock release), publishes real activity on a competing+ thread while the hammer is parked, and asserts the total order: any+ interrupt publication must have committed under the lock BEFORE the+ competing activity stamp. Publishing AFTER it is the round-6 defect+ and makes this test red on that tree.+ """+ agent = AIAgent.__new__(AIAgent)+ agent._turn_liveness_activity_generation = 5+ agent._turn_liveness_abort_claim = None+ agent._interrupt_requested = False+ agent._interrupt_message = None+ agent._tool_interrupt_reason = None+ agent._hard_interrupt_requested = threading.Event()+ agent._execution_thread_id = None+ agent._active_children_lock = threading.Lock()+ agent._active_children = set()+ agent.quiet_mode = True++ parking_lock = _ParkingReleaseLock(threading.Lock())+ # Release #1 is the claim RESERVATION at interrupt() entry; release+ # #2 is the CONSUME on the round-4 tree / the atomic+ # consume+publication critical section on the repaired tree. Parking+ # on release #2 puts the competing activity exactly at the+ # claim-publication boundary under test.+ parking_lock.park_on_release = 2+ agent._turn_liveness_activity_lock = parking_lock++ result = {}++ def interrupt_fn():+ result["ret"] = AIAgent.interrupt(+ agent,+ "watchdog: no progress",+ hard_cancel=True,+ tool_reason="turn liveness watchdog fired",+ require_generation=5,+ )++ interrupt_thread = threading.Thread(target=interrupt_fn)+ interrupt_thread.start()+ assert parking_lock.parked.wait(10.0), (+ "interrupt never reached the claim-publication boundary"+ )++ # Real progress lands on a competing thread while the hammer is+ # parked: the activity clock advances to generation G+1 (6).+ touched = threading.Event()++ def turn_fn():+ agent._touch_activity("turn resumed")+ touched.set()++ turn_thread = threading.Thread(target=turn_fn)+ turn_thread.start()+ assert touched.wait(10.0), "competing activity never landed"++ def _published():+ return (+ agent._interrupt_requested+ or agent._interrupt_message is not None+ or agent._tool_interrupt_reason is not None+ or agent._hard_interrupt_requested.is_set()+ )++ # The window was really hit: the claim was consumed and the+ # competing activity advanced the generation.+ assert agent._turn_liveness_abort_claim is None+ assert agent._turn_liveness_activity_generation == 6++ published_before_activity = _published()+ parking_lock.release_park.set()+ interrupt_thread.join(10.0)+ turn_thread.join(10.0)+ published_after = _published()++ assert result.get("ret") is True+ assert not (published_after and not published_before_activity), (+ "interrupt state published after competing activity landed: "+ f"before={published_before_activity}, after={published_after}"+ )