Skip to content

The agent that grows with you

fix: fence canonical recovery output and report excluded runtime state

Teknium43f62e7af9f2
diff --git a/hermes_cli/session_recovery.py b/hermes_cli/session_recovery.py
index 7b09f119014..b2f25bed91b 100644
--- a/hermes_cli/session_recovery.py
+++ b/hermes_cli/session_recovery.py
@@ -42,7 +42,14 @@ _AUXILIARY_TABLE_SCHEMAS: dict[str, Callable[[sqlite3.Connection], None]] = {
"delivery_obligations": _init_delivery_ledger_schema,
}
_AUXILIARY_TABLES = tuple(_AUXILIARY_TABLE_SCHEMAS)
-_INVENTORY_TABLES = (*_CANONICAL_TABLES, "state_meta", *_TOPIC_TABLES, *_AUXILIARY_TABLES)
+# Salvage is a transcript output, not a runnable clone of accepted work. Copying
+# only part of this ledger could replay already-started effects or adopt workers
+# from another owner. Inventory and report the exclusions rather than losing them
+# silently. Activation under exclusive ownership creates a fresh runtime epoch;
+# ordinary full backup/restore instead preserves the complete ledger for startup
+# reconciliation (started -> unknown; never blindly replay started work).
+_RUNTIME_TABLES = ("runtime_epoch", "session_admissions", "worker_executions", "worker_receipts")
+_INVENTORY_TABLES = (*_CANONICAL_TABLES, "state_meta", *_TOPIC_TABLES, *_AUXILIARY_TABLES, *_RUNTIME_TABLES)
# Derived-index / optional-schema markers: a fresh destination regenerates these, never copies them.
_GENERATED_META_KEYS = frozenset({
@@ -1061,12 +1068,40 @@ def _recovery_report(
"partial": bool(verification.get("loss_detected")),
"verified": bool(verification.get("healthy") and source_unchanged),
"installed": False,
+ "runtime_state": {
+ "policy": "transcript-only; runtime ledger excluded; fresh epoch on activation",
+ "excluded_tables": {table: inspection["tables"].get(table, {}) for table in _RUNTIME_TABLES},
+ },
}
def recover_session_database(
source_path: Path, output_path: Path, *, work_dir: Optional[Path] = None, chunk_size: int = 1_000,
progress_cb: Optional[ProgressCallback] = None, allow_partial: bool = False,
+) -> dict[str, Any]:
+ """Separate-output salvage is allowed; a canonical output requires offline ownership."""
+ from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
+ from contextlib import nullcontext
+ # Validate before creating any lock or output. Reserve only a canonical
+ # destination, not the live source or an unrelated requested output file.
+ _, output, _ = _validate_paths(source_path, output_path=output_path, work_dir=work_dir)
+ assert output is not None
+ guard = exclusive_maintenance([output.parent]) if output.name == 'state.db' else nullcontext()
+ try:
+ with guard:
+ # Repeat the no-overwrite validation under the reservation: startup
+ # may have created state.db between the first check and lock claim.
+ return _recover_session_database_output(
+ source_path, output_path, work_dir=work_dir, chunk_size=chunk_size,
+ progress_cb=progress_cb, allow_partial=allow_partial,
+ )
+ except OwnershipConflict as exc:
+ raise SessionRecoverySafetyError(str(exc)) from exc
+
+
+def _recover_session_database_output(
+ source_path: Path, output_path: Path, *, work_dir: Optional[Path] = None, chunk_size: int = 1_000,
+ progress_cb: Optional[ProgressCallback] = None, allow_partial: bool = False,
) -> dict[str, Any]:
"""Recover canonical rows into a separate current-schema database. The source and its sidecars are
copied before SQLite opens anything; ``output_path`` must not exist and is never swapped into place."""
diff --git a/tests/hermes_cli/test_runtime_maintenance_exclusion.py b/tests/hermes_cli/test_runtime_maintenance_exclusion.py
index a5ce6413d2b..710608a7c32 100644
--- a/tests/hermes_cli/test_runtime_maintenance_exclusion.py
+++ b/tests/hermes_cli/test_runtime_maintenance_exclusion.py
@@ -74,3 +74,101 @@ def test_restore_refuses_live_authority_without_changing_data(tmp_path):
peer.shutdown()
peer.server_close()
thread.join(timeout=5)
+
+
+def test_import_and_startup_exclude_each_other_before_publication(tmp_path, monkeypatch):
+ import subprocess
+ import sys
+ import zipfile
+ from gateway.runtime_ownership import ProfileOwnership
+ from hermes_cli import backup
+
+ home = tmp_path / 'state'
+ home.mkdir(mode=0o700)
+ archive = tmp_path / 'restore.zip'
+ with sqlite3.connect(tmp_path / 'donor.db') as db:
+ db.execute('CREATE TABLE marker(value TEXT)')
+ db.execute("INSERT INTO marker VALUES('restored')")
+ with zipfile.ZipFile(archive, 'w') as zf:
+ zf.writestr('config.yaml', 'gateway: {multiplex_profiles: false}\n')
+ zf.write(tmp_path / 'donor.db', 'state.db')
+ arrived, release = threading.Event(), threading.Event()
+ publish = backup._extract_member_atomically
+
+ def barrier(*args, **kwargs):
+ arrived.set()
+ assert release.wait(30)
+ return publish(*args, **kwargs)
+
+ monkeypatch.setattr(backup, '_extract_member_atomically', barrier)
+ results = []
+
+ def restore():
+ with zipfile.ZipFile(archive) as zf:
+ results.append(backup._import_members(zf, zf.namelist(), '', home, 2))
+
+ thread = threading.Thread(target=restore)
+ thread.start()
+ try:
+ assert arrived.wait(20)
+ root = Path(__file__).resolve().parents[2]
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(tmp_path / 'user'), HERMES_HOME=str(home), PYTHONPATH=str(root))
+ contender = subprocess.run([sys.executable, '-c',
+ "import logging, runpy; logging.basicConfig(level=logging.INFO); runpy.run_module('gateway.run', run_name='__main__')"], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=25)
+ assert 'already owns profile' in contender.stdout + contender.stderr, contender
+ assert not (home / 'state.db').exists()
+ finally:
+ release.set()
+ thread.join(timeout=30)
+ assert not thread.is_alive() and results[0][0] == 2 and not results[0][2], results
+ # Startup has reserved but not published a PID or opened the database.
+ owner = ProfileOwnership()
+ owner.reserve([home])
+ try:
+ before = (home / 'config.yaml').read_bytes(), (home / 'state.db').read_bytes()
+ restore()
+ assert results[-1][0] == 0 and 'maintenance refused' in results[-1][2][0]
+ assert before == ((home / 'config.yaml').read_bytes(), (home / 'state.db').read_bytes())
+ finally:
+ owner.close()
+
+
+def test_recovery_output_exemption_excludes_canonical_activation(tmp_path):
+ import hashlib
+ import pytest
+ from gateway.runtime_ownership import ProfileOwnership
+ from hermes_cli.session_recovery import recover_session_database, SessionRecoverySafetyError
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch, admit_session_input
+
+ source_home, target_home = tmp_path / 'source', tmp_path / 'target'
+ source_home.mkdir()
+ target_home.mkdir()
+ source = source_home / 'state.db'
+ owner = ProfileOwnership()
+ owner.reserve([source_home, target_home])
+ try:
+ with SessionDB(db_path=source) as db:
+ db.create_session('retained', 'cli')
+ db.append_message('retained', 'user', 'retained content')
+ epoch = begin_runtime_epoch(db, instance_id='source-owner')
+ admit_session_input(db, epoch=epoch, principal_id='fixture', session_id='retained',
+ request_id='pending', payload={'text': 'must not execute in salvage'})
+ before = hashlib.sha256(source.read_bytes()).hexdigest()
+ with pytest.raises(SessionRecoverySafetyError, match='maintenance refused'):
+ recover_session_database(source, target_home / 'state.db')
+ assert not (target_home / 'state.db').exists()
+ report = recover_session_database(source, target_home / 'recovered.db')
+ assert report['verified'] and report['source_unchanged'], report
+ assert report['runtime_state']['excluded_tables']['session_admissions']['rows'] == 1
+ with sqlite3.connect(target_home / 'recovered.db') as db:
+ assert db.execute('SELECT content FROM messages').fetchall() == [('retained content',)]
+ assert db.execute('SELECT COUNT(*) FROM session_admissions').fetchone()[0] == 0
+ assert db.execute('SELECT COUNT(*) FROM runtime_epoch').fetchone()[0] == 0
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == before
+ finally:
+ owner.close()
+ report = recover_session_database(source, target_home / 'state.db')
+ assert report['verified'] and not report['installed']