Skip to content

The agent that grows with you

fix(backup): skip archive sidecars on import; count a refused live-safe restore as failed

kshitijk4poor46604fe7f499
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 5ecc8520fa5..807bccdf9b1 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -136,6 +136,8 @@ def _in_excluded_root_dir(rel_path: Path) -> bool:
# File-name suffixes to skip
+_SQLITE_SIDECAR_SUFFIXES = (".db-wal", ".db-shm", ".db-journal")
+
_EXCLUDED_SUFFIXES = (
".pyc",
".pyo",
@@ -144,9 +146,7 @@ _EXCLUDED_SUFFIXES = (
# rollback-journal alongside would pair a fresh snapshot with stale sidecar
# state and produce a torn restore on the next open. They're transient and
# regenerated on first connection anyway.
- ".db-wal",
- ".db-shm",
- ".db-journal",
+ *_SQLITE_SIDECAR_SUFFIXES,
)
# File names to skip (runtime state that's meaningless on another machine)
@@ -812,8 +812,10 @@ def _safe_restore_db(src: Path, dst: Path) -> bool:
the WAL journal is updated correctly, and all connections (old and
new) converge on the restored data.
- Falls back to the unlink+move approach on failure so restore never
- blocks on a transient error.
+ Falls back to the unlink+move approach on failure ONLY when no other
+ process or in-process connection holds the file: replacing the inode
+ under a live holder is the #90950 split-brain, so that branch fails
+ closed (returns ``False``) and the caller reports the file as skipped.
"""
try:
dst_conn = sqlite3.connect(str(dst))
@@ -1497,6 +1499,16 @@ def run_import(args) -> None:
skipped_runtime.append(rel)
continue
+ # A ``.db`` member is page-restored into the live file below; a
+ # WAL/SHM/journal member from the archive describes a different
+ # database image, and installing it beside the restored file (over
+ # a live sidecar, via os.replace) would replay a foreign WAL on
+ # the next open. Current backups never ship these
+ # (_EXCLUDED_SUFFIXES); older or hand-built archives might.
+ if rel.endswith(_SQLITE_SIDECAR_SUFFIXES):
+ skipped_runtime.append(rel)
+ continue
+
target = hermes_root / rel
# Security: reject absolute paths and traversals
@@ -2050,7 +2062,11 @@ def restore_quick_snapshot(
# (gateway, dashboard, another CLI session) see the
# restored data instead of continuing to serve stale
# cached pages from a replaced inode (issue #65942).
- _safe_restore_db(src, dst)
+ if not _safe_restore_db(src, dst):
+ # Refused (live holder) or failed: the destination was
+ # left as it was. Count it as a failure, not a restore.
+ logger.error("Failed to restore %s: live-safe restore refused", rel)
+ continue
else:
shutil.copy2(src, dst)
restored += 1
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 2bb28260707..459c5ec8b19 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -1336,6 +1336,32 @@ class TestQuickSnapshot:
assert "state.db" not in data.get("files", {})
assert "state.db" in data.get("failed_dbs", [])
+ def test_restore_refused_db_is_not_counted(self, hermes_home, monkeypatch):
+ """A refused live-safe restore (holder detected, backup leg failed) must
+ not be counted as a restored file — `hermes import` reports it, and
+ /snapshot restore must not claim success for that file either."""
+ import hermes_cli.backup as backup_mod
+ from hermes_cli.backup import create_quick_snapshot, restore_quick_snapshot
+
+ snap_id = create_quick_snapshot(hermes_home=hermes_home)
+ monkeypatch.setattr(backup_mod, "_safe_restore_db", lambda src, dst: False)
+ restored_log: list[str] = []
+ real_info = backup_mod.logger.info
+ monkeypatch.setattr(
+ backup_mod.logger, "info",
+ lambda msg, *a, **kw: restored_log.append(msg % a if a else msg) or real_info(msg, *a, **kw),
+ )
+
+ restore_quick_snapshot(snap_id, hermes_home=hermes_home)
+
+ manifest = json.loads(
+ (backup_mod._quick_snapshot_root(hermes_home) / snap_id / "manifest.json").read_text()
+ )
+ non_db = [rel for rel in manifest.get("files", {}) if not rel.endswith(".db")]
+ summary = [line for line in restored_log if line.startswith("Restored ")]
+ assert summary, restored_log
+ assert summary[-1].startswith(f"Restored {len(non_db)} files"), summary[-1]
+
def test_restore_state_db_live_connection(self, hermes_home):
"""Restoring state.db must update data visible through a live connection.
@@ -2345,6 +2371,31 @@ class TestImportLiveSessionDatabase:
# The pre-import database is still the one on disk.
assert _count_rows(live_db) == (3, 12)
+ def test_sidecar_members_are_not_installed_beside_a_restored_db(
+ self, tmp_path, monkeypatch
+ ):
+ """A `state.db-wal` member from an old/hand-built archive must not be
+ os.replace'd next to the page-restored database: it describes a
+ different image and SQLite would replay it on the next open."""
+ from hermes_cli.backup import run_import
+
+ home, live_db, zip_path = self._prepare(tmp_path, monkeypatch)
+ with zipfile.ZipFile(zip_path, "a") as zf:
+ zf.writestr("state.db-wal", b"foreign-wal-from-archive")
+ zf.writestr("state.db-shm", b"foreign-shm")
+ zf.writestr("state.db-journal", b"foreign-journal")
+
+ run_import(Namespace(zipfile=str(zip_path), force=True))
+
+ for suffix, payload in (
+ ("-wal", b"foreign-wal-from-archive"),
+ ("-shm", b"foreign-shm"),
+ ("-journal", b"foreign-journal"),
+ ):
+ sidecar = live_db.with_name("state.db" + suffix)
+ assert not sidecar.exists() or sidecar.read_bytes() != payload, suffix
+ assert _count_rows(live_db) == (2, 4)
+
def test_missing_target_takes_the_plain_publish(self, tmp_path, monkeypatch):
"""A fresh install has no inode to preserve; the member still lands."""
from hermes_cli.backup import run_import