Skip to content

The agent that grows with you

fix(agent): system watchdog interrupts are attributed to their issuer, not the user

teknium16a99766424f4
diff --git a/agent/interrupt_control.py b/agent/interrupt_control.py
index ced3a701752..067c36ee6d6 100644
--- a/agent/interrupt_control.py
+++ b/agent/interrupt_control.py
@@ -15,6 +15,22 @@ from tools.interrupt import set_interrupt as _set_interrupt
# Same logger name as the origin module so log records / caplog filters are unchanged.
logger = logging.getLogger("run_agent")
+# ``interrupt()`` categories that mean a human stopped the turn. Any other ``_tool_interrupt_reason`` was
+# supplied by a system producer via ``tool_reason`` (watchdogs, lease loss, lifecycle cancellation) and is
+# attributed to it in the turn exit reason instead of being booked as a user stop (#112647).
+_REASON_HARD_STOP = "explicit stop requested"
+_REASON_NEW_MESSAGE = "user sent a new message"
+_REASON_USER_INTERRUPT = "user interrupt"
+USER_INTERRUPT_REASONS = frozenset({_REASON_HARD_STOP, _REASON_NEW_MESSAGE, _REASON_USER_INTERRUPT})
+
+
+def interrupt_issuer(agent) -> Optional[str]:
+ """Slug of the system producer behind the pending interrupt, or ``None`` for a human stop."""
+ reason = getattr(agent, "_tool_interrupt_reason", None)
+ if not reason or reason in USER_INTERRUPT_REASONS:
+ return None
+ return str(reason).strip().replace(" ", "_")
+
def _fence_cancel_before_commit(fence, *, when_in_flight: bool, failure_log: str) -> None:
"""Call ``type(fence).cancel_before_commit(fence)`` when ``commit_in_flight`` matches.
@@ -112,14 +128,16 @@ class InterruptControlMixin:
# Tool cancellation attribution stays separate from _interrupt_message, which may carry the user's
# full next message.
tool_interrupt_reason = (
- (tool_reason or "explicit stop requested") if hard_cancel
- else ("user sent a new message" if message else "user interrupt")
+ (tool_reason or _REASON_HARD_STOP) if hard_cancel
+ else (_REASON_NEW_MESSAGE if message else _REASON_USER_INTERRUPT)
)
def _publish_interrupt_state() -> None:
self._interrupt_requested = True
self._interrupt_message = message
self._tool_interrupt_reason = tool_interrupt_reason
+ # The turn record and the log must agree on WHO asked for the stop (#112647).
+ logger.info("Interrupt requested (%s): %s", "hard" if hard_cancel else "soft", tool_interrupt_reason)
_hard_event = getattr(self, "_hard_interrupt_requested", None) if hard_cancel else None
if _hard_event is not None:
_hard_event.set()
diff --git a/agent/turn_explainers.py b/agent/turn_explainers.py
index eadc4935409..f81faf5c25d 100644
--- a/agent/turn_explainers.py
+++ b/agent/turn_explainers.py
@@ -39,10 +39,6 @@ _EXIT_REASON_EXPLANATIONS: Dict[str, str] = {
"no new content was produced this turn; showing recovered "
"prior context. Send `continue` to retry."
),
- "interrupted_during_api_call": (
- "the request was interrupted mid-call before a reply was "
- "received. Send `continue` to retry."
- ),
"redirect_restart_limit_exceeded": (
"the request was cancelled by a new correction on every attempt, "
"so the turn stopped instead of retrying forever. Your last "
@@ -70,6 +66,11 @@ _EXIT_REASON_EXPLANATIONS: Dict[str, str] = {
# Parameterised reasons (``max_iterations_reached(3/3)`` …) matched by prefix.
_EXIT_REASON_PREFIX_EXPLANATIONS = (
+ # ``interrupted_during_api_call(<issuer>)`` names a system watchdog (#112647).
+ ("interrupted_during_api_call", (
+ "the request was interrupted mid-call before a reply was "
+ "received. Send `continue` to retry."
+ )),
("max_iterations_reached", (
"the maximum tool-iteration limit was reached before a "
"final answer. Send `continue` to keep going, or raise "
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index 5f60e934836..520c443c4da 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -17,6 +17,9 @@ from typing import Any, Dict, List, Optional
# Same logger name as the origin module so log records / caplog filters are unchanged.
logger = logging.getLogger("run_agent")
+# ``tool_reason`` for a lost session turn lease: attributes the stop to the lease, not the user (#112647).
+_REASON_LEASE_LOST = "session turn lease lost"
+
LEASE_TTL_SECONDS = 300.0
LEASE_WAIT_SECONDS = 1800.0
@@ -117,10 +120,11 @@ class DurableTurnLease:
return
self.interrupt_message = message
try:
- self.agent.interrupt(message, hard_cancel=True)
+ self.agent.interrupt(message, hard_cancel=True, tool_reason=_REASON_LEASE_LOST)
except Exception:
self.agent._interrupt_requested = True
self.agent._interrupt_message = message
+ self.agent._tool_interrupt_reason = _REASON_LEASE_LOST
def commit_liveness_abort(self, snapshot, message: str) -> bool:
"""Commit point for the watchdog's stall observation.
@@ -142,7 +146,8 @@ class DurableTurnLease:
return False
try:
published = agent.interrupt(
- message, hard_cancel=True, require_generation=current_generation
+ message, hard_cancel=True, tool_reason="turn liveness watchdog",
+ require_generation=current_generation,
)
except Exception:
logger.debug("Turn liveness abort interrupt raised; declining the abort", exc_info=True)
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.py
index 7fb1cf19afb..950f1ed6a16 100644
--- a/agent/turn_iteration_prep.py
+++ b/agent/turn_iteration_prep.py
@@ -17,6 +17,7 @@ from dataclasses import dataclass
from typing import Any, Dict
from agent.display import KawaiiSpinner
+from agent.interrupt_control import interrupt_issuer
from agent.turn_context_compaction import _reanchor
logger = logging.getLogger("agent.conversation_loop")
@@ -329,7 +330,8 @@ def begin_iteration(
if agent._interrupt_requested:
interrupted = True
- _turn_exit_reason = "interrupted_by_user"
+ _issuer = interrupt_issuer(agent)
+ _turn_exit_reason = f"interrupted_by_system({_issuer})" if _issuer else "interrupted_by_user"
if not agent.quiet_mode:
agent._safe_print("\n⚡ Breaking out of tool loop due to interrupt...")
return _verdict("break")
@@ -437,7 +439,10 @@ def apply_retry_restarts(
return _verdict("continue")
if interrupted:
- _turn_exit_reason = "interrupted_during_api_call"
+ _issuer = interrupt_issuer(agent)
+ _turn_exit_reason = (
+ f"interrupted_during_api_call({_issuer})" if _issuer else "interrupted_during_api_call"
+ )
return _verdict("break")
if _retry.restart_with_compressed_messages:
diff --git a/cron/scheduler.py b/cron/scheduler.py
index d7cf8d38ca0..0bf5dd2aab0 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -1652,7 +1652,7 @@ def _raise_inactivity_timeout(agent, job_name: str, limit_s: float) -> None:
job_name, _secs_ago, limit_s,
_last_desc, _activity.get("api_call_count", 0), _activity.get("max_iterations", 0),
_activity.get("current_tool") or "none")
- request_hard_interrupt(agent, "Cron job timed out (inactivity)")
+ request_hard_interrupt(agent, "Cron job timed out (inactivity)", tool_reason="cron inactivity watchdog")
raise TimeoutError(
f"Cron job '{job_name}' idle for "
f"{int(_secs_ago)}s (limit {int(limit_s)}s) "
diff --git a/gateway/run.py b/gateway/run.py
index e3cdcdf6882..cf474612d5d 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2578,6 +2578,8 @@ def _dequeue_pending_event(adapter, session_key: str) -> MessageEvent | None:
_INTERRUPT_REASON_STOP = "Stop requested"
_INTERRUPT_REASON_RESET = "Session reset requested"
_INTERRUPT_REASON_TIMEOUT = "Execution timed out (inactivity)"
+# ``tool_reason`` for the inactivity timeout: attributes the stop to the gateway watchdog (#112647).
+_INTERRUPT_TOOL_REASON_TIMEOUT = "gateway inactivity watchdog"
_INTERRUPT_REASON_EVICTED = "Session ended while the turn was running"
_INTERRUPT_REASON_SSE_DISCONNECT = "SSE client disconnected"
_INTERRUPT_REASON_GATEWAY_SHUTDOWN = "Gateway shutting down"
@@ -2673,7 +2675,7 @@ def _abandon_timed_out_gateway_turn(
agent = agent_holder[0] if agent_holder else None
if agent is not None:
try:
- request_hard_interrupt(agent, _INTERRUPT_REASON_TIMEOUT)
+ request_hard_interrupt(agent, _INTERRUPT_REASON_TIMEOUT, tool_reason=_INTERRUPT_TOOL_REASON_TIMEOUT)
except Exception:
logger.debug("Timed-out agent interrupt failed", exc_info=True)
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index cd37b52544b..144c782f45d 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -3398,7 +3398,7 @@ class GatewayTurnMixin:
def _run_agent_timeout_result(self, worker, turn_ctx: TurnContext) -> dict:
"""Synthetic failed run dict for an inactivity timeout, with the activity-tracker diagnostic;
interrupts the agent if it is still running so the thread pool worker is freed."""
- from gateway.run import _INTERRUPT_REASON_TIMEOUT, request_hard_interrupt
+ from gateway.run import _INTERRUPT_REASON_TIMEOUT, _INTERRUPT_TOOL_REASON_TIMEOUT, request_hard_interrupt
session_key, result_holder, tools_holder = turn_ctx.session_key, turn_ctx.result_holder, turn_ctx.tools_holder
_timed_out_agent = turn_ctx.agent_holder[0]
_activity = self._agent_activity_summary(_timed_out_agent)
@@ -3415,7 +3415,7 @@ class GatewayTurnMixin:
_cur_tool or "none",
)
if _timed_out_agent:
- request_hard_interrupt(_timed_out_agent, _INTERRUPT_REASON_TIMEOUT)
+ request_hard_interrupt(_timed_out_agent, _INTERRUPT_REASON_TIMEOUT, tool_reason=_INTERRUPT_TOOL_REASON_TIMEOUT)
_timeout_mins = int(worker.agent_timeout // 60) or 1
_iter_progress = format_iteration_progress(_iter_n, _iter_max)
_diag_lines = [
diff --git a/tests/agent/test_interrupt_issuer_attribution.py b/tests/agent/test_interrupt_issuer_attribution.py
new file mode 100644
index 00000000000..e3a63a43670
--- /dev/null
+++ b/tests/agent/test_interrupt_issuer_attribution.py
@@ -0,0 +1,58 @@
+"""``interrupt()`` records who asked for the stop, so the turn exit reason can attribute it (#112647).
+
+Every system watchdog reaches the agent through ``request_hard_interrupt(..., tool_reason=...)``;
+the published ``_tool_interrupt_reason`` is the single source the exit reason is derived from.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+
+from agent.interrupt_compat import request_hard_interrupt
+from agent.interrupt_control import interrupt_issuer
+from tools.interrupt import set_interrupt
+
+
+def _bare_agent():
+ from run_agent import AIAgent
+
+ agent = AIAgent.__new__(AIAgent)
+ 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._interrupt_thread_signal_pending = False
+ agent._active_children = []
+ agent._active_children_lock = threading.Lock()
+ agent.quiet_mode = True
+ return agent
+
+
+def test_system_producer_is_recorded_and_logged_at_publication(caplog):
+ """The cron/gateway watchdog shape: the issuer survives to ``interrupt_issuer`` and ONE log line
+ names it at the point ``_interrupt_requested`` is set."""
+ agent = _bare_agent()
+ try:
+ with caplog.at_level(logging.INFO, logger="run_agent"):
+ assert request_hard_interrupt(agent, "Cron job timed out (inactivity)", tool_reason="cron inactivity watchdog")
+ assert agent._interrupt_requested is True
+ assert interrupt_issuer(agent) == "cron_inactivity_watchdog"
+ published = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Interrupt requested")]
+ assert published == ["Interrupt requested (hard): cron inactivity watchdog"]
+ finally:
+ set_interrupt(False)
+
+
+def test_human_stops_have_no_system_issuer():
+ """A plain ``interrupt()`` and a reason-less hard stop (CLI/TUI /stop) stay attributed to the user."""
+ agent = _bare_agent()
+ try:
+ agent.interrupt()
+ assert interrupt_issuer(agent) is None
+ agent.clear_interrupt()
+ assert request_hard_interrupt(agent)
+ assert interrupt_issuer(agent) is None
+ finally:
+ set_interrupt(False)
diff --git a/tests/agent/test_turn_iteration_prep.py b/tests/agent/test_turn_iteration_prep.py
index b283f790d58..39cb320ea83 100644
--- a/tests/agent/test_turn_iteration_prep.py
+++ b/tests/agent/test_turn_iteration_prep.py
@@ -11,7 +11,7 @@ from types import SimpleNamespace
import pytest
-from agent.turn_iteration_prep import apply_retry_restarts
+from agent.turn_iteration_prep import apply_retry_restarts, begin_iteration
from agent.turn_retry_state import TurnRetryState
RESTART_FLAGS = ["restart_with_redirected_messages", "restart_with_rebuilt_messages"]
@@ -64,3 +64,29 @@ def test_restart_refunds_are_bounded_per_turn(flag):
assert verdicts[-1]._turn_exit_reason.endswith("restart_limit_exceeded")
# The correction that tripped the redirect cap is handed back as the next user turn.
assert agent.steered == (["last correction"] if flag == "restart_with_redirected_messages" else [])
+
+
+def _interrupted_agent(tool_interrupt_reason):
+ agent = SimpleNamespace(
+ _interrupt_requested=True, _tool_interrupt_reason=tool_interrupt_reason, quiet_mode=True,
+ _drain_pending_redirect=lambda: None, _checkpoint_mgr=SimpleNamespace(new_turn=lambda: None),
+ )
+ return begin_iteration(
+ agent, messages=[], conversation_history=[], original_user_message="hi",
+ api_call_count=0, interrupted=False, _turn_exit_reason="unknown",
+ )
+
+
[email protected]("tool_interrupt_reason, expected", [
+ # Human stops keep the historical reason (every ``interrupt()`` category, and a bare flag write).
+ ("explicit stop requested", "interrupted_by_user"),
+ ("user sent a new message", "interrupted_by_user"),
+ (None, "interrupted_by_user"),
+ # A producer that named itself via ``tool_reason`` is booked as the issuer (#112647).
+ ("cron inactivity watchdog", "interrupted_by_system(cron_inactivity_watchdog)"),
+ ("turn liveness watchdog", "interrupted_by_system(turn_liveness_watchdog)"),
+])
+def test_interrupt_exit_reason_names_the_system_issuer(tool_interrupt_reason, expected):
+ """A watchdog abort must not be recorded as a user stop: the exit reason carries the issuer."""
+ verdict = _interrupted_agent(tool_interrupt_reason)
+ assert (verdict.action, verdict.interrupted, verdict._turn_exit_reason) == ("break", True, expected)
diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.md
index 3d1d82cd6be..fdf060b0483 100644
--- a/website/docs/developer-guide/programmatic-integration.md
+++ b/website/docs/developer-guide/programmatic-integration.md
@@ -177,7 +177,7 @@ The terminal status of a run is derived from how the agent's turn actually ended
| Turn outcome | Status | Terminal event | Flags on the event / status |
|---|---|---|---|
| Final answer produced | `completed` | `run.completed` | `completed: true` |
-| Interrupted (`/stop`, or an interrupt inside the agent) | `cancelled` | `run.cancelled` | `completed: false`, `interrupted: true` |
+| Interrupted (`/stop`, or an interrupt inside the agent) | `cancelled` | `run.cancelled` | `completed: false`, `interrupted: true`, `turn_exit_reason` naming the issuer — `interrupted_by_user` for a human stop, `interrupted_by_system(<issuer>)` / `interrupted_during_api_call(<issuer>)` when a watchdog (e.g. `cron_inactivity_watchdog`, `turn_liveness_watchdog`, `gateway_inactivity_watchdog`, `session_turn_lease_lost`) ended the turn |
| Provider/agent failure | `failed` | `run.failed` | `completed: false`, `error` |
| Ended without finishing (iteration budget, truncated or partial reply) | `failed` | `run.failed` | `completed: false`, `partial` when applicable, `turn_exit_reason` (e.g. `max_iterations_reached(60/60)`), `output` with any fallback text |