The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): stop backup staging from posing as a forensic copy
kshitij8de64b163423
diff --git a/hermes_state.py b/hermes_state.pyindex cfe94c98071..eb1dddf2c67 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -2094,6 +2094,23 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":)seq += 1try:+ # Sweep staging debris from an earlier interrupted pass (kill mid-copy)+ # BEFORE the dedupe below. A leftover staging file is a byte-identical+ # copy of the damaged DB, so its fingerprint MATCHES and the dedupe+ # would otherwise hand it back as a legitimate forensic backup.+ # Matches sidecar staging names (``.backup-staging-<stamp>-wal``) too.+ # The second pattern is the pre-merge ``.incomplete`` spelling, swept so+ # a host that ran that build does not keep prefix-matching debris that+ # sorts NEWEST and survives prune forever.+ for pattern in (+ f"{db_path.name}.backup-staging-*",+ f"{db_path.name}.malformed-backup-*.incomplete*",+ ):+ for old in db_path.parent.glob(pattern):+ try:+ old.unlink(missing_ok=True)+ except OSError: # pragma: no cover - best effort+ pass# Dedupe (#86747): a repair loop used to copy the SAME damaged bytes# on every restart — ~900MB a pass, 89GB over 11 days in the# reporting install. If the newest existing backup already matches@@ -2153,22 +2170,19 @@ def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":)logger.error("Refusing forensic backup of %s: %s", db_path, reason)return None, reason- # Copy to a staging name that does NOT match the backup prefix, then- # rename into place only once every copy has succeeded. A copy that- # fails partway (ENOSPC, kill) would otherwise leave a prefix-matching- # partial that `_prune_malformed_backups` never reaches — prune runs- # only on the success path — so debris accumulated unbounded and, on a- # later successful pass, the newest-by-name partials were KEPT while- # intact forensic copies were pruned away.- staging = db_path.with_name(f"{backup_path.name}.incomplete")+ # Copy to a staging name OUTSIDE the ``.malformed-backup-`` prefix, then+ # rename into place only once every copy has succeeded. The prefix+ # matters: ``_existing_malformed_backups`` matches on+ # ``startswith(f"{db}.malformed-backup-")`` and excludes only ``-wal``/+ # ``-shm`` suffixes, so a staging name derived from the backup name (e.g.+ # ``…malformed-backup-<stamp>.incomplete``) still counts as a backup —+ # it sorts NEWEST (``.incomplete`` > the bare stamp), so prune's+ # keep-3-newest slice retained partials and deleted intact copies, and+ # the dedupe could hand a partial back as the official ``backup_path``,+ # passing the #69603 hard-stop gate with no real forensic copy on disk.+ staging = db_path.with_name(f"{db_path.name}.backup-staging-{stamp}")staged: "List[Tuple[Path, Path]]" = []try:- # Clear debris from an earlier interrupted pass (kill mid-copy).- # Matches sidecar staging names (``.incomplete-wal``) too.- for old in db_path.parent.glob(- f"{db_path.name}.malformed-backup-*.incomplete*"- ):- old.unlink(missing_ok=True)shutil.copy2(db_path, staging)staged.append((staging, backup_path))for suffix in ("-wal", "-shm"):diff --git a/tests/test_state_db_repair_loop_mtime.py b/tests/test_state_db_repair_loop_mtime.pyindex b0fc6b8701c..3d1276f0d1d 100644--- a/tests/test_state_db_repair_loop_mtime.py+++ b/tests/test_state_db_repair_loop_mtime.py@@ -220,7 +220,9 @@ def test_failed_copy_leaves_no_countable_debris(tmp_path):with patch("shutil.disk_usage", return_value=roomy):path, reason = _backup_db_file(db)assert reason is None and path is not None- strays = list(tmp_path.glob("*.incomplete*"))+ strays = list(tmp_path.glob("*.backup-staging-*")) + list(+ tmp_path.glob("*.incomplete*")+ )assert not strays, f"staging debris survived: {strays}"@@ -361,6 +363,89 @@ def test_live_connection_keeps_its_write_lock_across_a_repair_pass(tmp_path):live.close()+# ---------------------------------------------------------------------------+# Staging must never be mistaken for a forensic backup+# ---------------------------------------------------------------------------+++def test_staging_name_is_outside_the_backup_prefix(tmp_path):+ """Whatever staging name the code picks must not be counted as a backup.++ Observes the REAL staging path (captured from the copy call) rather than+ hardcoding it, so the assertion binds to the invariant instead of to+ today's spelling. ``_existing_malformed_backups`` matches+ ``startswith(f"{db}.malformed-backup-")`` and excludes only ``-wal``/+ ``-shm``, so a staging name derived from the backup name sorts NEWEST and+ prune keeps partials while deleting intact copies.+ """+ db = _damaged_db(tmp_path, size=20_000)+ roomy = type(+ "Usage", (), {"total": 500_000_000_000, "used": 0, "free": 400_000_000_000}+ )()+ real_copy2 = shutil.copy2+ staging_names: list[str] = []++ def capture(src, dst, *a, **kw):+ staging_names.append(Path(dst).name)+ return real_copy2(src, dst, *a, **kw)++ with patch("shutil.disk_usage", return_value=roomy), \+ patch("shutil.copy2", capture):+ path, reason = _backup_db_file(db)++ assert reason is None and path is not None+ assert staging_names, "no copy was made (fixture problem)"+ prefix = f"{db.name}.malformed-backup-"+ for name in staging_names:+ assert not name.startswith(prefix), (+ f"staging name {name!r} matches the backup prefix — it would be "+ "counted by _existing_malformed_backups, sort NEWEST, and let "+ "prune keep partials while deleting intact forensic copies"+ )+++def test_orphaned_staging_is_never_returned_as_the_backup_path(tmp_path):+ """A kill mid-copy leaves a byte-identical staging file; the dedupe must+ not hand it back as the official ``backup_path``.++ It would pass the #69603 hard-stop gate — repair then runs destructive+ surgery believing a forensic copy exists — and the next pass's sweep+ deletes that very file.+ """+ db = _damaged_db(tmp_path, size=20_000)+ roomy = type(+ "Usage", (), {"total": 500_000_000_000, "used": 0, "free": 400_000_000_000}+ )()++ # Discover the staging name the implementation actually uses, then plant an+ # orphan under it — so this binds to the code's scheme, not to a literal.+ real_copy2 = shutil.copy2+ seen: list[Path] = []++ def capture(src, dst, *a, **kw):+ seen.append(Path(dst))+ return real_copy2(src, dst, *a, **kw)++ with patch("shutil.disk_usage", return_value=roomy), \+ patch("shutil.copy2", capture):+ first, _ = _backup_db_file(db)+ assert first is not None+ Path(first).unlink(missing_ok=True)+ orphan = seen[0]+ shutil.copy2(db, orphan) # identical bytes => fingerprint matches+ assert orphan.exists()++ with patch("shutil.disk_usage", return_value=roomy):+ path, reason = _backup_db_file(db)++ assert reason is None and path is not None+ assert Path(path) != orphan, f"staging returned as the backup: {path}"+ assert not str(path).endswith(".incomplete")+ assert "staging" not in Path(path).name+ assert Path(path).exists()+ assert not orphan.exists(), "stale staging debris was not swept"++def test_backup_refused_when_free_space_cannot_be_determined(tmp_path):"""Fail CLOSED: a nearly-full volume is where disk_usage is likeliest tofail, and proceeding is the multi-GB copy that finishes off the disk."""