Skip to content

The agent that grows with you

fix: ZIP staging never deletes a suffix path it cannot prove it made

Tekniumf22c1130c5f7
diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.py
index f50d44ad8ac..01839cc12e5 100644
--- a/hermes_cli/update_cmd_zip.py
+++ b/hermes_cli/update_cmd_zip.py
@@ -15,7 +15,7 @@ from pathlib import Path
from typing import Collection, Optional
from hermes_cli._early_recovery import (
- ZIP_SWAP_JOURNAL, _drop_path, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity,
+ ZIP_SWAP_JOURNAL, _keep_aside, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity,
zip_swap_owner_lock)
# Log-record parity with the origin module.
@@ -86,34 +86,34 @@ def _stage_replacement(src: str, dst: str, on_created=None) -> str:
# clearing leftovers, else deleting it then failing to stage (disk exhaustion) leaves a hole.
if not os.path.lexists(dst) and os.path.lexists(backup): # a dangling symlink backup is still one (Z3)
os.rename(backup, dst)
- # Fail closed: a leftover backup that survives would later be taken for this swap's own backup
- # (rollback and journal recovery put it back as the live entry).
+ # Nothing this run made is there yet: an entry at either suffix is not provably the update's (a
+ # user's file created after the clean-tree preflight, or a pre-journal crash's), so it is kept aside,
+ # never deleted (F78). Neither may stay: a backup would later be taken for this swap's own.
for leftover in (staging, backup):
- _drop_path(Path(leftover))
if os.path.lexists(leftover):
- raise OSError(f"could not remove the leftover {leftover}")
+ print(f" ⚠ Kept {leftover} aside as {_keep_aside(Path(leftover)).name}: nothing proves it is "
+ "this update's.")
# Never through the reusable pathname: copy2 opens it following a symlink planted after the sweep
# (review Z2). copytree's own os.mkdir is exclusive and never follows; a file is created the same way.
if os.path.isdir(src):
os.mkdir(staging)
- made = zip_entry_identity(staging)
- if on_created is not None:
- on_created(staging)
- if zip_entry_identity(staging) != made: # swapped while the journal recorded it: never fill that
- raise OSError(f"the staging directory {staging} was replaced while it was being created")
- try:
- shutil.copytree(src, staging, dirs_exist_ok=True)
- except BaseException:
- # A failed stage leaves nothing (a full disk must not shrink further on the retry). Best
- # effort, like _discard_staged: the journal's recovery drops what this cannot.
- with suppress(OSError):
- if zip_entry_identity(staging) == made:
- _remove_path(staging)
- raise
else:
_copy_file_exclusive(src, staging)
+ made = zip_entry_identity(staging)
+ try:
if on_created is not None:
on_created(staging)
+ if zip_entry_identity(staging) != made: # swapped while the journal recorded it: never fill that
+ raise OSError(f"the staging entry {staging} was replaced while it was being created")
+ if os.path.isdir(src):
+ shutil.copytree(src, staging, dirs_exist_ok=True)
+ except BaseException:
+ # A failed stage leaves nothing of its own (a full disk must not shrink further on the retry).
+ # Best effort, like _discard_staged: the journal's recovery drops what this cannot.
+ with suppress(OSError):
+ if zip_entry_identity(staging) == made:
+ _remove_path(staging)
+ raise
return staging
@@ -151,11 +151,9 @@ def _discard_staged(staged) -> None:
def _hardlink_backup(path: str, backup: str) -> bool:
- """Hardlink ``path`` to ``backup`` (a stale backup is replaced); False where links are unsupported.
- A link is all-or-nothing, so a killed swap never leaves a short backup the restore would put back."""
+ """Hardlink ``path`` to ``backup``; False where links are unsupported. A link is all-or-nothing, so a
+ killed swap never leaves a short backup the restore would put back."""
try:
- if os.path.lexists(backup):
- _remove_path(backup)
os.link(path, backup)
except OSError:
return False
@@ -200,6 +198,8 @@ def _commit_staged_replacements(staged, *, on_committed=None, tag: str = "") ->
try:
for staging, dst in staged:
backup = f"{dst}.hermes-update-old"
+ 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)
swapped.append((dst, backup))
@@ -427,16 +427,17 @@ def _graft_nested_artifacts(item: str, live: str, staging: str) -> None:
def _stage_entries(extracted: str, entries: list[str], project_root: str,
on_created=None) -> list[tuple[str, str]]:
"""Phase 1 for every entry; on failure nothing is live yet, so drop partial staging copies so a retry
- starts from the same free space. Each entry is recorded BEFORE its copy starts: a copy that fails
- partway (an unreadable source file) leaves a partial staging tree that must be dropped too.
+ starts from the same free space. An entry is listed only once its staging copy is this run's: a copy
+ that fails partway drops its own partial tree (``_stage_replacement``), and a pathname this run never
+ created (a user's file there) is never ``_discard_staged``'s to delete (F78).
``on_created(index, staging)``: the journal's hook as each staging entry comes into existence."""
staged: list[tuple[str, str]] = []
try:
for index, item in enumerate(entries):
dst = os.path.join(project_root, item)
- staged.append((f"{dst}.hermes-update-staging", dst))
- _stage_replacement(os.path.join(extracted, item), dst,
- None if on_created is None else (lambda path, i=index: on_created(i, path)))
+ staged.append((_stage_replacement(
+ os.path.join(extracted, item), dst,
+ None if on_created is None else (lambda path, i=index: on_created(i, path))), dst))
# The source ZIP carries only source; the built outputs (#70337/#87331 release/, then
# dist/, apps/desktop/node_modules and web_dist — #90495) exist only in the LIVE tree. Graft
# them into the staged copy BEFORE the swap so the commit preserves them atomically.
diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py
index ab940ec910f..c92d8d195ec 100644
--- a/tests/hermes_cli/test_update_zip_completion.py
+++ b/tests/hermes_cli/test_update_zip_completion.py
@@ -375,7 +375,10 @@ def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, mo
assert error.value.code == 1
witness = target / "code.py" if entry == "tools" else target
assert witness.read_text(encoding="utf-8") == ("retained" if entry == "tools" else "old")
- assert not _swap_leftovers(root)
+ # Nothing journaled the leftover copy: it is kept aside, never deleted (F78).
+ kept = root / (leftover.name + ".hermes-update-kept")
+ assert _swap_leftovers(root) == [kept] and kept.read_text(encoding="utf-8") == "interrupted copy"
+ kept.unlink()
update_cmd_zip._download_and_swap_zip("main", "local fixture")
assert witness.read_text(encoding="utf-8") == "new"
assert not _swap_leftovers(root)
diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.py
index cfc169aa40a..bcb55e3c61d 100644
--- a/tests/hermes_cli/test_update_zip_two_phase.py
+++ b/tests/hermes_cli/test_update_zip_two_phase.py
@@ -108,7 +108,9 @@ def test_commit_handles_entries_absent_from_the_install(tmp_path):
assert (live / "brand_new" / "version.txt").read_text() == "new"
-def test_staging_clears_leftovers_from_an_interrupted_run(tmp_path):
+def test_staging_sets_aside_leftovers_it_cannot_prove_are_its_own(tmp_path):
+ """A staging-suffix entry nothing journaled (a pre-journal crash's, or a user's) is neither staged
+ over nor deleted (F78): it is kept aside byte for byte and the update proceeds."""
live, new = tmp_path / "live", tmp_path / "new"
_live_tree(live, {"agent": "old"})
_live_tree(new, {"agent": "new"})
@@ -120,6 +122,8 @@ def test_staging_clears_leftovers_from_an_interrupted_run(tmp_path):
assert (live / "agent" / "version.txt").read_text() == "new"
assert not (live / "agent" / "junk.txt").exists()
+ assert [p.read_text() for p in live.glob("agent.hermes-update-staging.hermes-update-kept/*")] == [
+ "from a previous crash"]
# ---------------------------------------------------------------------------
# Shared venv helpers (#76105)
@@ -826,3 +830,29 @@ def test_a_committed_swap_keeps_its_journal_until_the_backup_is_gone(tmp_path, m
assert not (live / "payload.hermes-update-old").exists() and not (live / ZIP_SWAP_JOURNAL).exists()
assert update_cmd_zip._zip_overlay_block_reason(live) is None
[email protected]("planted", ["cli.py.hermes-update-staging", "cli.py.hermes-update-old"])
+def test_a_suffix_path_that_appears_after_the_preflight_is_never_deleted(tmp_path, monkeypatch, planted):
+ """F78: a file at the staging suffix (created during the download, after the clean-tree preflight)
+ or at the backup suffix (created after the pre-swap recheck) is nothing this transaction made. The
+ stage dropped the first unconditionally and the hardlink backup the second; both survive now, byte
+ for byte, and the swap is refused with the live tree left old."""
+ from hermes_cli import update_cmd_commit
+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap
+
+ live, extracted = tmp_path / "live", tmp_path / "extracted"
+ live.mkdir()
+ extracted.mkdir()
+ _git_checkout(live, {"cli.py": "LIVE"})
+ (extracted / "cli.py").write_text("NEW", encoding="utf-8")
+ user = live / planted
+ if planted.endswith("-staging"):
+ user.write_text("USER NOTE", encoding="utf-8")
+ monkeypatch.setattr(update_cmd_commit, "arm_commit_obligations", # the last step before the swap
+ lambda *a, **k: user.exists() or user.write_text("USER NOTE", encoding="utf-8"))
+ with pytest.raises((SystemExit, OSError)):
+ update_cmd_zip._journaled_stage_and_swap(str(extracted), ["cli.py"], live, "b" * 40)
+ restore_interrupted_zip_swap(live)
+ assert (live / "cli.py").read_text(encoding="utf-8") == "LIVE"
+ kept = [p.name for p in live.iterdir() if p.is_file() and p.read_bytes() == b"USER NOTE"]
+ assert len(kept) == 1, sorted(p.name for p in live.iterdir())
+ assert not (live / ZIP_SWAP_JOURNAL).exists()