Skip to content

The agent that grows with you

fix(terminal): bound env.execute wait so a wedged poll cannot disable every timer

HexLab9885bc25c9498a
diff --git a/agent/deadline.py b/agent/deadline.py
index a2c5cbfe051..e3357f8a240 100644
--- a/agent/deadline.py
+++ b/agent/deadline.py
@@ -63,6 +63,7 @@ Design invariants:
from __future__ import annotations
import asyncio
+import contextvars
import faulthandler
import logging
import os
@@ -100,6 +101,12 @@ MAX_SAFE_TIMEOUT_S = 31_536_000.0 # 365 days
# is blocked in a synchronous call and dumping stacks (family A diagnostics).
_LOOP_BLOCKED_DUMP_GRACE_S = 5.0
+# ``Event.wait`` is a C-level block: KeyboardInterrupt / SetAsyncExc only
+# land when the thread returns to Python. Slice the wait so a /stop or
+# SIGINT during a bounded sync call is observed within this window rather
+# than at the full deadline (#94285, tools/test_local_interrupt_cleanup).
+_BOUNDED_SYNC_WAIT_SLICE_S = 0.2
+
class DeadlineExpired(TimeoutError):
"""A deadline enforced by this layer expired.
@@ -485,6 +492,14 @@ def run_bounded_sync(
in a retry loop would accumulate them.
``timeout=None`` (or non-positive) blocks until ``fn`` returns.
+
+ The worker runs under ``contextvars.copy_context()`` so profile secret
+ scope, session id, and delegated-child guards set on the caller survive
+ the thread hop (terminal env.execute — #94285 CI).
+
+ The caller's wait is sliced (``_BOUNDED_SYNC_WAIT_SLICE_S``) so a
+ ``KeyboardInterrupt`` or ``PyThreadState_SetAsyncExc`` lands within
+ that window instead of only at the full deadline.
"""
timeout_s = clamp_timeout(timeout)
start = time.monotonic()
@@ -499,10 +514,11 @@ def run_bounded_sync(
box: dict[str, Any] = {}
done = threading.Event()
+ ctx = contextvars.copy_context()
def _worker() -> None:
try:
- box["value"] = fn()
+ box["value"] = ctx.run(fn)
except BaseException as exc: # re-raised in caller; must not vanish
box["exc"] = exc
finally:
@@ -510,7 +526,14 @@ def run_bounded_sync(
thread = threading.Thread(target=_worker, name=f"deadline-{label}", daemon=True)
thread.start()
- if not done.wait(timeout_s):
+ deadline = start + timeout_s
+ while not done.is_set():
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ done.wait(min(_BOUNDED_SYNC_WAIT_SLICE_S, remaining))
+
+ if not done.is_set():
logger.warning(
"[deadline] %r timed out after %.1fs; worker abandoned", label, timeout_s
)
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 6ed6e97f405..3688ca49b7c 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -37,7 +37,7 @@ except ImportError:
except ImportError:
msvcrt = None
from pathlib import Path
-from typing import Any, List, Optional, Protocol
+from typing import Any, Callable, List, Optional, Protocol
# Add parent directory to path for imports BEFORE repo-level imports.
# Without this, standalone invocations (e.g. after `hermes update` reloads
@@ -6502,24 +6502,44 @@ def run_job(
task_id=_cron_task_id,
)
_inactivity_timeout = False
- try:
+ _watch_stop = threading.Event()
+
+ def _idle_seconds() -> float:
+ if not hasattr(agent, "get_activity_summary"):
+ return 0.0
+ try:
+ _act = agent.get_activity_summary()
+ return float(_act.get("seconds_since_activity", 0.0) or 0.0)
+ except Exception:
+ return 0.0
+
+ def _watch_inactivity() -> None:
+ nonlocal _inactivity_timeout
if _cron_inactivity_limit is None:
- # Unlimited — no inactivity watchdog, but a one-shot still
- # needs its run_claim heartbeat, so poll instead of blocking.
- if _is_oneshot or cancel_event is not None:
- result = None
- while True:
- done, _ = concurrent.futures.wait(
- {_cron_future}, timeout=_POLL_INTERVAL,
- )
- if done:
- _abort_if_fire_claim_lost()
- result = _cron_future.result()
- break
- _abort_if_fire_claim_lost()
- _heartbeat_run_claim_if_due()
- else:
- result = _cron_future.result()
+ return
+ if _inactivity_watchdog_loop(
+ get_idle_seconds=_idle_seconds,
+ limit_s=_cron_inactivity_limit,
+ poll_s=_POLL_INTERVAL,
+ stop=_watch_stop,
+ future_done=_cron_future.done,
+ ):
+ _inactivity_timeout = True
+
+ _watch_thread = threading.Thread(
+ target=_watch_inactivity,
+ name=f"cron-inactivity-{str(job_id)[:8]}",
+ daemon=True,
+ )
+ try:
+ if _cron_inactivity_limit is not None:
+ # Daemon thread: kernel ``Event.wait`` timeout, independent of
+ # the ``run_job`` thread. A blocked loop / hung
+ # ``get_activity_summary`` on this thread can no longer keep
+ # the 600s inactivity limit from firing (#94285).
+ _watch_thread.start()
+ if _cron_inactivity_limit is None and not _is_oneshot and cancel_event is None:
+ result = _cron_future.result()
else:
result = None
while True:
@@ -6530,23 +6550,15 @@ def run_job(
_abort_if_fire_claim_lost()
result = _cron_future.result()
break
+ if _inactivity_timeout:
+ break
_abort_if_fire_claim_lost()
_heartbeat_run_claim_if_due()
- # Agent still running — check inactivity.
- _idle_secs = 0.0
- if hasattr(agent, "get_activity_summary"):
- try:
- _act = agent.get_activity_summary()
- _idle_secs = _act.get("seconds_since_activity", 0.0)
- except Exception:
- pass
- if _idle_secs >= _cron_inactivity_limit:
- _inactivity_timeout = True
- break
except Exception:
_cron_pool.shutdown(wait=False, cancel_futures=True)
raise
finally:
+ _watch_stop.set()
_cron_pool.shutdown(wait=False, cancel_futures=True)
if _inactivity_timeout:
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 684958699cf..561fca5f8e4 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -24,7 +24,7 @@ from typing import IO, Callable, Iterable, Protocol
from hermes_constants import get_hermes_home
from hermes_cli._subprocess_compat import windows_hide_flags
-from tools.interrupt import is_interrupted
+from tools.interrupt import is_interrupted, is_thread_interrupted
from tools.environments.path_utils import (
_SANDBOX_DIR_HASH_LEN,
_SANDBOX_DIR_MAX_LEN,
@@ -40,6 +40,14 @@ logger = logging.getLogger(__name__)
# to avoid flooding production gateway logs.
_DEBUG_INTERRUPT = bool(os.getenv("HERMES_DEBUG_INTERRUPT"))
+# Extra seconds the ``run_bounded_sync`` backstop waits past the inner
+# ``_wait_for_process`` deadline. The inner poll loop is what returns
+# partial output + returncode 124; this outer bound only exists for when
+# that loop itself never returns (family A of #94285: a blocked wait
+# that silently disables asyncio timers). Keep it small so a healthy
+# timeout still comes from the inner path.
+_EXECUTE_WAIT_BOUND_GRACE_S = 2.0
+
if _DEBUG_INTERRUPT:
# AIAgent's quiet_mode path (run_agent.py) forces the `tools` logger to
# ERROR on CLI startup, which would silently swallow every trace we emit.
@@ -999,7 +1007,12 @@ class BaseEnvironment(ABC):
# ------------------------------------------------------------------
def _wait_for_process(
- self, proc: ProcessHandle, timeout: int = 120, *, bounded_capture: bool = False
+ self,
+ proc: ProcessHandle,
+ timeout: int = 120,
+ *,
+ bounded_capture: bool = False,
+ watch_interrupt_tid: int | None = None,
) -> dict:
"""Poll-based wait with interrupt checking and stdout draining.
@@ -1017,6 +1030,11 @@ class BaseEnvironment(ABC):
while the process is running so the gateway's inactivity timeout
doesn't kill long-running commands.
+ ``watch_interrupt_tid`` is the tool-worker thread that submitted this
+ wait. ``execute()`` may move the wait onto a ``run_bounded_sync``
+ worker; ``/stop`` still interrupts the original worker tid, so the
+ poll loop must honor that bit as well as the current thread's.
+
Also wraps the poll loop in a ``try/finally`` that guarantees we
call ``self._kill_process(proc)`` if we exit via ``KeyboardInterrupt``
or ``SystemExit``. Without this, the local backend (which spawns
@@ -1213,7 +1231,7 @@ class BaseEnvironment(ABC):
_poll_sleep = 0.005
while proc.poll() is None:
_iter_count += 1
- if is_interrupted():
+ if is_interrupted() or is_thread_interrupted(watch_interrupt_tid):
if _DEBUG_INTERRUPT:
logger.info(
"[interrupt-debug] _wait_for_process INTERRUPT DETECTED "
@@ -1444,6 +1462,10 @@ class BaseEnvironment(ABC):
full-fidelity consumers — file operations ``cat`` reads that feed
the patch engine, code-execution RPC reads, log reads — MUST leave
it False: truncating those corrupts data, not just display.
+
+ The wait is bounded by ``agent.deadline.run_bounded_sync`` so a
+ wedged poll loop cannot hang past ``timeout`` and silently disable
+ every asyncio timer in the process (#94285).
"""
self._before_execute()
@@ -1476,12 +1498,82 @@ class BaseEnvironment(ABC):
# unless login itself is broken — then non-login is the only path.
login = not self._snapshot_ready and not self._prefer_nonlogin
- proc = self._run_bash(
- wrapped, login=login, timeout=effective_timeout, stdin_data=effective_stdin
- )
- result = self._wait_for_process(
- proc, timeout=effective_timeout, bounded_capture=bounded_capture
- )
+ parent_tid = threading.current_thread().ident
+ # Activity callback is thread-local (see set_activity_callback). The
+ # wait runs on the deadline worker, so copy it across or long
+ # commands look idle to cron/gateway heartbeats.
+ parent_activity_cb = get_activity_callback()
+ proc_holder: list = []
+
+ def _spawn_and_wait() -> dict:
+ if parent_activity_cb is not None:
+ set_activity_callback(parent_activity_cb)
+ spawned = self._run_bash(
+ wrapped, login=login, timeout=effective_timeout, stdin_data=effective_stdin
+ )
+ proc_holder.append(spawned)
+ return self._wait_for_process(
+ spawned,
+ timeout=effective_timeout,
+ bounded_capture=bounded_capture,
+ watch_interrupt_tid=parent_tid,
+ )
+
+ def _on_timeout() -> None:
+ if not proc_holder:
+ return
+ spawned = proc_holder[0]
+ try:
+ self._kill_process(spawned)
+ except Exception:
+ logger.debug(
+ "terminal wait-bound kill_process failed", exc_info=True
+ )
+ pid = getattr(spawned, "pid", None)
+ if not pid:
+ return
+ try:
+ from agent.deadline import kill_process_tree
+
+ kill_process_tree(int(pid))
+ except Exception:
+ logger.debug(
+ "terminal wait-bound kill_process_tree failed", exc_info=True
+ )
+
+ # Hard wall-clock backstop (#94285): ``_wait_for_process`` already
+ # polls to ``effective_timeout``, but that loop runs on the tool
+ # thread. If that thread is the event-loop thread — or the wait
+ # itself never returns (Windows pipe/poll hang) — every asyncio
+ # timer in the process is silently disabled, including the 420s
+ # sequential-tool deadline and the cron inactivity monitor.
+ # ``run_bounded_sync`` drives expiry from a daemon worker +
+ # ``Event.wait`` so a blocked loop cannot disable it. Grace lets
+ # the inner poll return the partial-output 124 path on a healthy
+ # timeout; the outer bound only fires when that loop is wedged.
+ from agent.deadline import run_bounded_sync
+
+ try:
+ bound_s = float(effective_timeout) + _EXECUTE_WAIT_BOUND_GRACE_S
+ except (TypeError, ValueError):
+ bound_s = None
+
+ try:
+ bounded = run_bounded_sync(
+ _spawn_and_wait,
+ bound_s,
+ label=f"terminal.wait:{type(self).__name__}",
+ on_timeout=_on_timeout,
+ )
+ except (KeyboardInterrupt, SystemExit):
+ _on_timeout()
+ raise
+
+ if bounded.timed_out:
+ timeout_msg = f"\n[Command timed out after {effective_timeout}s]"
+ result = {"output": timeout_msg.lstrip(), "returncode": 124}
+ else:
+ result = bounded.value
self._update_cwd(result)
return result
diff --git a/tools/interrupt.py b/tools/interrupt.py
index 7ec1db39d81..aaa4b1081d4 100644
--- a/tools/interrupt.py
+++ b/tools/interrupt.py
@@ -79,9 +79,20 @@ def is_interrupted() -> bool:
Safe to call from any thread — each thread only sees its own
interrupt state.
"""
- tid = threading.current_thread().ident
+ return is_thread_interrupted(threading.current_thread().ident)
+
+
+def is_thread_interrupted(thread_id: int | None) -> bool:
+ """Check whether *thread_id* has an interrupt bit set.
+
+ Used when a wait is moved onto a deadline worker (``run_bounded_sync``)
+ so ``/stop`` targeting the original tool-worker tid still kills the
+ subprocess (#94285). ``None`` is never interrupted.
+ """
+ if thread_id is None:
+ return False
with _lock:
- return tid in _interrupted_threads
+ return thread_id in _interrupted_threads
def get_interrupt_reason() -> str | None: