Skip to content

The agent that grows with you

fix(sessions): browse also refuses a lockless legacy gateway; name the owner's restart

Teknium6fd792aa8690
diff --git a/hermes_state_reconcile.py b/hermes_state_reconcile.py
index 8b8484142be..2cba992d8c5 100644
--- a/hermes_state_reconcile.py
+++ b/hermes_state_reconcile.py
@@ -152,6 +152,40 @@ def _owner_remedy(home: Path) -> tuple[str, str]:
return label or str(home), 'hermes gateway restart'
+def _owning_gateway_restart(home: Path) -> str:
+ """Restart command for the gateway that holds *home*'s lock. A multiplexer launched from another
+ home (usually the default) records that home in ``hermes_home``; `hermes -p <named> gateway
+ restart` is refused there ("Manage the host gateway instead"), so name the owner's own command."""
+ from gateway.runtime_ownership import canonical_home
+ from gateway.status import _read_gateway_lock_record
+ record = _read_gateway_lock_record(canonical_home(home) / 'gateway.lock') or {}
+ owner_home = record.get('hermes_home')
+ if isinstance(owner_home, str) and owner_home and canonical_home(Path(owner_home)) != canonical_home(home):
+ return _owner_remedy(Path(owner_home))[1]
+ return _owner_remedy(home)[1]
+
+
+def _lockless_gateway_holder(path: Path) -> str | None:
+ """A Hermes gateway process holding *path* open without this profile's gateway.lock: a pre-v0.22.1
+ multiplexer serves named profiles without reserving their per-profile lock, so the lock alone
+ misses it. Only holders whose command line is a Hermes ``gateway`` run count; plain readers
+ (Desktop, sibling browses, CLI reads) are not owners. Returns a description, else None."""
+ from hermes_state_holders import _looks_like_hermes, _read_proc_argv, describe_holder_pid, foreign_state_db_holders
+ for pid, _target in foreign_state_db_holders(path):
+ if pid <= 0:
+ continue
+ argv = _read_proc_argv(pid)
+ if argv is None:
+ try:
+ import psutil
+ argv = psutil.Process(pid).cmdline() or None
+ except Exception:
+ argv = None
+ if argv and _looks_like_hermes(argv) and 'gateway' in argv[1:]:
+ return describe_holder_pid(pid)
+ return None
+
+
class BrowseBudgetExceeded(RuntimeError):
"""The browse reconcile could not finish inside BROWSE_RECONCILE_BUDGET_S; nothing was written."""
@@ -361,13 +395,15 @@ def reconcile_drift_for_browse(path: Path) -> bool:
f'Session store is missing its history tables ({reason}); this is not upgrade drift. '
'Run `hermes sessions recover`.') from exc
home = path.parent
- label, remedy = _owner_remedy(home)
+ label, _ = _owner_remedy(home)
- def owned(drift):
+ def owned(drift, holder=None):
+ restart = 'hermes gateway restart' if holder else _owning_gateway_restart(home)
+ who = f' ({holder})' if holder else ''
return DeclarativeDriftError(
f"Session store for profile '{label}' is behind this Hermes version ({drift}), and a "
- f'running gateway owns it, so browsing will not write to it. Restart that gateway '
- f'(`{remedy}`) to bring the store up to date.', owned=True)
+ f'running gateway owns it{who}, so browsing will not write to it. Restart that gateway '
+ f'(`{restart}`) to bring the store up to date.', owned=True)
def too_slow():
# A gateway that booted while browse was verifying the store is the real answer: name it.
@@ -389,6 +425,8 @@ def reconcile_drift_for_browse(path: Path) -> bool:
except OwnershipConflict as exc:
if live_runtime_owner(home) is not None:
raise owned(reason) from exc
+ if holder := _lockless_gateway_holder(path):
+ raise owned(reason, holder)
# Already latched corrupt in this process: do not rescan a damaged file on every poll.
if storage_state(path) == STORAGE_CORRUPT:
raise CorruptStoreError(storage_corrupt_reason(path) or 'latched corrupt')
@@ -415,6 +453,8 @@ def reconcile_drift_for_browse(path: Path) -> bool:
if current:
return False
budget = _Budget(BROWSE_RECONCILE_BUDGET_S)
+ if holder := _lockless_gateway_holder(path): # a legacy gateway started during the scan
+ raise owned(reason, holder)
if _store_signature(path) != signature:
# Written since the scan (a gateway that came and went): the scan no longer
# vouches for these bytes. Refuse; the next browse scans the new state.
diff --git a/tests/hermes_cli/test_browse_schema_drift.py b/tests/hermes_cli/test_browse_schema_drift.py
index bbf36bce677..47798f409c4 100644
--- a/tests/hermes_cli/test_browse_schema_drift.py
+++ b/tests/hermes_cli/test_browse_schema_drift.py
@@ -893,3 +893,80 @@ def test_budget_refusal_on_unowned_store_names_repair_not_a_gateway(tmp_path, mo
reconcile._scan_too_slow.clear()
_open_session_db_at_path(path, read_only=True).close()
assert "last_read_at" in _session_columns(path)
+
+
+_LEGACY_GATEWAY = r'''
+import sqlite3, sys, time
+conn = sqlite3.connect(sys.argv[1]) # what a pre-v0.22.1 multiplexer does: no per-profile gateway.lock
+conn.execute("SELECT count(*) FROM sessions").fetchone()
+print("holding", flush=True)
+time.sleep(60)
+'''
+
+
+def test_legacy_gateway_holding_the_store_without_a_lock_is_not_written(tmp_path):
+ """alt-glitch W1: a v0.22.0 multiplex gateway keeps a named profile's state.db open without writing
+ that profile's gateway.lock/gateway.pid. Browse must still treat it as the owner: no DDL, a named
+ 503. Plain readers (sibling browses, Desktop) are not owners, so only a holder identified as a
+ Hermes gateway process refuses."""
+ import os
+ import subprocess
+ import sys
+
+ home = _profile_home(tmp_path)
+ path = _lagging_store_with_history(home, rows=10)
+ before = _file_state(path)
+ legacy = subprocess.Popen(["hermes", "-c", _LEGACY_GATEWAY, str(path), "gateway", "run"],
+ executable=sys.executable, env=os.environ, stdout=subprocess.PIPE, text=True)
+ try:
+ assert legacy.stdout.readline().strip() == "holding"
+ assert not (home / "gateway.lock").exists() or not (home / "gateway.lock").read_text()
+ with pytest.raises(HTTPException) as caught:
+ _open_session_db_at_path(path, read_only=True)
+ finally:
+ legacy.kill()
+ legacy.wait()
+ assert caught.value.status_code == 503
+ assert "running gateway owns it" in caught.value.detail
+ assert f"PID {legacy.pid}" in caught.value.detail
+ assert _file_state(path) == before
+ assert "last_read_at" not in _session_columns(path)
+
+
+_MULTIPLEXER_LOCK = r'''
+import fcntl, json, os, sys, time
+fh = open(sys.argv[1], "a+")
+fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+fh.seek(0); fh.truncate()
+json.dump({"pid": os.getpid(), "kind": "hermes-gateway", "hermes_home": sys.argv[2]}, fh); fh.flush()
+print("held", flush=True)
+time.sleep(60)
+'''
+
+
[email protected]("linux", "macos")
[email protected]_gateway_lookalike
+def test_owned_refusal_names_the_owning_multiplexers_restart(tmp_path):
+ """alt-glitch W2: when the default multiplexer owns a named profile's lock, `hermes -p NAME gateway
+ restart` is refused ("Manage the host gateway instead"). Name the owner's own restart command,
+ from the lock record's hermes_home."""
+ import os
+ import subprocess
+ import sys
+
+ home = _profile_home(tmp_path)
+ path = _lagging_store_with_history(home, rows=10)
+ host = subprocess.Popen([sys.executable, "-c", _MULTIPLEXER_LOCK, str(home / "gateway.lock"), str(tmp_path)],
+ env=os.environ, stdout=subprocess.PIPE, text=True)
+ try:
+ assert host.stdout.readline().strip() == "held"
+ with pytest.raises(HTTPException) as caught:
+ _open_session_db_at_path(path, read_only=True)
+ finally:
+ host.kill()
+ host.wait()
+ detail = caught.value.detail
+ assert caught.value.status_code == 503 and "running gateway owns it" in detail
+ assert "`hermes gateway restart`" in detail
+ assert "-p scribe gateway restart" not in detail