The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: ZIP recovery deletes a backup temp only on the identity the swap journaled
Tekniumf1196a55f047
diff --git a/hermes_cli/_early_recovery_zip.py b/hermes_cli/_early_recovery_zip.pyindex f3d07fd2fa8..bc060473548 100644--- a/hermes_cli/_early_recovery_zip.py+++ b/hermes_cli/_early_recovery_zip.py@@ -83,22 +83,24 @@ def zip_swap_owner_lock(root: Path, *, wait: float = 0.0):os.close(fd)-def write_zip_swap_journal(root: Path, phase: str, entries: list, gen: str) -> None:+def write_zip_swap_journal(root: Path, phase: str, entries: list, gen: str, temps: dict | None = None) -> None:"""Publish the swap journal: ``entries`` are ``[name, existed, staged_id, live_id]`` (ids from- ``zip_entry_identity``, "" while unknown); ``gen`` is the run's random tag (its backup temps)."""+ ``zip_entry_identity``, "" while unknown); ``gen`` is the run's random tag (its backup temps);+ ``temps`` maps each backup temp the swap created (its file name) to its ``filling`` identity."""import json- write_durable_text(Path(root) / ZIP_SWAP_JOURNAL,- json.dumps({"pid": os.getpid(), "gen": gen, "phase": phase, "entries": entries}))+ write_durable_text(Path(root) / ZIP_SWAP_JOURNAL, json.dumps(+ {"pid": os.getpid(), "gen": gen, "phase": phase, "entries": entries, "temps": temps or {}}))-def zip_entry_identity(path) -> str:+def zip_entry_identity(path, *, filling: bool = False) -> str:"""The entry's own identity (lstat, never its target); "" when absent or unidentifiable.The ZIP journal's provenance: recovery deletes only an entry whose identity it recorded when theswap made it (a staging copy, or the live entry its backup links/renames), never a lookalike. Anon-directory adds size and mtime: a file deleted and recreated often gets the same inode back.- A directory is ``dev:ino:type`` only: a staged tree's own mtime moves while it is being filled."""+ A directory, or a file still being written (``filling``), is ``dev:ino:type`` only: its own size+ and mtime move while it is being filled."""try:st = os.lstat(path)except OSError:@@ -106,7 +108,7 @@ def zip_entry_identity(path) -> str:if not st.st_ino:return ""base = f"{st.st_dev}:{st.st_ino}:{stat.S_IFMT(st.st_mode):o}"- return base if stat.S_ISDIR(st.st_mode) else f"{base}:{st.st_size}:{st.st_mtime_ns}"+ return base if filling or stat.S_ISDIR(st.st_mode) else f"{base}:{st.st_size}:{st.st_mtime_ns}"def _drop_path(path: Path) -> None:@@ -138,8 +140,9 @@ def _drop_path(path: Path) -> None:path.unlink()-def _parse_zip_swap_journal(raw: str) -> tuple[str, str, list[tuple[str, bool, str, str]]] | None:- """``(phase, gen, [(entry name, existed, staged_id, live_id)])`` from a journal this code wrote, else None."""+def _parse_zip_swap_journal(raw: str) -> tuple[str, str, list[tuple[str, bool, str, str]], dict[str, str]] | None:+ """``(phase, gen, [(entry name, existed, staged_id, live_id)], temps)`` from a journal this code wrote,+ else None. A journal without ``temps`` (an older writer's) vouches for no backup temp."""import jsontry:@@ -155,7 +158,10 @@ def _parse_zip_swap_journal(raw: str) -> tuple[str, str, list[tuple[str, bool, sand isinstance(e[1], bool) and e[0] not in ("", ".", "..") and "/" not in e[0] and "\\" not in e[0]for e in entries):return None- return data["phase"], gen, [(name, existed, staged, live) for name, existed, staged, live in entries]+ temps = data.get("temps", {})+ if not isinstance(temps, dict) or not all(isinstance(v, str) for v in temps.values()):+ return None+ return data["phase"], gen, [(name, existed, staged, live) for name, existed, staged, live in entries], tempsdef _discard_unless_owned(path: Path, identity: str, kept: list[Path]) -> None:@@ -169,7 +175,8 @@ def _discard_unless_owned(path: Path, identity: str, kept: list[Path]) -> None:kept.append(_keep_aside(path))-def _settle_zip_entry(root: Path, phase: str, gen: str, entry: tuple[str, bool, str, str], kept: list[Path]) -> bool:+def _settle_zip_entry(root: Path, phase: str, gen: str, entry: tuple[str, bool, str, str], temps: dict[str, str],+ kept: list[Path]) -> bool:"""Finish or roll back one journaled entry; True when the live tree changed.Presence is the ENTRY's (lexists/lstat), never its target's: a dangling symlink backup is the only@@ -201,18 +208,24 @@ def _settle_zip_entry(root: Path, phase: str, gen: str, entry: tuple[str, bool,for leftover, identity in ((staging, staged_id), (old, live_id)):_discard_unless_owned(leftover, identity, kept)# ``<old>.<gen>.tmp``: a backup copy of the live file killed before its rename (no-hardlink file- # systems). The tag names it but proves nothing about the bytes (F78): only a prefix of the live- # file is that copy; anything else at the name is kept aside.+ # systems). Neither the tag nor the bytes prove a file there is that copy (F78/F78-R): only the+ # identity the swap journaled the moment it created the temp does. A file system that hands a+ # recreated name its old inode (FAT, where this copy runs) would let that record vouch for a+ # later file too, so the bytes must also be what a killed copy is: a prefix of the live file.tmp = Path(f"{old}.{gen}.tmp")- if here(tmp):- regular = [p.is_file() and not p.is_symlink() for p in (tmp, dst)]- if all(regular) and dst.read_bytes().startswith(tmp.read_bytes()):- _drop_path(tmp)- else:- kept.append(_keep_aside(tmp))+ if _is_killed_backup_copy(tmp, dst, temps.get(tmp.name, "")):+ _drop_path(tmp)+ elif here(tmp):+ kept.append(_keep_aside(tmp))return changed+def _is_killed_backup_copy(tmp: Path, dst: Path, identity: str) -> bool:+ """The identity matches the regular file the swap recorded (type included), so the bytes are readable."""+ return (bool(identity) and zip_entry_identity(tmp, filling=True) == identity+ and dst.is_file() and not dst.is_symlink() and dst.read_bytes().startswith(tmp.read_bytes()))++def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:"""Finish or roll back a ZIP swap whose owner died; True when the tree changed (relaunch).@@ -246,13 +259,13 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:"it and every `*.hermes-update-old` backup were kept. Put back what each backup replaced ""(or reinstall), then delete the journal.", file=sys.stderr)return False- phase, gen, entries = parsed+ phase, gen, entries, temps = parsedchanged = Falsefailed = Falsekept: list[Path] = []for entry in reversed(entries):try:- changed = _settle_zip_entry(root, phase, gen, entry, kept) or changed+ changed = _settle_zip_entry(root, phase, gen, entry, temps, kept) or changedexcept OSError as exc:failed = Trueprint(f"⚠ Could not settle {entry[0]} after an interrupted ZIP update: {exc}", file=sys.stderr)diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 86d976e9eb1..cf3732f7a24 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -117,14 +117,17 @@ def _stage_replacement(src: str, dst: str, on_created=None) -> str:return staging-def _copy_file_exclusive(src: str, dst: str, *, sync: bool = False) -> None:+def _copy_file_exclusive(src: str, dst: str, *, sync: bool = False, on_created=None) -> None:"""``copy2`` that only ever creates ``dst``: O_CREAT|O_EXCL (+O_NOFOLLOW) fails on any entry there(symlink, hardlink, file) instead of writing through it, and the bytes and mode go through the held- fd. Times are copied only where that can be done without following ``dst``."""+ fd. Times are copied only where that can be done without following ``dst``. ``on_created(dst)``+ runs once ``dst`` exists, before a byte is written, so a journal can record what this run made."""flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)st = os.stat(src)fd = os.open(dst, flags, 0o600)try:+ if on_created is not None:+ on_created(dst)with os.fdopen(fd, "wb") as out, open(src, "rb") as source:shutil.copyfileobj(source, out, 1 << 20)out.flush()@@ -160,15 +163,16 @@ def _hardlink_backup(path: str, backup: str) -> bool:return True-def _file_backup(path: str, backup: str, tag: str = "") -> None:+def _file_backup(path: str, backup: str, tag: str = "", on_temp=None) -> None:"""Back up the regular file ``path`` as a complete ``backup`` while ``path`` stays in place: a hardlink,or where links are unsupported (FAT32/exFAT/SMB) a synced copy landed whole by ``os.replace``. The- copy's temp carries the journal's random ``tag``: recovery deletes only its own run's temp."""+ copy's temp carries the journal's random ``tag``, and ``on_temp(temp)`` journals it as it comes into+ existence: recovery deletes a temp only on that record (F78-R)."""if _hardlink_backup(path, backup):returntmp = f"{backup}.{tag or os.urandom(6).hex()}.tmp"try:- _copy_file_exclusive(path, tmp, sync=True) # never through a planted <backup>.tmp link (Z2)+ _copy_file_exclusive(path, tmp, sync=True, on_created=on_temp) # never through a planted link (Z2)os.replace(tmp, backup)except OSError:with suppress(OSError):@@ -176,7 +180,7 @@ def _file_backup(path: str, backup: str, tag: str = "") -> None:raise-def _commit_staged_replacements(staged, *, on_committed=None, tag: str = "") -> None:+def _commit_staged_replacements(staged, *, on_committed=None, tag: str = "", on_temp=None) -> None:"""Phase 2: swap every staged entry into place, rolling back all on failure.Per-entry safety wasn't enough: a partway failure over ~90 entries left a mixed-version tree (every@@ -201,7 +205,7 @@ def _commit_staged_replacements(staged, *, on_committed=None, tag: str = "") ->if os.path.lexists(backup): # appeared since staging set leftovers aside: not ours to replace (F78)raise FileExistsError(f"{backup} appeared during the update; it was left in place")if os.path.isfile(dst) and not os.path.islink(dst):- _file_backup(dst, backup, tag)+ _file_backup(dst, backup, tag, on_temp)swapped.append((dst, backup))os.replace(staging, dst)continue@@ -515,8 +519,17 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, tafor entry in journal_entries:entry[3] = zip_entry_identity(root / entry[0])write_zip_swap_journal(root, "swapping", journal_entries, gen)+ temps: dict[str, str] = {}++ def record_temp(tmp: str) -> None: # a backup copy's temp, journaled before its first byte+ temps[os.path.basename(tmp)] = zip_entry_identity(tmp, filling=True)+ write_zip_swap_journal(root, "swapping", journal_entries, gen, temps)++ # Committed: every temp already became its backup, so the record drops them (a backup the+ # cleanup then frees must never leave an inode that vouches for a later file at a temp name)._commit_staged_replacements(- staged, on_committed=lambda: write_zip_swap_journal(root, "committed", journal_entries, gen), tag=gen)+ staged, on_committed=lambda: write_zip_swap_journal(root, "committed", journal_entries, gen), tag=gen,+ on_temp=record_temp)# Committed: the new tree is whole. A journal that cannot go now (AV/indexer holding it) says# "committed", which the next launch's recovery settles by keeping the new tree. It stays, too,# while a backup (or backup temp) the best-effort cleanup could not remove is still on disk:diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.pyindex 3823b0a98eb..da699183908 100644--- a/tests/hermes_cli/test_update_zip_two_phase.py+++ b/tests/hermes_cli/test_update_zip_two_phase.py@@ -662,20 +662,45 @@ def test_a_journal_that_cannot_be_dropped_after_the_commit_never_fails_the_updatassert (live / "payload" / "version.txt").read_text(encoding="utf-8-sig") == "new"+_KILLED_BACKUP_COPY = r'''+import os, shutil, sys+from pathlib import Path+from hermes_cli import update_cmd_commit, update_cmd_zip+live, extracted = Path(sys.argv[1]), Path(sys.argv[2])+update_cmd_commit.arm_commit_obligations = lambda *a, **k: None+update_cmd_zip._hardlink_backup = lambda path, backup: False # FAT32/exFAT/SMB: no hardlinks+real = shutil.copyfileobj+def killed_inside_the_backup_copy(source, out, length=0):+ if source.name == str(live / "a.py"):+ out.write(source.read(2))+ out.flush()+ os._exit(9) # a SIGKILL: no handler runs, the half-written temp stays+ return real(source, out, length)+shutil.copyfileobj = killed_inside_the_backup_copy+update_cmd_zip._journaled_stage_and_swap(str(extracted), ["a.py"], live, None)+'''++def test_a_backup_copy_killed_before_its_rename_is_cleared_by_the_recovery(tmp_path):- """On a file system without hardlinks ``_file_backup`` copies to ``<entry>.hermes-update-old.tmp``- first. A kill inside that copy left the temp behind: recovery dropped only staging and the backup,- so every later ZIP update refused on "uncommitted changes" (review C4)."""- from hermes_cli._early_recovery_zip import (- ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity)+ """On a file system without hardlinks ``_file_backup`` copies to ``<entry>.hermes-update-old.<gen>.tmp``+ first. The real swap is killed inside that copy: the temp it journaled on creation is its own and+ goes, or every later ZIP update refuses on "uncommitted changes" (review C4)."""+ import subprocess+ import sys- live = tmp_path / "live"+ from hermes_cli._early_recovery_zip import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap++ live, extracted = tmp_path / "live", tmp_path / "extracted"live.mkdir()+ extracted.mkdir()(live / "a.py").write_text("old\n", encoding="utf-8")- (live / "a.py.hermes-update-staging").write_text("new\n", encoding="utf-8")- (live / "a.py.hermes-update-old.0123456789ab.tmp").write_text("ol", encoding="utf-8") # the killed copy- write_zip_swap_journal(live, "swapping", [["a.py", True, zip_entry_identity(live / "a.py.hermes-update-staging"),- zip_entry_identity(live / "a.py")]], "0123456789ab")+ (extracted / "a.py").write_text("new\n", encoding="utf-8")+ repo = os.path.realpath(Path(update_cmd.__file__).parent.parent)+ killed = subprocess.run([sys.executable, "-c", _KILLED_BACKUP_COPY, str(live), str(extracted)], cwd=repo,+ env={**os.environ, "PYTHONPATH": repo}, capture_output=True, text=True, timeout=120)+ temps = list(live.glob("a.py.hermes-update-old.*.tmp"))+ assert killed.returncode == 9 and [p.read_bytes() for p in temps] == [b"ol"], (+ f"harness: not killed inside the backup copy: {killed.returncode} {killed.stderr[-2000:]}")restore_interrupted_zip_swap(live)@@ -684,11 +709,12 @@ def test_a_backup_copy_killed_before_its_rename_is_cleared_by_the_recovery(tmp_passert (live / "a.py").read_text(encoding="utf-8") == "old\n"-def test_a_file_at_the_backup_temp_name_that_is_not_the_killed_copy_is_kept(tmp_path):- """The run's tag names the temp but proves nothing about its bytes: a swap killed before its- backup copy existed leaves the name free, and a file there afterwards is not Hermes'. Recovery- deletes only a prefix of the live file (what a killed copy of it is) and keeps anything else- aside, still retiring the journal (review F78)."""[email protected]("content", ["USER FILE", "old", "old\n", ""])+def test_a_file_at_the_backup_temp_name_that_is_not_the_killed_copy_is_kept(tmp_path, content):+ """The run's tag names the temp but proves nothing, and neither do its bytes: a swap killed before+ its backup copy existed leaves the name free, and a file there afterwards is not Hermes', even an+ empty one, a prefix or a full copy of the live file. Only the identity the swap journaled when it+ created the temp may delete it; anything else is kept aside, the journal still retiring (F78-R)."""from hermes_cli._early_recovery_zip import (ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity)@@ -698,12 +724,12 @@ def test_a_file_at_the_backup_temp_name_that_is_not_the_killed_copy_is_kept(tmp_(live / "a.py.hermes-update-staging").write_text("new\n", encoding="utf-8")write_zip_swap_journal(live, "swapping", [["a.py", True, zip_entry_identity(live / "a.py.hermes-update-staging"),zip_entry_identity(live / "a.py")]], "0123456789ab")- (live / "a.py.hermes-update-old.0123456789ab.tmp").write_text("USER FILE", encoding="utf-8")+ (live / "a.py.hermes-update-old.0123456789ab.tmp").write_text(content, encoding="utf-8")restore_interrupted_zip_swap(live)kept = [p for p in live.iterdir() if ".hermes-update-kept" in p.name]- assert [p.read_text(encoding="utf-8") for p in kept] == ["USER FILE"], sorted(p.name for p in live.iterdir())+ assert [p.read_text(encoding="utf-8") for p in kept] == [content], sorted(p.name for p in live.iterdir())assert not (live / ZIP_SWAP_JOURNAL).exists()assert (live / "a.py").read_text(encoding="utf-8") == "old\n"