Skip to content

The agent that grows with you

fix(update): the launch repair runs a published closure only when it hashes to pre's blobs (M1, m3, m4)

Teknium0e430b2d8278
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index 123d4d6bd0d..a85f0f5e735 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -255,10 +255,42 @@ RECOVERY_CLOSURE_DIR = "hermes-update-recovery"
RECOVERY_CLOSURE = ("hermes_cli/_early_recovery.py", "hermes_cli/update_lock.py", "hermes_cli/update_custody.py")
+# ``<blob id> <path>`` per published file (``RECOVERY_CLOSURE`` + the empty package initializer):
+# a closure is used only when every file hashes to its id (a power loss can leave the renamed dir
+# with files git's objects never had), else it is rebuilt from git's objects.
+RECOVERY_CLOSURE_MANIFEST = "MANIFEST"
+RECOVERY_CLOSURE_INIT = "hermes_cli/__init__.py"
+
+
def recovery_closure_dir(root: Path, pre: str) -> Path:
+ if not is_object_id(pre): # never a revision (``HEAD``) or a path (``../x``) under the git dir
+ raise ValueError(f"not a commit id: {pre!r}")
return _git_dir(root) / RECOVERY_CLOSURE_DIR / pre
+def is_object_id(value: str) -> bool:
+ return bool(re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", value or ""))
+
+
+def blob_id(data: bytes, like: str) -> str:
+ """Git's object id of a blob holding ``data``, in ``like``'s object format (SHA-1 or SHA-256)."""
+ import hashlib
+
+ return hashlib.new("sha1" if len(like) == 40 else "sha256", b"blob %d\0" % len(data) + data).hexdigest()
+
+
+def recovery_closure_verified(closure: Path, pre: str) -> bool:
+ """Every closure file present with exactly the bytes its manifest names, and nothing missing."""
+ try:
+ listed = dict(line.split(" ", 1)[::-1] for line in
+ (closure / RECOVERY_CLOSURE_MANIFEST).read_text(encoding="utf-8-sig").splitlines())
+ return (set(listed) == {*RECOVERY_CLOSURE, RECOVERY_CLOSURE_INIT}
+ and listed[RECOVERY_CLOSURE_INIT] == blob_id(b"", pre)
+ and all(blob_id((closure / rel).read_bytes(), pre) == oid for rel, oid in listed.items()))
+ except (OSError, ValueError):
+ return False
+
+
def _git_executable(recorded_by_updater: str = "") -> str:
"""The git ``hermes update`` runs (``_subprocess_compat.expose_pm_git``), without installing it.
diff --git a/hermes_cli/_launchers.py b/hermes_cli/_launchers.py
index f6306430f24..c73eb5c01ff 100644
--- a/hermes_cli/_launchers.py
+++ b/hermes_cli/_launchers.py
@@ -307,13 +307,15 @@ def mint_launcher(
# A killed move can tear the repair's own code (``hermes_bootstrap``, ``hermes_cli``). With the
# marker still there, a launcher whose checkout import failed runs the copy of the repair that the
-# updater published beside the marker (``update_cmd_commit.publish_recovery_closure``), or, when
-# none was published (an updater predating it), the same files read from git's objects at the
-# marker's ``pre``: stdlib plus that copy only, under the same claim and checkout lock (a live
-# writer still refuses), then a relaunch from the restored tree.
+# updater published beside the marker (``update_cmd_commit.publish_recovery_closure``) once every
+# file hashes to the blob id its manifest names; a missing, torn or foreign closure (or none, from
+# an updater predating it) is rebuilt from git's objects at the marker's ``pre`` with the recorded
+# git or an absolute PATH entry (never one from the current directory) and verified the same way.
+# Stdlib plus that copy only, under the same claim and checkout lock (a live writer still refuses,
+# which exits 1 with the repair's own reason), then a relaunch from the restored tree.
_CLOSURE_REPAIR = """\
def _hermes_closure_repair():
- import subprocess
+ import contextlib, hashlib, io, shutil, subprocess
from pathlib import Path
root = Path(__ROOT__)
git = root / '.git'
@@ -325,41 +327,82 @@ def _hermes_closure_repair():
except OSError:
return
pre = fields.get('pre', '').strip()
+ if not re.fullmatch('[0-9a-f]{40}|[0-9a-f]{64}', pre):
+ return
closure = git / __CLOSURE_DIR__ / pre
- if pre and not all((closure / rel).is_file() for rel in __CLOSURE__):
+ files = (*__CLOSURE__, __INIT__)
+
+ def blob_id(data):
+ return hashlib.new('sha1' if len(pre) == 40 else 'sha256', b'blob %d\\0' % len(data) + data).hexdigest()
+
+ def verified():
+ try:
+ listed = dict(line.split(' ', 1)[::-1] for line in (closure / __MANIFEST__).read_text(encoding='utf-8-sig').splitlines())
+ return (set(listed) == set(files) and listed[__INIT__] == blob_id(b'')
+ and all(blob_id((closure / rel).read_bytes()) == oid for rel, oid in listed.items()))
+ except (OSError, ValueError):
+ return False
+
+ if not verified():
exe = fields.get('git', '').strip()
+ if not (os.path.isabs(exe) and os.path.isfile(exe)):
+ names = ('git.exe',) if os.name == 'nt' else ('git',)
+ exe = next((os.path.join(d, n) for d in os.environ.get('PATH', '').split(os.pathsep) if os.path.isabs(d)
+ for n in names if os.path.isfile(os.path.join(d, n))), '')
+ if not exe:
+ return
+
+ def git_out(*args):
+ done = subprocess.run([exe, '--no-replace-objects', '-C', str(root), *args], capture_output=True, timeout=60,
+ stdin=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
+ if done.returncode != 0:
+ raise OSError(done.stderr)
+ return done.stdout
+
staging = closure.with_name('.%s.%d.launch' % (pre, os.getpid()))
try:
- for rel in (*__CLOSURE__, 'hermes_cli/__init__.py'):
- blob = b''
- if rel in __CLOSURE__:
- blob = subprocess.run([exe if exe and os.path.isfile(exe) else 'git', '-C', str(root), 'cat-file',
- 'blob', pre + ':' + rel], capture_output=True, timeout=60,
- stdin=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
- if blob.returncode != 0:
- return
- blob = blob.stdout
+ ids = {}
+ for entry in git_out('ls-tree', '-z', '--full-tree', pre, '--', *__CLOSURE__).split(b'\\0'):
+ meta, _, rel = entry.decode('utf-8', 'replace').partition('\\t')
+ if meta.split()[1:2] == ['blob']:
+ ids[rel] = meta.split()[2]
+ blobs = {__INIT__: b''}
+ for rel in __CLOSURE__:
+ blobs[rel] = git_out('cat-file', 'blob', ids[rel])
+ blobs[__MANIFEST__] = ''.join('%s %s\\n' % (blob_id(data), rel) for rel, data in blobs.items()).encode('utf-8')
+ for rel, data in blobs.items():
(staging / rel).parent.mkdir(parents=True, exist_ok=True)
- (staging / rel).write_bytes(blob)
+ (staging / rel).write_bytes(data)
+ shutil.rmtree(closure, ignore_errors=True)
os.replace(staging, closure)
- except (OSError, subprocess.SubprocessError):
+ except (OSError, KeyError, subprocess.SubprocessError):
pass
finally:
- __import__('shutil').rmtree(staging, ignore_errors=True)
- if not pre or not all((closure / rel).is_file() for rel in __CLOSURE__):
- return
+ shutil.rmtree(staging, ignore_errors=True)
+ if not verified():
+ return
for name in [n for n in sys.modules if n.split('.')[0] in ('hermes_cli', 'hermes_bootstrap', 'hermes_constants', 'pm')]:
del sys.modules[name]
tree = os.path.normcase(os.path.realpath(root))
sys.path[:] = [str(closure)] + [p for p in sys.path if p and os.path.normcase(os.path.realpath(p)) != tree
and not os.path.normcase(os.path.realpath(p)).startswith(tree + os.sep)]
- print('hermes: the checkout cannot start after an interrupted `hermes update`; '
- 'repairing it with the recovery code saved before the update.', file=sys.stderr)
sys.dont_write_bytecode = True
- from hermes_cli import _early_recovery
- if _early_recovery.restore_interrupted_pull(root):
+ said = io.StringIO()
+ restored = False
+ try:
+ with contextlib.redirect_stderr(said):
+ from hermes_cli import _early_recovery
+ restored = _early_recovery.restore_interrupted_pull(root)
+ except Exception as exc:
+ said.write('hermes: the checkout cannot start after an interrupted `hermes update`, and it was not '
+ 'repaired: %s\\n' % (exc,))
+ if restored:
+ sys.stderr.write('hermes: the checkout could not start after an interrupted `hermes update`; '
+ 'repaired it with the recovery code saved before the update.\\n' + said.getvalue())
_early_recovery.relaunch_after_restore()
- return True
+ sys.stderr.write(said.getvalue() or 'hermes: the checkout cannot start after an interrupted `hermes update`; '
+ 'launch again once the update that owns it finishes.\\n')
+ raise SystemExit(1)
"""
@@ -375,10 +418,18 @@ def _launcher_script(name: str, repo_root: Path, dependencies: Path | None) -> s
# ``hermes_bootstrap`` right after the repair (``_PIN_DEFAULT_HOME``), and here again for a
# bootstrap that predates that hook.
root = str(repo_root.resolve())
- from hermes_cli._early_recovery import INTERRUPTED_PULL_MARKER, RECOVERY_CLOSURE, RECOVERY_CLOSURE_DIR
+ from hermes_cli._early_recovery import (
+ INTERRUPTED_PULL_MARKER,
+ RECOVERY_CLOSURE,
+ RECOVERY_CLOSURE_DIR,
+ RECOVERY_CLOSURE_INIT,
+ RECOVERY_CLOSURE_MANIFEST,
+ )
closure_repair = (_CLOSURE_REPAIR.replace("__MARKER__", repr(INTERRUPTED_PULL_MARKER))
.replace("__CLOSURE_DIR__", repr(RECOVERY_CLOSURE_DIR))
+ .replace("__MANIFEST__", repr(RECOVERY_CLOSURE_MANIFEST))
+ .replace("__INIT__", repr(RECOVERY_CLOSURE_INIT))
.replace("__CLOSURE__", repr(RECOVERY_CLOSURE))
.replace("__ROOT__", repr(root))) # last: a path is never re-substituted
return (
diff --git a/hermes_cli/update_cmd_commit.py b/hermes_cli/update_cmd_commit.py
index 5abbd7b5d32..27564757e7b 100644
--- a/hermes_cli/update_cmd_commit.py
+++ b/hermes_cli/update_cmd_commit.py
@@ -24,8 +24,13 @@ from typing import Optional
from hermes_cli._early_recovery import (
RECOVERY_CLOSURE,
+ RECOVERY_CLOSURE_INIT,
+ RECOVERY_CLOSURE_MANIFEST,
+ blob_id,
interrupted_pull_marker,
+ is_object_id,
recovery_closure_dir,
+ recovery_closure_verified,
restore_interrupted_pull,
)
from hermes_cli.update_custody import run_git
@@ -134,29 +139,48 @@ def publish_recovery_closure(git_cmd, root: Path, pre: str) -> Path:
The bytes come from the commit the repair restores, never from the working tree: a rollback move
starts from a broken tree, and a second move in one run starts from code this process never ran.
- Published by an atomic directory rename, so a present closure is a whole one; an older run's
- closure (another ``pre``) is dropped.
+ A manifest names each file's blob id; the launcher runs the closure only when every file hashes
+ to it (``recovery_closure_verified``) and rebuilds it from git's objects otherwise. Files and
+ directory are fsynced before the atomic rename, so a power loss during the move that follows
+ finds the whole closure or none. An older run's closure (another ``pre``) is dropped.
"""
import shutil
+ if not is_object_id(pre):
+ raise OSError(f"not a commit id: {pre!r}")
dest = recovery_closure_dir(Path(root), pre)
- if all((dest / rel).is_file() for rel in RECOVERY_CLOSURE):
+ if recovery_closure_verified(dest, pre):
return dest
- blobs = {}
+ git_cmd = [*([git_cmd] if isinstance(git_cmd, str) else git_cmd), "--no-replace-objects"]
+ listed = run_git(git_cmd, ["ls-tree", "-z", "--full-tree", pre, "--", *RECOVERY_CLOSURE], cwd=str(root),
+ capture_output=True, stdin=subprocess.DEVNULL, timeout=120)
+ ids = {}
+ for entry in (listed.stdout or b"").split(b"\0") if listed.returncode == 0 else ():
+ meta, _, rel = entry.decode("utf-8", "replace").partition("\t")
+ if meta.split()[1:2] == ["blob"]:
+ ids[rel] = meta.split()[2]
+ blobs = {RECOVERY_CLOSURE_INIT: b""}
for rel in RECOVERY_CLOSURE:
- shown = run_git(git_cmd, ["cat-file", "blob", f"{pre}:{rel}"], cwd=str(root), capture_output=True,
- stdin=subprocess.DEVNULL, timeout=120)
- if shown.returncode != 0 or not isinstance(shown.stdout, bytes) or not shown.stdout:
+ shown = run_git(git_cmd, ["cat-file", "blob", ids.get(rel, "")], cwd=str(root), capture_output=True,
+ stdin=subprocess.DEVNULL, timeout=120) if rel in ids else None
+ if shown is None or shown.returncode != 0 or blob_id(shown.stdout or b"", pre) != ids[rel]:
raise OSError(f"{rel} is not in {pre[:10]}")
blobs[rel] = shown.stdout
+ manifest = "".join(f"{blob_id(data, pre)} {rel}\n" for rel, data in blobs.items()).encode("utf-8")
staging = dest.with_name(f".{pre}.{os.getpid()}.staging")
shutil.rmtree(staging, ignore_errors=True)
try:
- for rel, data in {**blobs, "hermes_cli/__init__.py": b""}.items():
+ for rel, data in {**blobs, RECOVERY_CLOSURE_MANIFEST: manifest}.items():
(staging / rel).parent.mkdir(parents=True, exist_ok=True)
- (staging / rel).write_bytes(data)
+ with open(staging / rel, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ for directory in (staging / "hermes_cli", staging):
+ _fsync_dir(directory)
shutil.rmtree(dest, ignore_errors=True)
os.replace(staging, dest)
+ _fsync_dir(dest.parent)
finally:
shutil.rmtree(staging, ignore_errors=True)
for stale in dest.parent.iterdir():
@@ -165,6 +189,18 @@ def publish_recovery_closure(git_cmd, root: Path, pre: str) -> Path:
return dest
+def _fsync_dir(directory: Path) -> None:
+ """POSIX: make a directory's entries durable. Windows opens no directory handle; NTFS journals
+ the rename itself."""
+ if os.name == "nt":
+ return
+ fd = os.open(directory, os.O_RDONLY)
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+
def _absolute_git(git_cmd) -> str:
"""The git this run moves the tree with, as an absolute path for the next launch's repair.
diff --git a/tests/hermes_cli/test_update_recovery_closure.py b/tests/hermes_cli/test_update_recovery_closure.py
index a9c4c789ef3..bce5d56c067 100644
--- a/tests/hermes_cli/test_update_recovery_closure.py
+++ b/tests/hermes_cli/test_update_recovery_closure.py
@@ -124,17 +124,32 @@ def test_a_launch_repairs_a_move_killed_while_writing_the_repairs_own_code(tmp_p
@pytest.mark.platforms("posix")
-def test_the_published_repair_leaves_the_tree_to_a_live_writer_holding_the_checkout(tmp_path):
[email protected]("published", [True, False])
+def test_the_published_repair_leaves_the_tree_to_a_live_writer_holding_the_checkout(tmp_path, published):
root, env, original, launcher = _killed_mid_write(tmp_path, "hermes_bootstrap.py")
+ if not published:
+ # The closure comes from git's objects, and no git was recorded: the launcher's git is an
+ # absolute PATH entry's, never a ``git`` in the current directory an empty entry names (m4).
+ shutil.rmtree(root / ".git/hermes-update-recovery")
+ marker = root / ".git/hermes-update-pull"
+ lines = marker.read_text(encoding="utf-8-sig").splitlines()
+ marker.write_text("".join(line + "\n" for line in lines if not line.startswith("git=")), encoding="utf-8")
+ (tmp_path / "git").write_text(f"#!/bin/sh\ntouch {shlex.quote(str(tmp_path / 'CWD_GIT_RAN'))}\nexit 1\n",
+ encoding="utf-8")
+ (tmp_path / "git").chmod(0o755)
holder = subprocess.Popen([sys.executable, "-I", "-c", _HOLDER, str(SOURCE), str(root)], env=env,
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True, encoding="utf-8")
try:
assert holder.stdout is not None and holder.stdout.readline().strip() == "HELD"
- launch = subprocess.run([str(launcher)], cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8",
- errors="replace", timeout=60)
+ launch = subprocess.run([str(launcher)], cwd=tmp_path, env={**env, "PATH": os.pathsep + env["PATH"]},
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
assert launch.returncode != 0 and "Not repairing the checkout now" in launch.stderr, launch.stderr
+ # One reason, not a "repairing it" banner followed by the import's traceback (m3).
+ assert "Traceback" not in launch.stderr and "repairing it" not in launch.stderr, launch.stderr
assert not (root / "hermes_bootstrap.py").exists(), "repaired under a live writer"
assert (root / ".git/hermes-update-pull").exists()
+ assert not (tmp_path / "CWD_GIT_RAN").exists()
+ assert (root / ".git/hermes-update-recovery").is_dir(), "closure not rebuilt from git's objects"
finally:
holder.kill()
holder.wait()
@@ -142,3 +157,22 @@ def test_the_published_repair_leaves_the_tree_to_a_live_writer_holding_the_check
errors="replace", timeout=60)
assert launch.returncode == 0 and "APP_REACHED" in launch.stdout, launch.stderr
assert (root / "hermes_bootstrap.py").read_bytes() == original
+
+
+
[email protected]("damage", ["truncated", "foreign"])
+def test_a_damaged_published_closure_is_rebuilt_from_git_objects_not_trusted(tmp_path, damage):
+ """A power loss can leave the published closure with bytes git never had: they never run, and the
+ launch rebuilds the closure from ``pre``'s objects before repairing (M1)."""
+ root, env, original, launcher = _killed_mid_write(tmp_path, "hermes_bootstrap.py")
+ (closure,) = (root / ".git/hermes-update-recovery").iterdir()
+ module = closure / "hermes_cli/_early_recovery.py"
+ module.write_bytes(b"" if damage == "truncated" else
+ module.read_bytes() + b"\nprint('NOT_PRE_CODE_RAN', file=__import__('sys').stderr)\n")
+ launch = subprocess.run([str(launcher)], cwd=tmp_path, env=env, capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=60)
+ assert launch.returncode == 0 and "APP_REACHED" in launch.stdout, launch.stderr
+ assert "NOT_PRE_CODE_RAN" not in launch.stderr, launch.stderr
+ assert (root / "hermes_bootstrap.py").read_bytes() == original
+ assert not (root / ".git/hermes-update-pull").exists()
diff --git a/website/docs/developer-guide/source-update-completion.md b/website/docs/developer-guide/source-update-completion.md
index c601a4b68e9..2009305901f 100644
--- a/website/docs/developer-guide/source-update-completion.md
+++ b/website/docs/developer-guide/source-update-completion.md
@@ -123,12 +123,16 @@ The repair code lives in the tree a killed move tears (`hermes_bootstrap.py`,
`update_custody.py`). Before git writes, every tree move publishes those
recovery/lock/custody modules, as committed at the move's starting commit, to
`<git dir>/hermes-update-recovery/<pre>/`, outside the working tree and keyed
-to the marker's `pre`. When the checkout's own import fails while the marker
-exists, the minted launcher (`.hermes/bin/hermes`) runs that published copy
-(when an older updater published none, it first reads the same files from
-git's objects at `pre` into that directory): stdlib plus the copy only, the
-same restore claim and checkout lock (a live writer still gets `Not repairing
-the checkout now`), then relaunches from the restored tree. Limits: other entry
+to the marker's `pre` (a full commit id, nothing else), with a `MANIFEST` of
+each file's blob id; files and directory are fsynced before the rename. When
+the checkout's own import fails while the marker exists, the minted launcher
+(`.hermes/bin/hermes`) runs that published copy only if every file hashes to
+its manifest id. A missing, torn or foreign copy (or none, from an older
+updater) is rebuilt first from git's objects at `pre` (`--no-replace-objects`,
+the recorded git or an absolute `PATH` entry, never the current directory) and
+verified the same way. Then: stdlib plus the copy only, the same restore claim
+and checkout lock (a live writer gets `Not repairing the checkout now` and exit
+1, no traceback), then a relaunch from the restored tree. Limits: other entry
points (`python -m hermes_cli.main`, the `hermes-agent` hook) have no such
fallback; a launcher minted before this fallback existed has none, so a kill
during the first update onto this code (run under the old launcher) is not