The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: `hermes serve` stops opening state.db writable under a live gateway
teknium1b4f8d83e1294
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex fc2c0d6e46b..48cd8dcface 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -231,6 +231,14 @@ def _maybe_auto_archive_for_profile(profile: Optional[str]) -> None:cfg = (_load_full_config().get("sessions") or {})if not cfg.get("auto_archive", False):return+ from gateway.status import is_gateway_runtime_lock_active++ # A live gateway owns this profile's store and runs the same sweep in its own+ # housekeeping. Opening it WRITABLE from `hermes serve` adds a second writer to a+ # database another process is already archiving, for zero extra coverage (#110405).+ lock_path = _session_db_path_for_profile(profile).with_name("gateway.lock")+ if is_gateway_runtime_lock_active(lock_path):+ returndb = _open_session_db_for_profile(profile, read_only=False)try:db.maybe_auto_archive(diff --git a/tests/hermes_cli/test_backup_import_deleted_holder.py b/tests/hermes_cli/test_backup_import_deleted_holder.pynew file mode 100644index 00000000000..2a3e3eb6408--- /dev/null+++ b/tests/hermes_cli/test_backup_import_deleted_holder.py@@ -0,0 +1,84 @@+"""Invariant: importing a backup must not publish a NEW state.db inode while a+live process still holds the deleted one (#110179).++``_import_db_member`` guards the replace path with ``_safe_restore_db``, but the+"target is missing" branch treated absence as proof of no holders. A gateway that+had the database open when it was unlinked keeps writing the deleted inode, so an+atomic publish there re-creates exactly the #90950 split brain the branch below+avoids. The holder here is a real subprocess with a real SQLite connection.+"""++from __future__ import annotations++import sqlite3+import subprocess+import sys+import zipfile++import pytest++from hermes_cli import backup as backup_mod++pytestmark = pytest.mark.skipif(+ not sys.platform.startswith("linux"), reason="/proc holder scan is Linux-only"+)++_HOLDER = (+ "import sqlite3, sys, time\n"+ "conn = sqlite3.connect(sys.argv[1])\n"+ "conn.execute('SELECT count(*) FROM t').fetchone()\n"+ "sys.stdout.write('held\\n')\n"+ "sys.stdout.flush()\n"+ "time.sleep(300)\n"+)++_MEMBER = "hermes/state.db"+++def _make_db(path, marker):+ conn = sqlite3.connect(str(path))+ conn.execute("CREATE TABLE t (v TEXT)")+ conn.execute("INSERT INTO t VALUES (?)", (marker,))+ conn.commit()+ conn.close()+++def test_import_refuses_to_publish_over_a_deleted_but_held_database(tmp_path):+ target = tmp_path / "state.db"+ _make_db(target, "live")+ archive = tmp_path / "backup.zip"+ payload = tmp_path / "archived.db"+ _make_db(payload, "from-archive")+ with zipfile.ZipFile(archive, "w") as zf:+ zf.write(payload, _MEMBER)++ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLDER, str(target)],+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,+ )+ stdout = holder.stdout+ assert stdout is not None+ try:+ assert stdout.readline().strip() == "held"+ target.unlink() # the deleted-inode window: holder keeps writing it+ assert backup_mod._foreign_db_holder_pids(target) == [holder.pid]++ with zipfile.ZipFile(archive) as zf:+ with pytest.raises(OSError) as excinfo:+ backup_mod._import_db_member(zf, _MEMBER, target)++ assert str(holder.pid) in str(excinfo.value)+ assert not target.exists(), "a new inode was published under a live holder"+ finally:+ holder.terminate() # by PID: the process this test spawned+ holder.wait(timeout=10)+ stdout.close()++ # No holder left: the ordinary atomic publish still applies.+ with zipfile.ZipFile(archive) as zf:+ backup_mod._import_db_member(zf, _MEMBER, target)+ conn = sqlite3.connect(str(target))+ try:+ assert conn.execute("SELECT v FROM t").fetchone()[0] == "from-archive"+ finally:+ conn.close()diff --git a/tests/hermes_cli/test_session_recovery_model_config.py b/tests/hermes_cli/test_session_recovery_model_config.pynew file mode 100644index 00000000000..3462b28c533--- /dev/null+++ b/tests/hermes_cli/test_session_recovery_model_config.py@@ -0,0 +1,57 @@+"""Invariant: session recovery neutralises unparseable ``sessions.model_config``.++``integrity_check`` never looks at column contents, so a source whose JSON was+truncated by the damage recovers "clean" and the recovered store then raises+``OperationalError: malformed JSON`` the first time a caller resumes a parent+session (``reopen_session`` rewrites reset-child markers with ``json_set``).+Both recovery lanes pass through ``_finalize_derived_metadata``, so the reset+belongs there rather than in either lane's copy loop.+"""++from __future__ import annotations++import sqlite3+from pathlib import Path++from hermes_state import SessionDB+from hermes_cli.session_recovery import recover_session_database++_TRUNCATED_JSON = '{"model": "sonnet", "cw'+++def _damaged_source(path: Path) -> None:+ """A structurally healthy DB whose child row carries truncated model_config JSON."""+ db = SessionDB(db_path=path)+ try:+ db.create_session("parent", "telegram", session_key="telegram:u:c")+ db.append_message("parent", "user", "hello")+ db.end_session("parent", "session_reset")+ db.create_session("child", "telegram", session_key="telegram:u:c", parent_session_id="parent")+ finally:+ db.close()+ raw = sqlite3.connect(str(path))+ try:+ raw.execute("UPDATE sessions SET model_config = ? WHERE id = 'child'", (_TRUNCATED_JSON,))+ raw.commit()+ finally:+ raw.close()+++def test_recovery_resets_unparseable_model_config(tmp_path):+ source = tmp_path / "state.db"+ output = tmp_path / "recovered.db"+ _damaged_source(source)++ report = recover_session_database(source, output)++ assert report["verification"]["healthy"], report["verification"]["errors"]+ assert report["derived_metadata"]["model_config_reset"] == 1++ recovered = SessionDB(db_path=output)+ try:+ # The blob was unrecoverable; what matters is that the store still works.+ row = recovered.get_session("child")+ assert row is not None and row["model_config"] == "{}"+ recovered.reopen_session("parent")+ finally:+ recovered.close()diff --git a/tests/hermes_cli/test_web_server_auto_archive_gateway_lock.py b/tests/hermes_cli/test_web_server_auto_archive_gateway_lock.pynew file mode 100644index 00000000000..cb7216e4c80--- /dev/null+++ b/tests/hermes_cli/test_web_server_auto_archive_gateway_lock.py@@ -0,0 +1,98 @@+"""Invariant: `hermes serve`'s opportunistic auto-archive never opens a WRITABLE+SessionDB for a profile whose gateway holds the runtime lock (#110405).++The lock holder is a real subprocess taking the same ``flock(LOCK_EX)`` on+``gateway.lock`` that ``gateway.status`` uses, so the guard is exercised against+kernel lock state rather than a patched predicate.+"""++from __future__ import annotations++import subprocess+import sys+import time++import pytest++from gateway.status import is_gateway_runtime_lock_active+from hermes_cli import web_server_sessions as wss++pytestmark = pytest.mark.skipif(+ sys.platform.startswith("win"), reason="POSIX flock holder"+)++_HOLDER = (+ "import fcntl, sys, time\n"+ "handle = open(sys.argv[1], 'a+')\n"+ "fcntl.flock(handle.fileno(), fcntl.LOCK_EX)\n"+ "sys.stdout.write('locked\\n')\n"+ "sys.stdout.flush()\n"+ "time.sleep(300)\n"+)+++class _FakeDB:+ def __init__(self, archived):+ self._archived = archived++ def maybe_auto_archive(self, **kwargs):+ self._archived.append(kwargs)++ def close(self):+ pass+++def archive_probe(tmp_path, monkeypatch):+ """Route the sweep at an isolated profile home and record every open."""+ db_path = tmp_path / "state.db"+ db_path.touch()+ opens: list[bool] = []+ archived: list[dict] = []++ monkeypatch.setattr(wss, "_session_db_path_for_profile", lambda profile: db_path)+ monkeypatch.setattr(wss, "_last_auto_archive_check", {})++ def _open(profile, *, read_only):+ opens.append(read_only)+ return _FakeDB(archived)++ monkeypatch.setattr(wss, "_open_session_db_for_profile", _open)+ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda *a, **k: {"sessions": {"auto_archive": True, "min_interval_hours": 0}},+ )+ return tmp_path, opens, archived+++def test_serve_auto_archive_defers_to_the_gateway_holding_the_runtime_lock(archive_probe):+ tmp_path, opens, archived = archive_probe+ lock_path = tmp_path / "gateway.lock"+ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLDER, str(lock_path)],+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,+ )+ stdout = holder.stdout+ assert stdout is not None+ try:+ assert stdout.readline().strip() == "locked"++ wss._maybe_auto_archive_for_profile(None)++ assert opens == [], "serve opened the store while the gateway owned it"+ assert archived == []+ finally:+ holder.terminate() # by PID: the process this test spawned+ holder.wait(timeout=10)+ stdout.close()++ # Lock released: the serve-side sweep is the only archiver left and must run.+ deadline = time.monotonic() + 5+ while is_gateway_runtime_lock_active(lock_path) and time.monotonic() < deadline:+ time.sleep(0.05)+ wss._last_auto_archive_check.clear()++ wss._maybe_auto_archive_for_profile(None)++ assert opens == [False], "serve must still archive when no gateway holds the lock"+ assert len(archived) == 1