The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): open the session store only after wake-gate and validation early-returns
Heath Harris3113f6056b80
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 7fa31b0c51e..68fe6e0c56a 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -5602,81 +5602,12 @@ def run_job(# ---------------------------------------------------------------from run_agent import AIAgent- # Initialize SQLite session store so cron job messages are persisted- # and discoverable via session_search (same pattern as gateway/run.py).- #- # Bounded with its own timeout (separate from HERMES_CRON_TIMEOUT, which- # only watches the agent's run_conversation below): SessionDB.__init__- # opens/migrates state.db synchronously and has no timeout of its own- # against a wedged sqlite3.connect (e.g. a stale flock left by a crashed- # sibling process). An unbounded hang here is invisible to every other- # cron safeguard, because it happens BEFORE _submit_with_guard's future- # exists — the finally block that releases the job from- # _running_job_ids never runs, so the job stays wedged "running" until- # the whole gateway process is restarted, silently skipping every- # scheduled fire in between with "already running — skipping".- _session_db = None- try:- from hermes_state import SessionDB-- # Resolve timeout: env override → config.yaml → default 10s.- # Mirrors the script_timeout_seconds resolution pattern.- _session_db_timeout: float | None = None- _raw_env_timeout = os.getenv("HERMES_CRON_SESSION_DB_TIMEOUT", "").strip()- if _raw_env_timeout:- try:- _session_db_timeout = float(_raw_env_timeout)- except (ValueError, TypeError):- logger.warning(- "Invalid HERMES_CRON_SESSION_DB_TIMEOUT=%r; using config/default",- _raw_env_timeout,- )- if _session_db_timeout is None:- 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("session_db_timeout_seconds")- if _configured is not None:- _session_db_timeout = float(_configured)- except Exception as exc:- logger.debug(- "Failed to load cron.session_db_timeout_seconds from config: %s",- exc,- )- if _session_db_timeout is None:- _session_db_timeout = 10.0-- if _session_db_timeout > 0:- _session_db_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)- _session_db_future = _session_db_pool.submit(SessionDB)- try:- _session_db = _session_db_future.result(timeout=_session_db_timeout)- except concurrent.futures.TimeoutError:- # The worker is abandoned (shutdown below doesn't wait for it).- # If SessionDB() later completes inside it, the future's result- # would be orphaned and its SQLite FDs (.db, WAL, SHM) leak- # until process exit. Register a done-callback that retrieves- # and closes any eventual late result (#72782).- _session_db_future.add_done_callback(_close_late_session_db_result)- raise- finally:- # Don't wait for a wedged connect() to unwind — abandon the- # worker thread (same pattern as the agent inactivity timeout- # further down) rather than blocking shutdown on it too.- _session_db_pool.shutdown(wait=False)- else:- # 0 = unlimited (legacy behavior, opt-in for debugging)- _session_db = SessionDB()- except concurrent.futures.TimeoutError:- logger.error(- "Job '%s': SessionDB init did not return within %.0fs — proceeding "- "without a session store for this run instead of blocking it "- "forever",- job.get("id", "?"), _session_db_timeout,- )- except Exception as e:- logger.debug("Job '%s': SQLite session store not available: %s", job.get("id", "?"), e)+ # NOTE: the SQLite session store used to be initialized here, BEFORE the+ # wake-gate and prompt-validation early returns below. Every gated run+ # (``wakeAgent: false``, blocked prompt) opened state.db and returned+ # without reaching the finally that closes it, relying on GC to release+ # the handle. Init now happens inside the main try, right before the+ # agent is constructed — after every early-return path (#96290).# Wake-gate: if this job has a pre-check script, run it BEFORE building# the prompt so a ``{"wakeAgent": false}`` response can short-circuit@@ -5848,6 +5779,7 @@ def run_job(_cron_session_var = _VAR_MAP["HERMES_CRON_SESSION"]_cron_session_token = None_non_dispatcher_token = None+ _session_db = Nonetry:if not _cwd_lock_acquired:# Fail closed (#79768): running without the lock would let a@@ -6363,6 +6295,92 @@ def run_job(job_id, _mcp_exc,)+ # Initialize the SQLite session store so cron job messages are+ # persisted and discoverable via session_search (same pattern as+ # gateway/run.py) — only now, after every early-return path+ # (wake-gate, prompt validation, drift skip) has passed, so a gated+ # run never opens state.db just to abandon the handle (#96290).+ #+ # Bounded with its own timeout (separate from HERMES_CRON_TIMEOUT,+ # which only watches the agent's run_conversation below):+ # SessionDB.__init__ opens/migrates state.db synchronously and has no+ # timeout of its own against a wedged sqlite3.connect (e.g. a stale+ # flock left by a crashed sibling process). An unbounded hang here is+ # invisible to every other cron safeguard, because it happens BEFORE+ # _submit_with_guard's future exists — the finally block that releases+ # the job from _running_job_ids never runs, so the job stays wedged+ # "running" until the whole gateway process is restarted, silently+ # skipping every scheduled fire in between with+ # "already running — skipping".+ _session_db_timeout: float | None = None+ try:+ from hermes_state import SessionDB++ # Resolve timeout: env override → config.yaml → default 10s.+ # Mirrors the script_timeout_seconds resolution pattern.+ _raw_env_timeout = os.getenv("HERMES_CRON_SESSION_DB_TIMEOUT", "").strip()+ if _raw_env_timeout:+ try:+ _session_db_timeout = float(_raw_env_timeout)+ except (ValueError, TypeError):+ logger.warning(+ "Invalid HERMES_CRON_SESSION_DB_TIMEOUT=%r; using config/default",+ _raw_env_timeout,+ )+ if _session_db_timeout is None:+ try:+ # _cfg was already loaded above for model/toolset routing.+ _cron_cfg_for_db = (+ _cfg.get("cron", {}) if isinstance(_cfg, dict) else {}+ )+ _configured = (+ _cron_cfg_for_db.get("session_db_timeout_seconds")+ if isinstance(_cron_cfg_for_db, dict)+ else None+ )+ if _configured is not None:+ _session_db_timeout = float(_configured)+ except Exception as exc:+ logger.debug(+ "Failed to load cron.session_db_timeout_seconds from config: %s",+ exc,+ )+ if _session_db_timeout is None:+ _session_db_timeout = 10.0++ if _session_db_timeout > 0:+ _session_db_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)+ _session_db_future = _session_db_pool.submit(SessionDB)+ try:+ _session_db = _session_db_future.result(timeout=_session_db_timeout)+ except concurrent.futures.TimeoutError:+ # The worker is abandoned (shutdown below doesn't wait for+ # it). If SessionDB() later completes inside it, the+ # future's result would be orphaned and its SQLite FDs+ # (.db, WAL, SHM) leak until process exit. Register a+ # done-callback that retrieves and closes any eventual+ # late result (#72782).+ _session_db_future.add_done_callback(_close_late_session_db_result)+ raise+ finally:+ # Don't wait for a wedged connect() to unwind — abandon the+ # worker thread (same pattern as the agent inactivity+ # timeout further down) rather than blocking shutdown on+ # it too.+ _session_db_pool.shutdown(wait=False)+ else:+ # 0 = unlimited (legacy behavior, opt-in for debugging)+ _session_db = SessionDB()+ except concurrent.futures.TimeoutError:+ logger.error(+ "Job '%s': SessionDB init did not return within %.0fs — proceeding "+ "without a session store for this run instead of blocking it "+ "forever",+ job.get("id", "?"), _session_db_timeout,+ )+ except Exception as e:+ logger.debug("Job '%s': SQLite session store not available: %s", job.get("id", "?"), e)+agent = AIAgent(model=model,api_key=runtime.get("api_key"),diff --git a/tests/cron/test_sessiondb_init_hang.py b/tests/cron/test_sessiondb_init_hang.pyindex b939ca82993..4402600ec7c 100644--- a/tests/cron/test_sessiondb_init_hang.py+++ b/tests/cron/test_sessiondb_init_hang.py@@ -345,3 +345,38 @@ class TestLateSessionDbClosedAfterTimeout:"The SessionDB that completed after the timeout must be closed by ""the done-callback — otherwise its SQLite FDs leak until process exit (#72782)")+++# ===========================================================================+# #96290: gated runs must not open the session store at all+# ===========================================================================++class TestSessionDbInitAfterEarlyReturns:+ """SessionDB init moved AFTER the wake-gate / prompt-validation early+ returns (#96290): a run that never reaches the agent must never open+ state.db, so there is no handle for a gated return path to abandon."""++ def test_wake_gate_false_never_opens_session_db(self, tmp_path, monkeypatch):+ monkeypatch.delenv("HERMES_CRON_SESSION_DB_TIMEOUT", raising=False)+ job = {+ "id": "gated-no-db",+ "name": "gated-no-db",+ "prompt": "hello",+ "script": "gate.py",+ }++ 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") as mock_db_cls, \+ patch(+ "cron.scheduler._run_job_script_with_claim_heartbeat",+ return_value=(True, '{"wakeAgent": false}'),+ ), \+ patch("run_agent.AIAgent") as mock_agent_cls:+ success, output, final_response, error = run_job(job)++ assert success is True+ mock_db_cls.assert_not_called()+ mock_agent_cls.assert_not_called()