The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): run the deferred state.db scan after the runner is live
unsupportedpastels2fe81e7879b7
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex ee5a51b8fea..958cd14a5f0 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -2,12 +2,50 @@from __future__ import annotationsimport logging+import mathimport threadingfrom pathlib import Pathfrom typing import Any, Optionalfrom gateway.config import GatewayConfig+_STATE_DB_INTEGRITY_DEADLINE_DEFAULT_S = 1800.0+++def _state_db_integrity_deadline_s() -> float:+ """``agent.gateway_state_db_integrity_deadline_s`` (default 1800 s) for the deferred scan.++ The deadline is the only bound on a pathological store, so anything but a finite positive+ number (unset, unparsable, ``0``, ``.inf``) keeps the default instead of removing it.+ """+ from gateway.run import _best_effort+ from hermes_cli.config import read_raw_config_readonly+ cfg = _best_effort(read_raw_config_readonly, "config.yaml unreadable for the scan deadline: %s")+ agent_cfg = cfg.get("agent") if isinstance(cfg, dict) else None+ raw = agent_cfg.get("gateway_state_db_integrity_deadline_s") if isinstance(agent_cfg, dict) else None+ try:+ value = float(raw) if raw is not None and not isinstance(raw, bool) else None+ except (TypeError, ValueError):+ value = None+ if value is None or not math.isfinite(value) or value <= 0:+ return _STATE_DB_INTEGRITY_DEADLINE_DEFAULT_S+ return value+++def _start_deferred_state_db_integrity_check(evidence: dict) -> None:+ """Run the store scan an unclean-exit report deferred, once the runner is live.++ On the event loop it held every local listener open but unanswered for the whole+ ``quick_check`` (minutes on a multi-GB ``state.db``), so local clients hung instead of being+ refused. A daemon thread nothing waits on; it only appends the forensic exit-diag record.+ """+ from agent.memory_provider import spawn_context_thread+ from gateway.lifecycle_ledger import run_deferred_integrity_check+ # Under the caller's profile scope: the scan resolves this gateway's state.db through it.+ spawn_context_thread(+ run_deferred_integrity_check, args=(evidence,),+ kwargs={"deadline_s": _state_db_integrity_deadline_s()}, name="state-db-integrity-check").start()+# Log-record parity with the origin module.logger = logging.getLogger("gateway.run")@@ -772,23 +810,26 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =from gateway.run_runtime import start_gateway_runtime_apiawait start_gateway_runtime_api(runner)- def _lifecycle_record_startup() -> None:+ def _lifecycle_record_startup() -> Optional[dict]:# Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the# sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.+ # The store scan that report used to run here is deferred: see below.from gateway.lifecycle_ledger import record_startup- record_startup()+ return record_startup()def _start_keepalive() -> None:from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalivestart_nous_auth_keepalive()- _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")+ _unclean_exit = _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")_best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")_ensure_windows_gateway_venv_imports()_early_verdict = await _start_gateway_run_runner(runner, _signal_initiated_shutdown)if _early_verdict is not None:return _early_verdict+ if _unclean_exit is not None:+ _start_deferred_state_db_integrity_check(_unclean_exit)cron_stop, cron_provider, cron_thread, housekeeping_thread = (_start_gateway_start_cron_and_housekeeping(runner))diff --git a/tests/gateway/test_bootstrap_deferred_integrity_scan.py b/tests/gateway/test_bootstrap_deferred_integrity_scan.pynew file mode 100644index 00000000000..76d3ade6993--- /dev/null+++ b/tests/gateway/test_bootstrap_deferred_integrity_scan.py@@ -0,0 +1,65 @@+"""start_gateway runs the unclean-exit state.db scan off the event loop, after the runner is live."""+import ast+import inspect+import threading++import pytest++from gateway import run_bootstrap+++def _config(monkeypatch, agent):+ from hermes_cli import config+ monkeypatch.setattr(config, "read_raw_config_readonly", lambda: {"agent": agent})++[email protected]("raw, expected", [+ (None, 1800.0), (600, 600.0), ("90", 90.0), (0.5, 0.5),+ (0, 1800.0), (-5, 1800.0), (float("inf"), 1800.0), ("1e999", 1800.0), ("nan", 1800.0),+ ("soon", 1800.0), (True, 1800.0), ([], 1800.0),+])+def test_deadline_is_finite_and_positive(monkeypatch, raw, expected):+ _config(monkeypatch, {} if raw is None else {"gateway_state_db_integrity_deadline_s": raw})+ assert run_bootstrap._state_db_integrity_deadline_s() == expected+++def test_deadline_survives_unreadable_config(monkeypatch):+ from hermes_cli import config++ def broken():+ raise OSError("unreadable")+ monkeypatch.setattr(config, "read_raw_config_readonly", broken)+ assert run_bootstrap._state_db_integrity_deadline_s() == 1800.0+++def test_scan_runs_on_a_daemon_thread_with_the_configured_deadline(monkeypatch):+ from gateway import lifecycle_ledger as ledger+ _config(monkeypatch, {"gateway_state_db_integrity_deadline_s": 42})+ seen, release, done = {}, threading.Event(), threading.Event()++ def scan(evidence, *, deadline_s):+ seen.update(evidence=evidence, deadline_s=deadline_s, thread=threading.current_thread())+ release.wait(5) # still running when the caller returns: nothing waits on it+ done.set()+ monkeypatch.setattr(ledger, "run_deferred_integrity_check", scan)++ evidence = {"prior_pid": 1234}+ run_bootstrap._start_deferred_state_db_integrity_check(evidence)+ assert not done.is_set()+ release.set()+ assert done.wait(5)+ assert seen["evidence"] is evidence and seen["deadline_s"] == 42.0+ assert seen["thread"].daemon and seen["thread"].name == "state-db-integrity-check"+++def test_start_gateway_starts_the_scan_only_after_the_runner_is_live():+ """The listeners answer from ``start_gateway_runtime_api`` on; the scan must not run before+ ``_start_gateway_run_runner`` returns, and only for an unclean previous exit."""+ tree = ast.parse(inspect.getsource(run_bootstrap.start_gateway))+ calls = [node for node in ast.walk(tree) if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)]+ line = {node.func.id: node.lineno for node in calls}+ assert line["_start_deferred_state_db_integrity_check"] > line["_start_gateway_run_runner"]+ guard = next(node for node in ast.walk(tree) if isinstance(node, ast.If) and any(+ isinstance(c, ast.Call) and getattr(c.func, "id", None) == "_start_deferred_state_db_integrity_check"+ for c in ast.walk(node)))+ assert ast.unparse(guard.test) == "_unclean_exit is not None"