Skip to content

The agent that grows with you

fix(update): Windows never runs an update child the job refuses (D2)

Teknium74c3927de12b
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.py
index 968f0e0f7aa..57cea1bbdcc 100644
--- a/hermes_cli/update_custody.py
+++ b/hermes_cli/update_custody.py
@@ -20,6 +20,12 @@ can still write the checkout, and must NOT leak into processes that outlive the
then resumed, so it and everything it spawns die with the lock owner. The Node build goes
through ``pm.progress.run_contained`` (whose Popen it never sees): :func:`contained_command`
wraps it in a stdlib launcher that joins the job before it starts node.
+* Windows fails CLOSED (D2): a child the job refuses is never run. The msvcrt byte lock belongs
+ to the process that took it — an inherited handle does not keep it, the kernel unlocks it when
+ the owner exits — so nothing else could fence a writer outside the job: after the owner's
+ death the lock would be free while it still wrote. A refused bind kills the still-suspended
+ child; a refused launcher join exits before it starts node; either raises
+ :class:`CustodyRefused`, a clear refusal of that step instead of an unfenced writer.
Every updater git runner (``update_cmd._git_run``, ``update_cmd_git._git_run``,
``update_cmd_stash``, ``update_cmd_check``, ``gitlock``, ``update_cmd_commit``,
@@ -70,6 +76,22 @@ _GLOBAL_WITH_VALUE = frozenset({"-c", "-C", "--git-dir", "--work-tree", "--names
_CREATE_SUSPENDED = 0x00000004
+class CustodyRefused(OSError):
+ """Windows would not put an update child in the update's kill-on-close job, so the child was
+ never run (D2): outside the job it could outlive a killed update and write the checkout after
+ the checkout lock is free."""
+
+ def __init__(self, argv: Sequence[str], cause: object) -> None:
+ import os
+
+ name = os.path.basename(str(argv[0])) if argv else "child"
+ super().__init__(
+ f"Windows would not put `{name}` in this update's process job ({cause}), so it was not "
+ "run: a checkout writer outside the job could outlive a killed update and write the "
+ "checkout after its lock is released. Run the command again from a regular terminal, "
+ "outside any sandbox or tool that confines the processes it starts.")
+
+
def git_subcommand(args: Sequence[str]) -> str | None:
"""The subcommand in ``args`` (everything after the git executable), skipping global options."""
it = iter(args)
@@ -144,21 +166,26 @@ def _lock_fds(inherit_lock: bool) -> tuple[int, ...]:
def _bind_suspended(proc: subprocess.Popen) -> None:
"""Assign a CREATE_SUSPENDED child to the update's kill-on-close job, then resume it.
- Suspended until bound, so nothing it spawns can escape the job. A failed bind still resumes
- (the update must not hang on a weaker lock); a failed resume kills the child."""
+ Suspended until bound, so nothing it spawns can escape the job. A refused bind kills the
+ child before it ran a single instruction and raises :class:`CustodyRefused` (D2: never an
+ unfenced writer); a failed resume kills the child."""
import ctypes
- from hermes_cli.update_lock import bind_child_to_update_tree
+ from hermes_cli.update_lock import _bind_to_kill_on_close_job
try:
- bind_child_to_update_tree(proc)
- finally:
- ntdll = ctypes.WinDLL("ntdll")
- ntdll.NtResumeProcess.argtypes = [ctypes.c_void_p]
- ntdll.NtResumeProcess.restype = ctypes.c_long
- if ntdll.NtResumeProcess(int(proc._handle)) != 0:
- proc.kill()
- raise OSError(f"could not resume update child {proc.pid}")
+ _bind_to_kill_on_close_job(proc)
+ except OSError as exc:
+ proc.kill()
+ proc.wait()
+ logger.warning("Refused update child %s: the update's job would not take it (%s)", proc.args, exc)
+ raise CustodyRefused(proc.args if isinstance(proc.args, (list, tuple)) else [proc.args], exc) from exc
+ ntdll = ctypes.WinDLL("ntdll")
+ ntdll.NtResumeProcess.argtypes = [ctypes.c_void_p]
+ ntdll.NtResumeProcess.restype = ctypes.c_long
+ if ntdll.NtResumeProcess(int(proc._handle)) != 0:
+ proc.kill()
+ raise OSError(f"could not resume update child {proc.pid}")
def popen(argv: Sequence[str], *, inherit_lock: bool = False, **kwargs) -> subprocess.Popen:
@@ -280,11 +307,12 @@ def _prefetch_for_move(git_cmd: list[str], args: list[str], kwargs: dict) -> Non
# A stdlib launcher for children whose Popen the updater never sees (``run_contained``): it
# joins the job named by an inherited handle, drops that handle (only the owner's handle may
-# keep the job open) and runs the real command with the same stdio. A refused join never fails
-# the build: the command runs outside the job (the pre-custody behavior), says so on stderr and
-# writes the notice to the report file (argv[2]) so the updater can log it and note it in the
-# update receipt — run_contained captures the child's stderr, so stderr alone is not seen (m1).
+# keep the job open) and runs the real command with the same stdio. A refused join never runs
+# the command (D2): the launcher says so on stderr, writes the notice to the report file
+# (argv[2]) — run_contained captures the child's stderr, so stderr alone is not seen (m1) — and
+# exits; the updater logs the notice, notes it in the receipt and raises CustodyRefused.
_CUSTODY_UNAVAILABLE = "hermes: update custody unavailable"
+_REFUSED_EXIT = 87
_JOIN_JOB = (
"import ctypes, subprocess, sys\n"
"k = ctypes.WinDLL('kernel32', use_last_error=True)\n"
@@ -294,7 +322,7 @@ _JOIN_JOB = (
"h = ctypes.c_void_p(int(sys.argv[1]))\n"
"if not k.AssignProcessToJobObject(h, k.GetCurrentProcess()):\n"
f" note = ('{_CUSTODY_UNAVAILABLE} (could not join the update job: %d); '\n"
- " 'this child runs outside it' % ctypes.get_last_error())\n"
+ " 'the command was not run' % ctypes.get_last_error())\n"
" sys.stderr.write(note + '\\n')\n"
" sys.stderr.flush()\n"
" try:\n"
@@ -302,6 +330,7 @@ _JOIN_JOB = (
" report.write(note)\n"
" except OSError:\n"
" pass\n"
+ f" sys.exit({_REFUSED_EXIT})\n"
"k.CloseHandle(h)\n"
"sys.exit(subprocess.call(sys.argv[3:], stdin=subprocess.DEVNULL))\n"
)
@@ -352,16 +381,18 @@ def _join_launcher_python() -> str:
def contained_command(argv: Sequence[str], *, inherit_lock: bool = True):
"""``(argv, kwargs)`` for a checkout writer started by a runner that hides its Popen (the Node
build in ``pm.progress.run_contained``). POSIX: the lock fd. Windows inside an update: the
- command runs under a launcher that joins the update's kill-on-close job first."""
+ command runs under a launcher that joins the update's kill-on-close job first; when the job
+ cannot be handed over or the join is refused, the command never runs and
+ :class:`CustodyRefused` is raised (D2)."""
argv = list(argv)
if not (sys.platform == "win32" and _held() is not None):
fds = _lock_fds(inherit_lock)
yield argv, ({"pass_fds": fds} if fds else {})
return
- handle = _inheritable_job_handle()
- if handle is None:
- yield argv, {}
- return
+ try:
+ handle = _inheritable_job_handle()
+ except OSError as exc:
+ raise CustodyRefused(argv, exc) from exc
import os
import tempfile
@@ -376,11 +407,15 @@ def contained_command(argv: Sequence[str], *, inherit_lock: bool = True):
import ctypes
ctypes.WinDLL("kernel32").CloseHandle(ctypes.c_void_p(handle))
- _report_refused_join(report, argv)
+ note = _report_refused_join(report, argv)
+ if note:
+ cause = note.removeprefix(f"{_CUSTODY_UNAVAILABLE} (").partition(")")[0]
+ raise CustodyRefused(argv, cause)
-def _inheritable_job_handle() -> int | None:
- """An inheritable duplicate of the update's kill-on-close job handle (Windows), or None."""
+def _inheritable_job_handle() -> int:
+ """An inheritable duplicate of the update's kill-on-close job handle (Windows). Raises
+ ``OSError`` when the job cannot be created or duplicated."""
import ctypes
from hermes_cli.update_lock import update_tree_job
@@ -399,4 +434,4 @@ def _inheritable_job_handle() -> int | None:
return int(dup.value)
except OSError as exc:
logger.warning("Could not hand the update's job to a build child: %s", exc)
- return None
+ raise
diff --git a/tests/hermes_cli/test_update_custody.py b/tests/hermes_cli/test_update_custody.py
index e830bfdcb60..c913f749881 100644
--- a/tests/hermes_cli/test_update_custody.py
+++ b/tests/hermes_cli/test_update_custody.py
@@ -180,7 +180,7 @@ def test_a_refused_build_join_is_logged_and_noted_in_the_receipt(tmp_path, monke
home.mkdir()
monkeypatch.setenv("HERMES_HOME", str(home))
report = tmp_path / "report.txt"
- note = f"{update_custody._CUSTODY_UNAVAILABLE} (could not join the update job: 5); this child runs outside it"
+ note = f"{update_custody._CUSTODY_UNAVAILABLE} (could not join the update job: 5); the command was not run"
report.write_text(note, encoding="utf-8")
with ur.update_receipt_scope():
ur.begin_update_receipt()
diff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.py
index 8f0cbcaa912..a8bab1948d0 100644
--- a/tests/hermes_cli/test_update_lock_windows_live.py
+++ b/tests/hermes_cli/test_update_lock_windows_live.py
@@ -147,7 +147,8 @@ def _tree_dies_with_its_owner(tmp_path: Path, install: Path, owner_args: list[st
owner.kill()
-def test_killed_owner_takes_its_git_child_down(tmp_path):
+def _git_install(tmp_path: Path) -> Path:
+ """A checkout whose ``f.txt`` clean filter is the blocker: a ``stash push`` blocks in git."""
exe = Path(sys.executable).as_posix()
if any(ch in exe for ch in " =~%#'\"&;|<>()$`*?["):
pytest.skip("the clean filter must run without a shell: interpreter path has shell metacharacters")
@@ -163,10 +164,11 @@ def test_killed_owner_takes_its_git_child_down(tmp_path):
_git(install, "config", "filter.block.clean", exe)
(install / ".git" / "info" / "attributes").write_text("f.txt filter=block\n", encoding="utf-8")
(install / "f.txt").write_text(_blocker(tmp_path), encoding="utf-8")
- _tree_dies_with_its_owner(tmp_path, install, [_GIT_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m")])
+ return install
-def test_killed_owner_takes_its_node_build_down(tmp_path):
+def _build_install(tmp_path: Path) -> tuple[Path, Path]:
+ """A checkout whose ``node`` (a .bat on the build PATH) runs the blocker."""
install = tmp_path / "checkout"
install.mkdir()
(install / "build.py").write_text(_blocker(tmp_path), encoding="utf-8")
@@ -174,13 +176,99 @@ def test_killed_owner_takes_its_node_build_down(tmp_path):
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
(bin_dir / "node.bat").write_text(f'@"{sys.executable}" "{install / "build.py"}"\r\n', encoding="utf-8")
+ return install, bin_dir
+
+
+def test_killed_owner_takes_its_git_child_down(tmp_path):
+ install = _git_install(tmp_path)
+ _tree_dies_with_its_owner(tmp_path, install, [_GIT_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m")])
+
+
+def test_killed_owner_takes_its_node_build_down(tmp_path):
+ install, bin_dir = _build_install(tmp_path)
_tree_dies_with_its_owner(tmp_path, install,
[_BUILD_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m"), str(bin_dir)])
-def test_a_refused_job_join_still_runs_the_child(tmp_path):
- """Custody degrades, never fails: a launcher whose join is refused runs its command anyway."""
- from hermes_cli.update_custody import _CUSTODY_UNAVAILABLE, _JOIN_JOB
+# --- D2: a child the job refuses is fenced or never runs ---------------------------------------
+#
+# Negative control: the update's job handle is replaced by an event handle right before the
+# writer starts, so the REAL AssignProcessToJobObject refuses it (ERROR_INVALID_HANDLE) the way it
+# refuses a process it cannot nest. Invariant: once the owner is killed, an update writer still
+# alive means the checkout lock is still held — or the writer never ran and the owner refused it
+# with a clear message. Never a live writer behind a free lock.
+_REFUSE_JOBS = (
+ "import ctypes\n"
+ "from hermes_cli import update_lock as _ul\n"
+ "_k = ctypes.WinDLL('kernel32', use_last_error=True)\n"
+ "_k.CreateEventW.restype = ctypes.c_void_p\n"
+ "_ul._JOBS[:] = [_k.CreateEventW(None, True, False, None)]\n"
+)
+_GIT_REFUSED_OWNER = _GIT_OWNER.replace("_git_run([", _REFUSE_JOBS + "_git_run([")
+_BUILD_REFUSED_OWNER = _BUILD_OWNER.replace("env = {", _REFUSE_JOBS + "env = {")
+REFUSED = "so it was not run"
+
+
+def _writer_fenced_or_refused(tmp_path: Path, install: Path, owner_args: list[str]) -> str:
+ import psutil
+
+ owner = subprocess.Popen([sys.executable, "-c", *owner_args], stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8",
+ errors="replace")
+ pid_file, tree = tmp_path / "blocker.pid", []
+
+ def started() -> bool:
+ return pid_file.exists() and bool(pid_file.read_text(encoding="utf-8-sig").strip())
+
+ try:
+ deadline = time.time() + 60
+ while not started() and owner.poll() is None:
+ assert time.time() < deadline, "the owner neither ran nor refused its writer"
+ time.sleep(0.1)
+ time.sleep(0.5) # an exiting owner's writer may still be starting
+ if not started():
+ out = owner.communicate(timeout=30)[0]
+ assert owner.returncode != 0 and REFUSED in out, f"the owner neither ran nor refused its writer:\n{out}"
+ return "refused"
+ blocker = psutil.Process(int(pid_file.read_text(encoding="utf-8-sig")))
+ tree = [blocker, *(p for p in blocker.parents() if p.pid != owner.pid and owner.pid in
+ {q.pid for q in p.parents()})]
+ subprocess.run(["taskkill", "/F", "/PID", str(owner.pid)], capture_output=True, check=False)
+ owner.wait(timeout=30)
+ deadline = time.time() + 15
+ while any(p.is_running() for p in tree) and time.time() < deadline:
+ time.sleep(0.2)
+ survivors = [f"{p.pid}:{p.name()}" for p in tree if p.is_running()]
+ assert not survivors or update_in_progress(install), \
+ f"update writer(s) {survivors} outlived the killed owner while the checkout lock is free"
+ return "fenced"
+ finally:
+ (tmp_path / "go").touch()
+ for proc in tree:
+ with contextlib.suppress(Exception):
+ proc.kill()
+ if owner.poll() is None:
+ owner.kill()
+
+
+def test_a_git_child_the_job_refuses_never_runs_unfenced(tmp_path):
+ install = _git_install(tmp_path)
+ outcome = _writer_fenced_or_refused(
+ tmp_path, install, [_GIT_REFUSED_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m")])
+ if outcome == "refused": # refused before it ran: the checkout is untouched
+ stash = subprocess.run(["git", "-C", str(install), "stash", "list"], capture_output=True)
+ assert stash.stdout == b"", stash
+
+
+def test_a_node_build_the_job_refuses_never_runs_unfenced(tmp_path):
+ install, bin_dir = _build_install(tmp_path)
+ _writer_fenced_or_refused(
+ tmp_path, install, [_BUILD_REFUSED_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m"), str(bin_dir)])
+
+
+def test_a_refused_job_join_never_runs_the_command(tmp_path):
+ """D2: a launcher whose join is refused exits without running its command (m1: and says so)."""
+ from hermes_cli.update_custody import _CUSTODY_UNAVAILABLE, _JOIN_JOB, _REFUSED_EXIT
child = "import sys; print('built'); sys.exit(3)"
launcher = tmp_path / "join_job.py" # a file, not -c: the guard reads argv text as a command line
@@ -188,8 +276,8 @@ def test_a_refused_job_join_still_runs_the_child(tmp_path):
report = tmp_path / "report.txt"
out = subprocess.run([sys.executable, "-I", "-S", str(launcher), "0", str(report), sys.executable, "-c", child],
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
- assert out.returncode == 3, out
- assert out.stdout.strip() == "built"
+ assert out.returncode == _REFUSED_EXIT, out
+ assert "built" not in out.stdout
assert _CUSTODY_UNAVAILABLE in out.stderr
# m1: the notice also lands in the report the updater turns into a warning + receipt step
- assert _CUSTODY_UNAVAILABLE in report.read_text(encoding="utf-8")
+ assert _CUSTODY_UNAVAILABLE in report.read_text(encoding="utf-8-sig")