Skip to content

The agent that grows with you

fix(cron): never lose a bot-chat alert to a delivery timeout

Emir Saffarfa939860ca8e
diff --git a/cron/jobs.py b/cron/jobs.py
index 5a749440e3a..7346c681999 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -323,6 +323,30 @@ def _jobs_lock():
_jobs_lock_state.load_stamp = None
+_FENCE_COMPLAINT_INTERVAL_SECONDS = 600.0
+_fire_fence_complaints: "dict[str, float]" = {}
+_fire_fence_complaints_lock = threading.Lock()
+
+
+def _fence_timeout_log(lock_key: str, message: str, *args) -> None:
+ """One ERROR per fence-hold episode, DEBUG for repeats inside the interval.
+
+ A bot-chat delivery turn holding the fire fence for minutes timed out the NEXT
+ occurrence's claim on every scheduler tick — one episode became an 8-ERROR storm
+ plus restore warnings (2026-09-19). Repeats inside the interval log at DEBUG; a
+ genuinely stuck fence re-alerts at ERROR every interval; a successful acquire
+ clears the episode."""
+ now = time.monotonic()
+ with _fire_fence_complaints_lock:
+ last = _fire_fence_complaints.get(lock_key)
+ if last is not None and now - last < _FENCE_COMPLAINT_INTERVAL_SECONDS:
+ level = logger.debug
+ else:
+ _fire_fence_complaints[lock_key] = now
+ level = logger.error
+ level(message, *args)
+
+
@contextlib.contextmanager
def _fire_job_lock(job_id: str):
"""Serialize one job's owner mutations and external side effects. Unlike the global jobs lock
@@ -334,7 +358,8 @@ def _fire_job_lock(job_id: str):
local_lock = _fire_fence_locks.setdefault(lock_key, threading.RLock())
if not local_lock.acquire(timeout=_JOBS_LOCK_TIMEOUT_SECONDS):
- logger.error("Timed out waiting for local fire fence %s; failing closed", lock_key)
+ _fence_timeout_log(lock_key,
+ "Timed out waiting for local fire fence %s; failing closed", lock_key)
yield False
return
@@ -358,7 +383,11 @@ def _fire_job_lock(job_id: str):
if result is None: # pragma: no cover - supported platforms provide one backend
logger.error("No cross-process lock backend for cron fire fence")
elif not result:
- logger.error("Timed out waiting for fire fence %s; failing closed", lock_path)
+ _fence_timeout_log(lock_key,
+ "Timed out waiting for fire fence %s; failing closed", lock_path)
+ else:
+ with _fire_fence_complaints_lock:
+ _fire_fence_complaints.pop(lock_key, None)
acquired = bool(result)
except (OSError, IOError) as exc:
logger.error("Cron fire fence unavailable for %s: %s", job_id, exc)
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index a71a960a920..228d0acbe58 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -781,6 +781,14 @@ def _run_bot_chat_turn(argv: list, env: dict, report_path: str, timeout: float)
if report is None and time.monotonic() >= deadline:
proc.kill()
drain.join(timeout=5.0)
+ # A killed child cannot run further, but the turn may have ENDED (and delivered)
+ # in the window between the last report check and the kill landing. Re-read once:
+ # a report that appeared means the turn completed — book it as delivered instead
+ # of misreporting a delivered turn as a timeout (and never re-notifying).
+ late = read_turn_report(report_path, proc.pid)
+ if late is not None:
+ return subprocess.CompletedProcess(
+ argv, int(late["exit_code"]), "", late.get("error") or "")
raise subprocess.TimeoutExpired(argv, timeout)
@@ -974,11 +982,42 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)
return None
except subprocess.TimeoutExpired:
+ # The turn was killed mid-flight: the killed child cannot complete, but its turn may
+ # have persisted the query into the session before the kill landed. Replaying the
+ # full payload risks a duplicate; staying silent loses the alert entirely (the
+ # 2026-09-19 docgen-deadman case: findings existed in the job output and nobody
+ # knew to look). Fail-safe middle: queue a SHORT degraded-delivery marker through
+ # the deferred lane — it references the saved output instead of repeating it, so a
+ # late-completing original turn cannot duplicate content. One marker per execution
+ # (stable key); a marker that itself times out is never re-marked (recursion guard).
+ marker_queued = False
+ if "DELIVERY DEGRADED" not in content:
+ marker = (
+ f"[Cronjob \"{job.get('name', job_id)}\" — DELIVERY DEGRADED, scheduled job, "
+ f"not the user. This alert's bot-chat turn timed out after "
+ f"{_get_bot_chat_delivery_timeout()}s, so the full output could NOT be posted "
+ f"here. Read the complete saved output with `hermes cron runs` "
+ f"(job '{job_id}'). Excerpt: {content.strip()[:280]}]"
+ )
+ try:
+ from cron.bot_chat_delivery import defer as _defer_marker
+ _defer_marker(f"{key}-degraded", dict(job), marker, profile, home,
+ for_failure=for_failure)
+ marker_queued = True
+ except Exception as defer_exc:
+ logger.warning(
+ "Job '%s': degraded-delivery marker could not be queued: %s",
+ job_id, defer_exc)
+ tail = (
+ "a short degraded-delivery notice was queued to Bot Chat — posted once the "
+ f"session frees; full output stays saved, run `hermes cron runs` for job '{job_id}'"
+ if marker_queued else
+ "the result is saved; run `hermes cron runs` to see it, or `hermes doctor` "
+ "if this keeps happening")
return _fail(
f"bot-chat delivery to profile '{profile_label}' timed out "
- f"after {_get_bot_chat_delivery_timeout()}s (the bot's turn may "
- "still complete; raise cron.bot_chat_delivery_timeout_seconds if "
- "this recurs)")
+ f"after {_get_bot_chat_delivery_timeout()}s ({tail}; raise "
+ "cron.bot_chat_delivery_timeout_seconds if this recurs)")
except Exception as e:
logger.warning(
"Job '%s': bot-chat delivery to profile '%s' failed: %s", job_id, profile_label,
diff --git a/tests/cron/test_bot_chat_timeout_marker.py b/tests/cron/test_bot_chat_timeout_marker.py
new file mode 100644
index 00000000000..53a24573cc5
--- /dev/null
+++ b/tests/cron/test_bot_chat_timeout_marker.py
@@ -0,0 +1,161 @@
+"""Timeout must never silently lose a bot-chat alert (2026-09-19 docgen-deadman RCA).
+
+Covers three behaviors:
+1. A timed-out CLI delivery queues a SHORT degraded-delivery marker via the deferred
+ lane (references the saved output; never repeats the full payload).
+2. A marker that itself times out is never re-marked (recursion guard).
+3. A turn report appearing in the kill window books the delivery instead of raising
+ TimeoutExpired (a delivered turn must not be reported as lost).
+"""
+import logging
+import subprocess
+import threading
+import time
+from unittest.mock import Mock
+
+import pytest
+
+from cron import scheduler_delivery as delivery
+
+
+def cli_lane(tmp_path, monkeypatch):
+ """Route _deliver_to_bot_chat straight into the CLI fallback lane."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(
+ delivery, "_run_bot_chat_turn",
+ Mock(side_effect=subprocess.TimeoutExpired(["hermes"], 600)))
+ return tmp_path
+
+
+def _capturing_defer():
+ captured = {}
+ mock = Mock(side_effect=lambda key, job, content, profile, home, **kw:
+ captured.update(key=key, content=content, profile=profile,
+ home=home, kw=kw) or {"id": key, "status": "queued"})
+ return mock, captured
+
+
+def test_timeout_queues_degraded_marker(cli_lane, monkeypatch):
+ from cron import bot_chat_delivery as queue
+ defer_mock, captured = _capturing_defer()
+ monkeypatch.setattr(queue, "defer", defer_mock)
+
+ job = {"id": "job-1", "name": "docgen deadman", "execution_id": "exec-1"}
+ result = delivery._deliver_to_bot_chat(job, "P1 findings: everything on fire", "")
+
+ assert defer_mock.call_count == 1
+ assert captured["key"].endswith("-degraded")
+ marker = captured["content"]
+ assert "DELIVERY DEGRADED" in marker
+ assert "docgen deadman" in marker
+ assert "job-1" in marker
+ assert "hermes cron runs" in marker
+ assert "P1 findings: everything on fire" in marker # short excerpt
+ assert result is not None and "degraded-delivery notice was queued" in result
+ assert "timed out" in result
+
+
+def test_timeout_marker_not_recursive(cli_lane, monkeypatch):
+ """A marker's own timeout must not queue another marker."""
+ from cron import bot_chat_delivery as queue
+ defer_mock, _ = _capturing_defer()
+ monkeypatch.setattr(queue, "defer", defer_mock)
+
+ marker_payload = ("[Cronjob \"x\" — DELIVERY DEGRADED, scheduled job, not the user. "
+ "Excerpt: boom]")
+ job = {"id": "job-1", "execution_id": "exec-1"}
+ result = delivery._deliver_to_bot_chat(job, marker_payload, "")
+
+ defer_mock.assert_not_called()
+ assert result is not None and "the result is saved" in result
+ assert "degraded-delivery notice was queued" not in result
+
+
+def test_timeout_defer_failure_falls_back(cli_lane, monkeypatch):
+ """A broken deferred lane degrades to the old message, never raises."""
+ from cron import bot_chat_delivery as queue
+ monkeypatch.setattr(queue, "defer", Mock(side_effect=OSError("disk full")))
+
+ job = {"id": "job-1", "execution_id": "exec-1"}
+ result = delivery._deliver_to_bot_chat(job, "alert body", "")
+
+ assert result is not None and "the result is saved" in result
+ assert "timed out" in result
+
+
+class _FakeProc:
+ """Blocks in communicate() until killed; exit code set by the report path."""
+
+ def __init__(self, *args, **kwargs):
+ self.pid = 4242
+ self.returncode = None
+ self.killed = threading.Event()
+
+ def communicate(self):
+ self.killed.wait()
+ return "", ""
+
+ def kill(self):
+ self.returncode = -9
+ self.killed.set()
+
+
+def test_late_turn_report_books_delivery(tmp_path, monkeypatch):
+ """Report appearing in the kill window = turn completed = booked, not a timeout."""
+ from hermes_cli import quiet_single_query as qsq
+ monkeypatch.setattr(delivery.subprocess, "Popen", _FakeProc)
+
+ def fake_read(path, pid):
+ # Only after the kill: simulate the report landing in the kill window.
+ if pid == 4242 and _late_state.get("killed"):
+ return {"pid": pid, "exit_code": 0, "error": None}
+ return None
+
+ late_state = _late_state = {}
+ real_kill = _FakeProc.kill
+
+ def kill_and_flag(self):
+ real_kill(self)
+ late_state["killed"] = True
+
+ monkeypatch.setattr(_FakeProc, "kill", kill_and_flag)
+ monkeypatch.setattr(qsq, "read_turn_report", fake_read)
+
+ result = delivery._run_bot_chat_turn(["hermes"], {}, str(tmp_path / "r.json"), 0.4)
+ assert isinstance(result, subprocess.CompletedProcess)
+ assert result.returncode == 0
+
+
+def test_no_report_still_raises_timeout(tmp_path, monkeypatch):
+ """Polarity: with no report at all the timeout still raises (lost turn detected)."""
+ from hermes_cli import quiet_single_query as qsq
+ monkeypatch.setattr(delivery.subprocess, "Popen", _FakeProc)
+ monkeypatch.setattr(qsq, "read_turn_report", lambda path, pid: None)
+
+ with pytest.raises(subprocess.TimeoutExpired):
+ delivery._run_bot_chat_turn(["hermes"], {}, str(tmp_path / "r.json"), 0.4)
+
+
+def test_fence_timeout_log_episode_dedupe(caplog):
+ """One ERROR per episode; repeats inside the interval log DEBUG; a new episode re-alerts."""
+ from cron.jobs import _FENCE_COMPLAINT_INTERVAL_SECONDS, _fire_fence_complaints, _fence_timeout_log
+ _fire_fence_complaints.clear()
+ try:
+ with caplog.at_level(logging.DEBUG, logger="cron.jobs"):
+ _fence_timeout_log("fence-k", "Timed out waiting for fire fence %s; failing closed", "p1")
+ _fence_timeout_log("fence-k", "Timed out waiting for fire fence %s; failing closed", "p2")
+ _fence_timeout_log("fence-k", "Timed out waiting for fire fence %s; failing closed", "p3")
+ errors = [r for r in caplog.records if r.levelno == logging.ERROR]
+ debugs = [r for r in caplog.records if r.levelno == logging.DEBUG]
+ assert len(errors) == 1 and "p1" in errors[0].getMessage()
+ assert len(debugs) == 2
+
+ # Interval elapsed -> a genuinely stuck fence re-alerts at ERROR.
+ _fire_fence_complaints["fence-k"] = (
+ time.monotonic() - _FENCE_COMPLAINT_INTERVAL_SECONDS - 1)
+ with caplog.at_level(logging.DEBUG, logger="cron.jobs"):
+ _fence_timeout_log("fence-k", "Timed out waiting for fire fence %s; failing closed", "p4")
+ assert len([r for r in caplog.records if r.levelno == logging.ERROR]) == 2
+ finally:
+ _fire_fence_complaints.clear()