From e030f340737ebecfb4bf687175d341ca9adfd8b2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 10:20:18 -0500 Subject: [PATCH 1/2] ci(desktop): start git without forking in the release tooling and its tests On the hosted macOS runners a forked copy of the pytest process sometimes never reached exec, so the parent waited inside Popen where the per-call timeout could not apply, and the test hit its 300-second deadline. The release scripts and the tests now run every git command through one helper that uses posix_spawn, takes the directory through git -C, gives each call a 120-second timeout that names the command, and reads no terminal input. A guard in the test module fails any subprocess that would fork pytest. --- .../desktop/scripts/check_release_intent.py | 9 +- packages/desktop/scripts/prepare_release.py | 99 ++++++++++++------- packages/desktop/tests/test_release_intent.py | 73 +++++++++----- 3 files changed, 113 insertions(+), 68 deletions(-) diff --git a/packages/desktop/scripts/check_release_intent.py b/packages/desktop/scripts/check_release_intent.py index debfaf2968..c3bae93704 100644 --- a/packages/desktop/scripts/check_release_intent.py +++ b/packages/desktop/scripts/check_release_intent.py @@ -19,7 +19,6 @@ import argparse import re -import subprocess import sys from pathlib import Path @@ -35,13 +34,7 @@ def version_at(root: Path, ref: str) -> str: - text = subprocess.run( - ["git", "show", f"{ref}:./pyproject.toml"], - cwd=root, - check=True, - capture_output=True, - text=True, - ).stdout + text = prepare_release.run_git(root, "show", f"{ref}:./pyproject.toml").stdout.decode("utf-8") match = PYPROJECT_VERSION.search(text) if match is None: raise ValueError(f"could not read the version at {ref}") diff --git a/packages/desktop/scripts/prepare_release.py b/packages/desktop/scripts/prepare_release.py index 3227a5c0f9..9c283196c7 100644 --- a/packages/desktop/scripts/prepare_release.py +++ b/packages/desktop/scripts/prepare_release.py @@ -25,8 +25,11 @@ import copy import datetime import difflib +import functools import json +import os import re +import shutil import subprocess import sys import tempfile @@ -78,10 +81,57 @@ def breaking(self) -> bool: return bool(match and match.group("bang")) or "BREAKING CHANGE:" in self.body +# Every git call here is a local read of history. The slowest takes well under a +# second, so one that runs this long is stuck. +GIT_TIMEOUT = 120 + + +class GitTimeout(RuntimeError): + """A git command did not finish in time.""" + + +@functools.lru_cache(maxsize=None) +def _git_executable(search_path: str | None) -> str: + found = shutil.which("git", path=search_path) + if found is None: + raise FileNotFoundError("git is not on PATH") + return os.path.abspath(found) + + +def run_git( + root: Path, *args: str, check: bool = True, input: bytes | None = None +) -> subprocess.CompletedProcess[bytes]: + """Run one git command in ``root`` without forking this process. + + On macOS a forked copy of a Python process that has loaded system + frameworks can stop before it ever runs git, and the parent then waits + inside Popen where no timeout applies. Python starts the child with + posix_spawn instead of fork when the program path is absolute, no working + directory is passed and inherited descriptors are left alone, so git gets + its directory from ``-C``. Python opens its own descriptors close-on-exec, + so git still inherits only its three pipes. The timeout then covers the + whole call, and a stuck command fails with its name. + """ + + command = [_git_executable(os.environ.get("PATH")), "-C", str(root), *args] + try: + return subprocess.run( + command, + check=check, + capture_output=True, + input=input, + stdin=subprocess.DEVNULL if input is None else None, + close_fds=os.name != "posix", + timeout=GIT_TIMEOUT, + ) + except subprocess.TimeoutExpired as exc: + raise GitTimeout( + f"git {' '.join(args)} did not finish within {GIT_TIMEOUT}s in {root}" + ) from exc + + def _git(root: Path, *args: str) -> str: - return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True).stdout.decode( - "utf-8" - ) + return run_git(root, *args).stdout.decode("utf-8") def parse_version(version: str) -> tuple[int, int, int]: @@ -344,18 +394,14 @@ def _clean_path_merge( size = int(_git(root, "cat-file", "-s", value[1]).strip()) if not 0 <= size <= 8 * 1024 * 1024: raise ValueError("a net Desktop merge blob exceeds its reconstruction bound") - content = subprocess.run( - ["git", "cat-file", "blob", value[1]], cwd=root, check=True, capture_output=True - ).stdout + content = run_git(root, "cat-file", "blob", value[1]).stdout if len(content) != size or b"\0" in content: raise ValueError("a net Desktop merge has non-text or incomplete blob data") contents.append(content) target = Path(directory) / label target.write_bytes(content) files.append(str(target)) - merged = subprocess.run( - ["git", "merge-file", "--stdout", *files], cwd=root, capture_output=True - ) + merged = run_git(root, "merge-file", "--stdout", *files, check=False) if path in RELEASE_VERSION_FIELDS: # A merge may select a generated engine version, but it may not # invent any other bytes. Normalize only witnessed literal spans, @@ -366,12 +412,7 @@ def _clean_path_merge( size = int(_git(root, "cat-file", "-s", resolved[1]).strip()) if not 0 <= size <= 8 * 1024 * 1024: raise ValueError("release resolution exceeds its content bound") - actual = subprocess.run( - ["git", "cat-file", "blob", resolved[1]], - cwd=root, - check=True, - capture_output=True, - ).stdout + actual = run_git(root, "cat-file", "blob", resolved[1]).stdout if len(actual) != size or b"\0" in actual: raise ValueError("release resolution has incomplete or non-text data") if merged.returncode != 0 or actual != merged.stdout: @@ -380,21 +421,11 @@ def _clean_path_merge( version = text[spans[0][0] : spans[0][1]] for target, content in zip(files, contents, strict=True): Path(target).write_bytes(_release_content(path, content, version)) - merged = subprocess.run( - ["git", "merge-file", "--stdout", *files], cwd=root, capture_output=True - ) + merged = run_git(root, "merge-file", "--stdout", *files, check=False) if merged.returncode != 0: raise ValueError("a net Desktop merge resolution has no clean combination") oid = ( - subprocess.run( - ["git", "hash-object", "--stdin"], - cwd=root, - input=merged.stdout, - check=True, - capture_output=True, - ) - .stdout.decode("ascii") - .strip() + run_git(root, "hash-object", "--stdin", input=merged.stdout).stdout.decode("ascii").strip() ) if re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", oid) is None: raise ValueError("a net Desktop merge result has incomplete object metadata") @@ -498,9 +529,7 @@ def content(oid: str) -> bytes: size = int(_git(root, "cat-file", "-s", oid).strip()) if not 0 <= size <= 8 * 1024 * 1024: raise ValueError("a Desktop copy source exceeds its content bound") - raw = subprocess.run( - ["git", "cat-file", "blob", oid], cwd=root, check=True, capture_output=True - ).stdout + raw = run_git(root, "cat-file", "blob", oid).stdout if len(raw) != size: raise ValueError("a Desktop copy source has incomplete content") blob_cache[oid] = raw @@ -826,11 +855,7 @@ def last_version_change(root: Path) -> str: maximal = set(origins) for candidate in origins: for other in origins - {candidate}: - result = subprocess.run( - ["git", "merge-base", "--is-ancestor", candidate, other], - cwd=root, - capture_output=True, - ) + result = run_git(root, "merge-base", "--is-ancestor", candidate, other, check=False) if result.returncode == 0: maximal.discard(candidate) elif result.returncode != 1: @@ -851,9 +876,7 @@ def _release_commits(root: Path, base: str | None, current: str) -> list[Commit] _complete_release_history(root) if _commit_identity(root, base) != base: raise ValueError("--base does not identify the declared commit") - result = subprocess.run( - ["git", "merge-base", "--is-ancestor", base, "HEAD"], cwd=root, capture_output=True - ) + result = run_git(root, "merge-base", "--is-ancestor", base, "HEAD", check=False) if result.returncode != 0: raise ValueError("--base must be an available ancestor of HEAD") text = (root / "pyproject.toml").read_text(encoding="utf-8") diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index d8a5f18f08..b1a0efa626 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -52,7 +52,9 @@ def _load(name: str): # release scripts under test. Each git call gets no terminal input, no editor, # pager, prompt or signing, and none of the machine's global or system Git # configuration, so a call either finishes or fails; it never waits for input. -GIT_TIMEOUT = 120 +# Every call goes through prepare_release.run_git, which starts git without +# forking pytest and stops a call that outlasts its own timeout. +# # The slowest test here takes under 20 seconds on a hosted macOS runner. A test # that runs much longer is stuck, so it fails with a traceback that shows where # instead of using up the CI job's time limit. @@ -113,27 +115,54 @@ def expire(_signum, _frame): signal.signal(signal.SIGALRM, previous) -def _run_git( - root: Path, *args: str, check: bool = False, text: bool = False -) -> subprocess.CompletedProcess: - try: - return subprocess.run( - ["git", *args], - cwd=root, - check=check, - capture_output=True, - text=text, - stdin=subprocess.DEVNULL, - timeout=GIT_TIMEOUT, - ) - except subprocess.TimeoutExpired as exc: - raise AssertionError( - f"git {' '.join(args)} did not finish within {GIT_TIMEOUT}s in {root}" - ) from exc +@pytest.fixture(autouse=True) +def _no_fork(monkeypatch: pytest.MonkeyPatch) -> None: + """Fail any subprocess in this module that would fork pytest. + + By the time these tests run, earlier tests have loaded macOS system + frameworks into the pytest process. On the hosted macOS runners a forked + copy of that process sometimes never reached exec, and the parent waited + inside Popen until the job was cancelled. With this guard a call that + brings the fork back fails at once, on Linux as well as macOS. + """ + + if not getattr(subprocess, "_USE_POSIX_SPAWN", False): + return + + def refuse(args, *_rest, **_named): + raise AssertionError(f"{args!r} would fork pytest; run git through prepare_release.run_git") + + monkeypatch.setattr(subprocess, "_fork_exec", refuse) + + +def _run_git(root: Path, *args: str, check: bool = False) -> subprocess.CompletedProcess[bytes]: + return prepare_release.run_git(root, *args, check=check) def _git(root: Path, *args: str) -> str: - return _run_git(root, *args, check=True, text=True).stdout.strip() + return _run_git(root, *args, check=True).stdout.decode("utf-8").strip() + + +@pytest.mark.skipif(sys.platform != "darwin", reason="the hang this prevents is on macOS") +def test_git_never_forks_on_macos() -> None: + """The _no_fork guard is only active when Python can spawn without forking.""" + + assert subprocess._USE_POSIX_SPAWN + assert callable(subprocess._fork_exec) + + +@pytest.mark.skipif(sys.platform == "win32", reason="the stand-in git is a shell script") +def test_a_stuck_git_command_fails_with_its_name( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + stand_in = tmp_path / "bin" / "git" + stand_in.parent.mkdir() + stand_in.write_text("#!/bin/sh\nexec /bin/sleep 30\n", encoding="utf-8") + stand_in.chmod(0o755) + monkeypatch.setenv("PATH", str(stand_in.parent)) + monkeypatch.setattr(prepare_release, "GIT_TIMEOUT", 0.5) + with pytest.raises(prepare_release.GitTimeout, match="git rev-parse HEAD did not finish"): + prepare_release.run_git(tmp_path, "rev-parse", "HEAD") def _commit(root: Path, message: str, touch: str | None = None) -> str: @@ -681,7 +710,7 @@ def _merge_independent_release(repo: Path, main: str, feature: str, number: int) package.write_text(json.dumps(data) + "\n") base = _commit(repo, f"chore: independently prepare main {number}") _git(repo, "checkout", "-q", feature) - merged = _run_git(repo, "merge", "--no-ff", "--no-commit", main, text=True) + merged = _run_git(repo, "merge", "--no-ff", "--no-commit", main) assert merged.returncode in {0, 1}, merged.stderr if merged.returncode: assert _git(repo, "diff", "--name-only", "--diff-filter=U") == "package.json" @@ -792,7 +821,7 @@ def _two_sided_history(repo: Path, subject: str, reverse: bool, *, conflict: boo host.write_text("".join(ambient)) base = _commit(repo, "feat: independently change main host") _git(repo, "checkout", "-q", "two-sided-feature") - merged = _run_git(repo, "merge", "--no-ff", "--no-commit", main, text=True) + merged = _run_git(repo, "merge", "--no-ff", "--no-commit", main) assert merged.returncode == int(conflict), merged.stderr if not conflict: text = host.read_text() @@ -1418,7 +1447,7 @@ def _resolve_version_merge( repo, "checkout", "-q", "-B", "release-resolution", feature if first == "feature" else main ) other = main if first == "feature" else feature - result = _run_git(repo, "merge", "--no-ff", "--no-commit", other, text=True) + result = _run_git(repo, "merge", "--no-ff", "--no-commit", other) assert result.returncode in {0, 1}, result.stderr # Resolve only the generated version files. The independent runtime files # are the ordinary merge result; no source code is fabricated by the helper. From a8195ce726ea8563364e1b7da38c7b42bb62e127 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 10:23:47 -0500 Subject: [PATCH 2/2] test(desktop): show the fork guard refuses the call pattern that stalled --- packages/desktop/tests/test_release_intent.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index b1a0efa626..96f708651d 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -143,12 +143,17 @@ def _git(root: Path, *args: str) -> str: return _run_git(root, *args, check=True).stdout.decode("utf-8").strip() -@pytest.mark.skipif(sys.platform != "darwin", reason="the hang this prevents is on macOS") -def test_git_never_forks_on_macos() -> None: - """The _no_fork guard is only active when Python can spawn without forking.""" - - assert subprocess._USE_POSIX_SPAWN - assert callable(subprocess._fork_exec) +@pytest.mark.skipif(sys.platform == "win32", reason="Windows has no fork") +def test_a_subprocess_that_would_fork_pytest_fails(tmp_path: Path) -> None: + """The guard is active on macOS and stops the call pattern that stalled there.""" + + if sys.platform == "darwin": + assert subprocess._USE_POSIX_SPAWN + if not subprocess._USE_POSIX_SPAWN: + pytest.skip("this Python cannot start a process without forking") + with pytest.raises(AssertionError, match="would fork pytest"): + subprocess.run(["git", "--version"], cwd=tmp_path, capture_output=True) + assert prepare_release.run_git(tmp_path, "--version").stdout.startswith(b"git version") @pytest.mark.skipif(sys.platform == "win32", reason="the stand-in git is a shell script")