Skip to content

The agent that grows with you

fix(update): no Node build descendant outlives the build call (review N13)

Tekniumd7709316a91a
diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.py
index eef127eda90..8170bc1f0a4 100644
--- a/hermes_cli/source_build.py
+++ b/hermes_cli/source_build.py
@@ -46,25 +46,25 @@ def source_build_env(base_env: dict | None = None, *, explicit: bool = False) ->
return ensure("npm", base_env=env, explicit=explicit).env
-def run_source_script(project_root: Path, script: str, *args: str, env: dict, label: str) -> None:
+def run_in_custody(project_root: Path, command: list, label: str, **kwargs):
+ """``pm.progress.run_contained`` for a build command that writes the checkout (node, npm):
+ it and everything it starts stay in the update's custody (POSIX: the checkout lock fd and
+ its own process group, killed when it exits; Windows: the owner's kill-on-close job), so the
+ checkout is never handed to a contender while one of them still writes. Outside an update it
+ is ``run_contained`` as is."""
from pm.progress import run_contained
from hermes_cli.update_custody import contained_command
- from hermes_cli.update_lock import checkout_lock_fds
- # The build writes the checkout: node (and npm/esbuild under it) stays in the update's custody
- # (POSIX: the checkout lock fd; Windows: the owner's kill-on-close job), so the checkout is
- # never handed to a contender while it still writes.
- fds = checkout_lock_fds(project_root)
+ with contained_command(command, root=project_root) as (argv, custody):
+ return run_contained(argv, label, **kwargs, **custody)
+
+
+def run_source_script(project_root: Path, script: str, *args: str, env: dict, label: str) -> None:
command = [shutil.which("node", path=env["PATH"]), str(project_root / script), *args]
- with contained_command(command) as (argv, custody):
- if fds and "pass_fds" not in custody: # an inherited lock fd this process did not take
- custody = {**custody, "pass_fds": fds}
- # npm's deprecation warnings are the loudest lines and never actionable
- # here; they still land in the failure tail.
- run_contained(
- argv, label, hide=lambda line: line.lower().startswith("npm warn"), indent=" ",
- cwd=project_root, env=env, **custody,
- )
+ # npm's deprecation warnings are the loudest lines and never actionable
+ # here; they still land in the failure tail.
+ run_in_custody(project_root, command, label, hide=lambda line: line.lower().startswith("npm warn"),
+ indent=" ", cwd=project_root, env=env)
def prepare_source_dependencies(project_root: Path, workspaces: tuple[str, ...], *, env: dict,
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.py
index 26a2aee0e82..d9184d9fec0 100644
--- a/hermes_cli/update_custody.py
+++ b/hermes_cli/update_custody.py
@@ -447,16 +447,40 @@ def _join_launcher_python() -> str:
return sys.executable
+# POSIX twin of the launcher: Node marks the donated lock fd close-on-exec, so nothing node
+# starts (npm, esbuild, sh) keeps the checkout locked. The command runs as its own process group
+# under this stdlib parent, which holds the fd too and, once the command exits (or this parent is
+# interrupted), kills the whole group: no descendant outlives the custodial command (N13).
+_OWN_GROUP = (
+ "import os, signal, subprocess, sys\n"
+ "fds = tuple(int(fd) for fd in sys.argv[1].split(','))\n"
+ "p = subprocess.Popen(sys.argv[2:], pass_fds=fds, start_new_session=True)\n"
+ "try:\n"
+ " code = p.wait()\n"
+ "finally:\n"
+ " try:\n"
+ " os.killpg(p.pid, signal.SIGKILL)\n" # windows-footgun: ok — POSIX-only launcher
+ " except OSError:\n"
+ " pass\n"
+ "sys.exit(code if code >= 0 else 128 - code)\n"
+)
+
+
@contextlib.contextmanager
-def contained_command(argv: Sequence[str], *, inherit_lock: bool = True):
+def contained_command(argv: Sequence[str], *, inherit_lock: bool = True, root=None):
"""``(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; when the job
- cannot be handed over or the join is refused, the command never runs and
- :class:`CustodyRefused` is raised (D2)."""
+ build in ``pm.progress.run_contained``). POSIX: the lock fd (this process's, or one it
+ inherited for checkout ``root``), with the command's process group killed when it exits.
+ Windows inside an update: the 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)
+ from hermes_cli.update_lock import checkout_lock_fds
+
+ fds = tuple(checkout_lock_fds(root)) if inherit_lock and root is not None else _lock_fds(inherit_lock)
+ if fds:
+ argv = [sys.executable, "-I", "-S", "-c", _OWN_GROUP, ",".join(map(str, fds)), *argv]
yield argv, ({"pass_fds": fds} if fds else {})
return
try:
diff --git a/tests/hermes_cli/test_update_custody.py b/tests/hermes_cli/test_update_custody.py
index 3a3bfaa9bba..869328b2a1e 100644
--- a/tests/hermes_cli/test_update_custody.py
+++ b/tests/hermes_cli/test_update_custody.py
@@ -316,3 +316,37 @@ def test_a_timed_out_child_never_waits_on_a_grandchild_holding_its_pipes(monkeyp
with pytest.raises(subprocess.TimeoutExpired):
update_custody.run(["sh", "-c", "sleep 20 & sleep 20"], capture_output=True, timeout=0.5)
assert time.monotonic() - started < 15, "run() waited on a grandchild after the timeout"
+
+
+def _held_lock_recorder(tmp_path: Path, name: str, body: str) -> Path:
+ """An executable on a fresh PATH dir that records whether it holds the checkout lock fd."""
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir(exist_ok=True)
+ exe = bin_dir / name
+ exe.write_text(_RECORDER.replace('exec "$@"', body), encoding="utf-8")
+ exe.chmod(0o755)
+ return exe
+
+
[email protected](not Path("/proc/self/fd").is_dir(), reason="needs /proc fd listing")
+def test_no_build_descendant_outlives_the_build_call(repo, tmp_path, monkeypatch):
+ """N13: node marks the donated lock fd close-on-exec, so npm/esbuild under it never hold the
+ checkout; custody rested on node alone. A node that dies leaving a writer behind must not
+ leave it running once the build call returns: the next lock owner would share the checkout."""
+ from hermes_cli.source_build import run_source_script
+
+ late = tmp_path / "late"
+ writer = f"import os, time; os.closerange(3, 4096); time.sleep(2); __import__('pathlib').Path({str(late)!r}).touch()"
+ node = _held_lock_recorder(tmp_path, "node", f"{sys.executable} -c \"{writer}\" >/dev/null 2>&1 &\nexit 1")
+ monkeypatch.setenv("HERMES_TEST_LOCK", os.path.realpath(ul.checkout_lock_path(repo)))
+ monkeypatch.setenv("HERMES_TEST_OUT", str(tmp_path / "node.out"))
+ lock = ul.UpdateLock(path=tmp_path / "marker", install_root=repo)
+ assert lock.acquire()
+ try:
+ with pytest.raises(subprocess.CalledProcessError):
+ run_source_script(repo, "build.mjs", env={**os.environ, "PATH": f"{node.parent}{os.pathsep}{os.environ['PATH']}"}, label="probe")
+ finally:
+ lock.release()
+ time.sleep(3)
+ assert not late.exists(), "a build descendant kept writing after the build call returned"
+