The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): include the rollback journal in the forensic backup
kshitij5777e68b3ded
diff --git a/hermes_state.py b/hermes_state.pyindex bd19621b48e..c067afb1c4c 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1854,6 +1854,14 @@ def _bump_schema_cookie(conn: sqlite3.Connection) -> None:_MAX_PERSISTENT_REPAIR_ATTEMPTS = 3_MAX_MALFORMED_BACKUPS = 3+# Sidecars copied alongside a damaged DB and pruned with it. ``-journal`` is+# included because rollback-journal (DELETE) mode — Hermes's fallback on+# NFS/SMB/FUSE/ZFS and on WAL-reset-vulnerable SQLite builds — leaves a hot+# journal on disk whenever a transaction was open, and that file is what+# interprets the damaged bytes. Omitting it from the forensic copy means the+# backup cannot be rolled back to a consistent state by hand.+_DB_SIDECAR_SUFFIXES = ("-wal", "-shm", "-journal")+# Head/tail bytes sampled by ``_db_fingerprint``. Enough to change whenever# the DB is genuinely repaired, truncated or restored (SQLite rewrites the# header on any real recovery), while staying O(1) on a multi-GB file.@@ -2080,7 +2088,7 @@ def _existing_malformed_backups(db_path: Path) -> "List[Path]":pfor p in db_path.parent.iterdir()if p.name.startswith(prefix)- and not p.name.endswith(("-wal", "-shm"))+ and not p.name.endswith(_DB_SIDECAR_SUFFIXES)]except OSError:return []@@ -2092,8 +2100,7 @@ def _prune_malformed_backups(db_path: Path, keep: int = _MAX_MALFORMED_BACKUPS)for stale in _existing_malformed_backups(db_path)[keep:]:for victim in (stale,- stale.with_name(stale.name + "-wal"),- stale.with_name(stale.name + "-shm"),+ *(stale.with_name(stale.name + suffix) for suffix in _DB_SIDECAR_SUFFIXES),):try:victim.unlink(missing_ok=True)@@ -2191,7 +2198,7 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":# Refuse while there is still room to refuse in.try:need = db_path.stat().st_size- for suffix in ("-wal", "-shm"):+ for suffix in _DB_SIDECAR_SUFFIXES:sidecar = db_path.with_name(db_path.name + suffix)if sidecar.exists():need += sidecar.stat().st_size@@ -2236,7 +2243,7 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":try:shutil.copy2(db_path, staging)staged.append((staging, backup_path))- for suffix in ("-wal", "-shm"):+ for suffix in _DB_SIDECAR_SUFFIXES:sidecar = db_path.with_name(db_path.name + suffix)if sidecar.exists():side_staging = staging.with_name(staging.name + suffix)diff --git a/tests/test_state_db_repair_loop_mtime.py b/tests/test_state_db_repair_loop_mtime.pyindex 4abb7946c2b..872c5d9789c 100644--- a/tests/test_state_db_repair_loop_mtime.py+++ b/tests/test_state_db_repair_loop_mtime.py@@ -618,3 +618,62 @@ def test_genuine_recovery_still_resets_the_budget(tmp_path):with open(db, "r+b") as handle:handle.truncate(4096)assert _db_fingerprint(db) != before, "truncation left the fingerprint unchanged"+++def test_forensic_backup_includes_the_rollback_journal(tmp_path):+ """DELETE mode leaves a hot -journal, and that file interprets the damage.++ Rollback-journal mode is Hermes's fallback on NFS/SMB/FUSE/ZFS and on+ WAL-reset-vulnerable SQLite builds. A forensic copy without the journal+ cannot be rolled back to a consistent state by hand.+ """+ db = _damaged_db(tmp_path, size=20_000)+ for suffix, payload in (("-wal", b"WALDATA"), ("-journal", b"JOURNALDATA")):+ db.with_name(db.name + suffix).write_bytes(payload)++ roomy = type(+ "Usage", (), {"total": 500_000_000_000, "used": 0, "free": 400_000_000_000}+ )()+ with patch("shutil.disk_usage", return_value=roomy):+ path, reason = _backup_db_file(db)+ assert reason is None and path is not None++ journal_copy = path.with_name(path.name + "-journal")+ assert journal_copy.exists(), "the rollback journal was left out of the backup"+ assert journal_copy.read_bytes() == b"JOURNALDATA"+ assert path.with_name(path.name + "-wal").read_bytes() == b"WALDATA"++ # Sidecar copies must not inflate the retention count.+ assert len(_existing_malformed_backups(db)) == 1+++def test_prune_removes_journal_sidecars_too(tmp_path):+ """Otherwise the retention cap leaks one -journal per pruned backup."""+ db = _damaged_db(tmp_path, size=20_000)+ db.with_name(db.name + "-journal").write_bytes(b"J")+ roomy = type(+ "Usage", (), {"total": 500_000_000_000, "used": 0, "free": 400_000_000_000}+ )()+ for _ in range(_MAX_MALFORMED_BACKUPS + 2):+ db.write_bytes(b"SQLite format 3\x00" + os.urandom(20_000))+ with patch("shutil.disk_usage", return_value=roomy):+ _backup_db_file(db)++ kept = _existing_malformed_backups(db)+ assert len(kept) <= _MAX_MALFORMED_BACKUPS++ # Assert on what is ON DISK rather than on the paths returned earlier: a+ # same-second stamp collision means an earlier return value can name a file+ # a later pass legitimately recreated.+ kept_names = {p.name for p in kept}+ orphans = [+ p.name+ for p in tmp_path.iterdir()+ if p.name.endswith("-journal")+ and ".malformed-backup-" in p.name+ and p.name[: -len("-journal")] not in kept_names+ ]+ assert not orphans, f"pruned backups left journals behind: {orphans}"+ # And every surviving backup keeps its journal.+ for survivor in kept:+ assert survivor.with_name(survivor.name + "-journal").exists()