Skip to content

The agent that grows with you

fix(cron): bound post-run cleanup

yuric569b7a34b15a
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 8ba099cfd36..624efc48f92 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -4046,6 +4046,130 @@ def _preflight_job_config(job: dict, cfg: dict) -> Optional[str]:
return None
+def _cron_cleanup_timeout_seconds() -> float:
+ """Return the wall-clock bound for cron post-run cleanup."""
+ default = 10.0
+ try:
+ from hermes_cli.config import load_config
+
+ cfg = load_config() or {}
+ cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}
+ configured = cron_cfg.get("cleanup_timeout_seconds")
+ if configured is not None:
+ timeout = float(configured)
+ if timeout >= 0:
+ return timeout
+ except Exception as exc:
+ logger.debug("Failed to load cron cleanup timeout from config: %s", exc)
+ return default
+
+
+def _run_cron_cleanup_with_timeout(
+ cleanup,
+ *,
+ job_id: str,
+ label: str,
+ timeout_seconds: Optional[float] = None,
+) -> bool:
+ """Run fallible post-run cleanup without permanently wedging a cron ID."""
+ timeout = (
+ _cron_cleanup_timeout_seconds()
+ if timeout_seconds is None
+ else float(timeout_seconds)
+ )
+ if timeout <= 0:
+ try:
+ cleanup()
+ return True
+ except (Exception, KeyboardInterrupt) as exc:
+ logger.debug("Job '%s': %s failed: %s", job_id, label, exc)
+ return False
+
+ done = threading.Event()
+ error: list[BaseException] = []
+
+ def _runner() -> None:
+ try:
+ cleanup()
+ except BaseException as exc:
+ error.append(exc)
+ finally:
+ done.set()
+
+ # A daemon thread is deliberate: unlike ThreadPoolExecutor workers it is
+ # not joined by Python's interpreter-exit hook if the cleanup target never
+ # returns. The scheduler can release its dispatch guard and the gateway can
+ # still shut down normally.
+ worker = threading.Thread(
+ target=_runner,
+ name=f"cron-cleanup-{job_id}",
+ daemon=True,
+ )
+ worker.start()
+ if not done.wait(timeout):
+ logger.error(
+ "Job '%s': %s exceeded %.1fs; abandoning cleanup so future runs remain dispatchable",
+ job_id,
+ label,
+ timeout,
+ )
+ return False
+ if error:
+ logger.debug("Job '%s': %s failed: %s", job_id, label, error[0])
+ return False
+ return True
+
+
+class _BoundedCronSessionDB:
+ """Proxy SessionDB cleanup calls through the cron cleanup timeout.
+
+ After the first failed or timed-out operation the proxy fails subsequent
+ calls immediately. A damaged SQLite connection should leak at most one
+ abandoned cleanup worker, not one worker per finalization step.
+ """
+
+ def __init__(self, session_db, job_id: str):
+ self._session_db = session_db
+ self._job_id = job_id
+ self._disabled = False
+
+ def __getattr__(self, name):
+ target = getattr(self._session_db, name)
+ if not callable(target):
+ return target
+
+ def _bounded(*args, **kwargs):
+ if self._disabled:
+ raise RuntimeError("session finalization disabled after prior cleanup failure")
+
+ result = {}
+
+ def _call():
+ try:
+ result["value"] = target(*args, **kwargs)
+ except BaseException as exc:
+ result["error"] = exc
+ raise
+
+ ok = _run_cron_cleanup_with_timeout(
+ _call,
+ job_id=self._job_id,
+ label=f"session finalization ({name})",
+ )
+ if not ok:
+ error = result.get("error")
+ if error is not None:
+ raise error
+ # No exception reached the caller and the operation still did
+ # not complete: this is the timeout path. Disable the damaged
+ # connection so later finalization steps fail immediately.
+ self._disabled = True
+ raise TimeoutError(f"session finalization method {name} timed out")
+ return result.get("value")
+
+ return _bounded
+
+
def run_job(
job: dict,
*,
@@ -5374,6 +5498,9 @@ def run_job(
for _var_name in _cron_delivery_vars:
_VAR_MAP[_var_name].set("")
if _session_db:
+ # The agent turn has already returned. Bound every subsequent DB
+ # operation so storage failure cannot hold the dispatch guard.
+ _session_db = _BoundedCronSessionDB(_session_db, job_id)
# Compression can rotate the live agent onto a continuation while
# this run is in flight. Finalize that continuation, not the stale
# cron id captured before AIAgent started. SessionDB is the source
@@ -5458,29 +5585,37 @@ def run_job(
_teardown_cron_agent(agent, job_id)
-def _teardown_cron_agent(agent, job_id: str) -> None:
- """Release an ephemeral cron agent's async resources.
+def _teardown_cron_agent(
+ agent, job_id: str, *, timeout_seconds: Optional[float] = None
+) -> None:
+ """Release an ephemeral cron agent's async resources within a hard bound.
Split out of ``run_job``'s ``finally`` so a caller that defers teardown
(to deliver first — #58720) can invoke the identical cleanup AFTER delivery.
- Closes the agent (subprocesses, sandboxes, browser daemons, OpenAI/httpx
- client) and reaps stale async clients whose loop has since closed. Idempotent
- and independently guarded, matching the original inline behavior.
+ The timeout matters because this executes after ``run_conversation`` has
+ returned, outside the agent inactivity watchdog.
"""
- try:
- if agent is not None:
- agent.close()
- except (Exception, KeyboardInterrupt) as e:
- logger.debug("Job '%s': failed to close agent resources: %s", job_id, e)
- # Each cron run spins up a short-lived worker thread whose event loop
- # dies as soon as the ``ThreadPoolExecutor`` shuts down. Any async
- # httpx clients cached under that loop are now unusable — reap them
- # so their transports don't accumulate in the process-global cache.
- try:
- from agent.auxiliary_client import cleanup_stale_async_clients
- cleanup_stale_async_clients()
- except Exception as e:
- logger.debug("Job '%s': failed to reap stale auxiliary clients: %s", job_id, e)
+ def _cleanup_agent() -> None:
+ try:
+ if agent is not None:
+ agent.close()
+ except (Exception, KeyboardInterrupt) as e:
+ logger.debug("Job '%s': failed to close agent resources: %s", job_id, e)
+ # Each cron run spins up a short-lived worker thread whose event loop
+ # dies as soon as the ``ThreadPoolExecutor`` shuts down. Any async
+ # httpx clients cached under that loop are now unusable — reap them.
+ try:
+ from agent.auxiliary_client import cleanup_stale_async_clients
+ cleanup_stale_async_clients()
+ except Exception as e:
+ logger.debug("Job '%s': failed to reap stale auxiliary clients: %s", job_id, e)
+
+ _run_cron_cleanup_with_timeout(
+ _cleanup_agent,
+ job_id=job_id,
+ label="agent resource teardown",
+ timeout_seconds=timeout_seconds,
+ )
def _run_with_fire_claim_heartbeat(job: dict, run) -> bool:
diff --git a/tests/cron/test_cleanup_timeout.py b/tests/cron/test_cleanup_timeout.py
new file mode 100644
index 00000000000..6ceed5c0773
--- /dev/null
+++ b/tests/cron/test_cleanup_timeout.py
@@ -0,0 +1,140 @@
+"""Regression tests for bounded cron post-run cleanup.
+
+A cron worker must release its in-memory dispatch guard even when SQLite or an
+agent resource finalizer stops returning after the model turn has ended.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from unittest.mock import MagicMock, patch
+
+from cron.scheduler import run_job, _teardown_cron_agent
+
+
+_RUNTIME = {
+ "api_key": "test-key",
+ "base_url": "https://example.invalid/v1",
+ "provider": "openrouter",
+ "api_mode": "chat_completions",
+}
+
+
+class HangingSessionDB:
+ def __init__(self, release: threading.Event):
+ self.release = release
+ self.entered = threading.Event()
+
+ def get_compression_tip(self, _session_id):
+ self.entered.set()
+ self.release.wait()
+ return None
+
+ def end_session(self, *_args, **_kwargs):
+ return None
+
+ def close(self):
+ return None
+
+
+class HangingAgent:
+ def __init__(self, release: threading.Event):
+ self.release = release
+ self.entered = threading.Event()
+
+ def close(self):
+ self.entered.set()
+ self.release.wait()
+
+
+def test_run_job_bounds_sessiondb_finalization(tmp_path):
+ release = threading.Event()
+ fake_db = HangingSessionDB(release)
+ job = {"id": "cleanup-sessiondb-hang", "name": "test", "prompt": "hello"}
+
+ try:
+ with patch("cron.scheduler._hermes_home", tmp_path), \
+ patch("cron.scheduler._resolve_origin", return_value=None), \
+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \
+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \
+ patch("hermes_state.SessionDB", return_value=fake_db), \
+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", return_value=_RUNTIME), \
+ patch("run_agent.AIAgent") as mock_agent_cls, \
+ patch("cron.scheduler._cron_cleanup_timeout_seconds", return_value=0.02):
+ mock_agent = MagicMock()
+ mock_agent.run_conversation.return_value = {"final_response": "ok"}
+ mock_agent_cls.return_value = mock_agent
+
+ started = time.monotonic()
+ success, _output, final_response, error = run_job(job)
+ elapsed = time.monotonic() - started
+
+ assert fake_db.entered.wait(timeout=0.5)
+ assert elapsed < 0.5
+ assert success is True
+ assert final_response == "ok"
+ assert error is None
+ finally:
+ release.set()
+
+
+def test_agent_teardown_is_bounded():
+ release = threading.Event()
+ agent = HangingAgent(release)
+
+ try:
+ started = time.monotonic()
+ _teardown_cron_agent(agent, "cleanup-agent-hang", timeout_seconds=0.02)
+ elapsed = time.monotonic() - started
+
+ assert agent.entered.wait(timeout=0.5)
+ assert elapsed < 0.5
+ finally:
+ release.set()
+
+
+def test_dispatch_guard_releases_after_sessiondb_finalization_hang(tmp_path):
+ """A second scheduler tick can fire the same job after cleanup times out."""
+ import cron.scheduler as sched
+
+ release = threading.Event()
+ fake_db = HangingSessionDB(release)
+ job = {
+ "id": "cleanup-guard-hang",
+ "name": "cleanup-guard-hang",
+ "prompt": "hello",
+ "schedule": "every 5m",
+ "enabled": True,
+ "next_run_at": "2020-01-01T00:00:00",
+ "deliver": "local",
+ }
+ sched._parallel_pool = None
+ sched._parallel_pool_max_workers = None
+ sched._running_job_ids.clear()
+
+ try:
+ with patch("cron.scheduler._hermes_home", tmp_path), \
+ patch("cron.scheduler._resolve_origin", return_value=None), \
+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \
+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \
+ patch("hermes_state.SessionDB", return_value=fake_db), \
+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", return_value=_RUNTIME), \
+ patch("run_agent.AIAgent") as mock_agent_cls, \
+ patch("cron.scheduler._cron_cleanup_timeout_seconds", return_value=0.02), \
+ patch.object(sched, "get_due_jobs", return_value=[job]), \
+ patch.object(sched, "advance_next_runs"), \
+ patch.object(sched, "save_job_output", return_value="/tmp/out"), \
+ patch.object(sched, "mark_job_run"), \
+ patch.object(sched, "_deliver_result", return_value=None):
+ mock_agent = MagicMock()
+ mock_agent.run_conversation.return_value = {"final_response": "ok"}
+ mock_agent_cls.return_value = mock_agent
+
+ assert sched.tick(verbose=False) == 1
+ assert "cleanup-guard-hang" not in sched.get_running_job_ids()
+ assert sched.tick(verbose=False) == 1
+ finally:
+ release.set()
+ sched._running_job_ids.discard("cleanup-guard-hang")
+ sched._shutdown_parallel_pool()
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 9cff2758492..38473ff7ea6 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -516,6 +516,16 @@ cron:
Or set the `HERMES_CRON_SCRIPT_TIMEOUT` environment variable. The resolution order is: env var → config.yaml → 3600s default.
+Cron also bounds post-run session and agent-resource cleanup. This happens after the LLM turn returns, so it is separate from the inactivity timeout. The default is 10 seconds per cleanup operation. If a storage or client finalizer stops returning, the scheduler logs an error, releases the job's in-flight guard, and allows later runs to dispatch instead of skipping that job forever.
+
+```yaml
+# ~/.hermes/config.yaml
+cron:
+ cleanup_timeout_seconds: 10
+```
+
+Set `cleanup_timeout_seconds: 0` only to restore the legacy unbounded cleanup behavior.
+
## No-agent mode (script-only jobs)
For recurring jobs that don't need LLM reasoning — classic watchdogs, disk/memory alerts, heartbeats, CI pings — pass `no_agent=True` at creation time. The scheduler runs your script on schedule and delivers its stdout directly, skipping the agent entirely: