The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve runtime authority across updater snapshot restores
Teknium8a8a13723b82
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.pyindex a2579f28a9f..b318d62e297 100644--- a/hermes_cli/update_cmd_maint.py+++ b/hermes_cli/update_cmd_maint.py@@ -461,36 +461,22 @@ def _print_update_summary(*, node_failures: list, desktop_build_ok: bool, pre_updef _restore_state_db_from_snapshot(state_path: Path, snap_state: Path) -> bool:- """Replace *state_path* with the snapshot image; True when the result passes integrity.+ """Restore through backup's authority reservation and pre-publication epoch floor.- Stale sidecars are cleared first so the corrupt DB's WAL can't replay over the image.- Refuses (False) while another process — or a live connection in THIS process — holds the- DB: copying over a live writer's inode desyncs its page cache and its next checkpoint- clobbers pages. Holder scan ``None`` proceeds (gateways drained; refusing on unknown would- disable auto-restore on non-Linux). Raises OSError if the copy fails.+ Use the single-database primitive, not whole-profile restore: post-update config+ and unrelated files must not roll back with a damaged transcript store."""- from hermes_cli.backup import _foreign_db_holder_pids, verify_sqlite_integrity- from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access- holders = _foreign_db_holder_pids(state_path)- if holders:- print(- f" ✗ Auto-restore refused: process(es) {holders} still hold "- "state.db or its WAL open. Stop them (hermes gateway stop), "- "then restore manually with /snapshot restore."- )+ from hermes_cli.backup import _safe_restore_db, verify_sqlite_integrity++ snap_state.stat() # Preserve the caller's OSError reporting for missing snapshots.+ if not verify_sqlite_integrity(snap_state, check_header=True, run_pragma=True).get("valid"):return False- # The foreign-pid scan excludes THIS process; an in-process SessionDB handle is just as- # live (it would checkpoint through deleted-inode sidecars). offline_file_access fails- # CLOSED on any tracked connection and holds the lock across clear + copy.- try:- with offline_file_access(state_path, what="restore a snapshot over"):- _clear_stale_sqlite_sidecars(state_path)- shutil.copy2(snap_state, state_path)- except LiveConnectionError as exc:- print(- f" ✗ Auto-restore refused: {exc} Close the in-process database "- "handles (or restart Hermes) and retry."- )+ if not _safe_restore_db(snap_state, state_path):+ print(" ✗ Auto-restore refused or failed; state.db was not restored.")+ print(" Stop the owning runtime and close database handles before retrying.")+ print(" If the canonical runtime epoch is unreadable, do not restore in place:")+ print(" use `hermes sessions recover --source <snapshot> --output <separate-path>`")+ print(" to salvage transcripts into a separate output.")return Falserestored = verify_sqlite_integrity(state_path, check_header=True, run_pragma=True)return bool(restored.get("valid"))@@ -524,7 +510,7 @@ def _verify_and_restore_one_state_db(home: Path, *, label: str) -> None:if _restore_state_db_from_snapshot(state_path, snap_state):print(f" ✓ Auto-restored from snapshot {snap_dir.name} ({label})")else:- print(" ✗ Auto-restore FAILED — restored copy also failed integrity")+ print(" ✗ Auto-restore did not complete; see the restore diagnostic above.")except OSError as exc:print(f" ✗ Auto-restore file copy failed: {exc}")returndiff --git a/tests/hermes_cli/test_restore_own_holder_guard.py b/tests/hermes_cli/test_restore_own_holder_guard.pyindex c5039171ad7..d2e5a6ae749 100644--- a/tests/hermes_cli/test_restore_own_holder_guard.py+++ b/tests/hermes_cli/test_restore_own_holder_guard.py@@ -150,9 +150,7 @@ def test_update_autorestore_still_works_without_holder(tmp_path):_make_db(dst, "live-old")# Stale WAL from a crashed writer must still be cleared.dst.with_name(dst.name + "-wal").write_bytes(b"\x00" * 1024)- with open(dst, "r+b") as fh:- fh.write(b"\x00" * 100)-+ # Keep the canonical epoch readable; header corruption now requires salvage.assert update_cmd._restore_state_db_from_snapshot(dst, src) is Trueassert _read_marker(dst) == "snapshot-good"assert not dst.with_name(dst.name + "-wal").exists()diff --git a/tests/hermes_cli/test_update_restore_authority.py b/tests/hermes_cli/test_update_restore_authority.pynew file mode 100644index 00000000000..28f8b94d59b--- /dev/null+++ b/tests/hermes_cli/test_update_restore_authority.py@@ -0,0 +1,123 @@+"""Maintenance must not replace the database behind a live authority."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++from tests.gateway.fixtures.local_recovery_probe import Model, daemon, rpc, websocket+++def test_restore_refuses_live_authority_without_changing_data(tmp_path):+ from hermes_cli.backup import create_quick_snapshot+ from hermes_cli.update_cmd_maint import _restore_state_db_from_snapshot++ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'fixture', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'platform_toolsets': {'cli': []},+ }))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def rows():+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return list(db.execute('SELECT request_id,status FROM session_admissions ORDER BY rowid'))++ async def exercise(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='create', source='tui', cwd=str(home), toolsets=[])+ session = created['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=session, input_id='warm', text='WARM')+ async with asyncio.timeout(30):+ while dict(rows()).get('warm') != 'terminal':+ await asyncio.sleep(.05)+ snapshot = create_quick_snapshot(hermes_home=home)+ assert snapshot, snapshot+ await rpc(ws, 'prompt.submit', session_id=session, input_id='started', text='BLOCK_STARTED')+ assert await asyncio.to_thread(peer.blocked.wait, 25)+ await rpc(ws, 'prompt.submit', session_id=session, input_id='queued', text='FOLLOWER')+ before = rows()+ assert dict(before) == {'warm': 'terminal', 'started': 'started', 'queued': 'queued'}+ import hashlib+ bundle = [Path(str(home / 'state.db') + suffix) for suffix in ('', '-wal', '-shm')]+ hashes = {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}+ restored = _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ assert hashes == {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in bundle if p.exists()}+ after = rows()+ print(json.dumps({'live_restore': restored, 'before': before, 'after': after}), flush=True)+ assert not restored and after == before+ return snapshot++ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ snapshot = asyncio.run(exercise(desc))+ old_epoch = desc['authority_epoch']+ peer.release.set()+ assert _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ assert rows() == [('warm', 'terminal')]+ with daemon(root, home, env, barrier=False) as (_, restarted):+ assert restarted['instance_id'] != desc['instance_id']+ assert restarted['authority_epoch'] > old_epoch+ assert rows() == [('warm', 'terminal')]+ later_epoch = restarted['authority_epoch']+ # Restoring the same older snapshot must not reuse a previous owner's epoch.+ assert _restore_state_db_from_snapshot(home / 'state.db', home / 'state-snapshots' / snapshot / 'state.db')+ with daemon(root, home, env, barrier=False) as (_, restored_again):+ assert restored_again['authority_epoch'] > later_epoch+ print(json.dumps({'offline_restore_restart_epochs': [old_epoch, later_epoch, restored_again['authority_epoch']],+ 'restart_instance_changed': restored_again['instance_id'] != restarted['instance_id']}), flush=True)+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)+++def test_corrupt_epoch_refuses_profile_sweep_with_separate_recovery(tmp_path, monkeypatch, capsys):+ from hermes_cli import backup, update_cmd+ from hermes_cli.session_recovery import recover_session_database+ from hermes_state import SessionDB++ homes = [tmp_path / 'default', tmp_path / 'sibling']+ originals = {}+ snapshots = {}+ for home in homes:+ home.mkdir()+ with SessionDB(db_path=home / 'state.db') as db:+ db.create_session('retained', 'cli')+ db.append_message('retained', 'user', 'snapshot transcript')+ snapshot = backup.create_quick_snapshot(hermes_home=home)+ snapshots[home] = home / 'state-snapshots' / snapshot / 'state.db'+ (home / 'state.db').write_bytes(b'unreadable canonical runtime epoch')+ originals[home] = (home / 'state.db').read_bytes(), snapshots[home].read_bytes()+ monkeypatch.setattr(update_cmd, 'get_hermes_home', lambda: homes[0])+ monkeypatch.setattr(backup, '_sibling_profile_homes', lambda home: [('work', homes[1])])+ update_cmd._verify_and_restore_state_dbs_post_update()+ output = capsys.readouterr().out+ for home in homes:+ assert ((home / 'state.db').read_bytes(), snapshots[home].read_bytes()) == originals[home]+ assert 'Auto-restored' not in output+ assert 'separate' in output and 'hermes sessions recover' in output+ assert 'restored copy also failed integrity' not in output+ for home in homes:+ report = recover_session_database(snapshots[home], home / 'recovered.db')+ assert report['verified'] and report['source_unchanged']+ with closing(sqlite3.connect(home / 'recovered.db')) as db:+ assert db.execute('SELECT content FROM messages').fetchall() == [('snapshot transcript',)]+ assert (home / 'state.db').read_bytes() == originals[home][0]diff --git a/tests/hermes_cli/test_update_state_autorestore.py b/tests/hermes_cli/test_update_state_autorestore.pyindex 7b543408350..d9023c5b5a7 100644--- a/tests/hermes_cli/test_update_state_autorestore.py+++ b/tests/hermes_cli/test_update_state_autorestore.py@@ -249,10 +249,17 @@ def test_post_update_guard_covers_sibling_profiles(tmp_path, monkeypatch, capsys_make_valid_db(root_home / "state.db", 10)root_before = (root_home / "state.db").read_bytes()- # Sibling: live DB corrupted post-update (the #68474 zeroed signature),- # with its own VALID pre-update snapshot under its own snapshots dir.+ # Corrupt only the sessions B-tree; the canonical epoch must remain readable._make_valid_snapshot(sibling_home, "20260901-pre-update", 25)- (sibling_home / "state.db").write_bytes(b"\x00" * 4096)+ state = sibling_home / "state.db"+ _make_valid_db(state, 3)+ with sqlite3.connect(state) as conn:+ page = conn.execute("SELECT rootpage FROM sqlite_master WHERE name='sessions'").fetchone()[0]+ page_size = conn.execute("PRAGMA page_size").fetchone()[0]+ conn.close()+ with state.open("r+b") as stream:+ stream.seek((page - 1) * page_size)+ stream.write(b"\x00")monkeypatch.setattr(update_cmd, "get_hermes_home", lambda: root_home)monkeypatch.setattr(@@ -269,6 +276,7 @@ def test_post_update_guard_covers_sibling_profiles(tmp_path, monkeypatch, capsys# Operator-visible restore message mentions the profile.out = capsys.readouterr().outassert "profile work" in out+ assert "✓ Auto-restored from snapshot" in outdef test_post_update_guard_leaves_valid_sibling_dbs_alone(tmp_path, monkeypatch, capsys):