diff --git a/packages/desktop/scripts/native_release.py b/packages/desktop/scripts/native_release.py index 88c698bda3..f3d095ac0b 100644 --- a/packages/desktop/scripts/native_release.py +++ b/packages/desktop/scripts/native_release.py @@ -14,6 +14,7 @@ from __future__ import annotations import argparse +import functools import hashlib import json import os @@ -353,6 +354,78 @@ def _require_existing_file(path: Path, *, label: str) -> Path: return path +# 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 _hold_standard_descriptors() -> list[int]: + """Occupy any of descriptors 0, 1 and 2 that are closed; return the ones opened.""" + + held: list[int] = [] + if os.name != "posix": + return held + while True: + descriptor = os.open(os.devnull, os.O_RDWR) + if descriptor > 2: + os.close(descriptor) + return held + held.append(descriptor) + + +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. + + Python also falls back to fork when one of git's pipes is numbered 0, 1 or + 2, which happens when this process was started with a standard descriptor + closed. Those numbers are held open on the null device for the length of + the call so the pipes always get higher ones. + """ + + command = [_git_executable(os.environ.get("PATH")), "-C", str(root), *args] + held = _hold_standard_descriptors() + 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 + finally: + for descriptor in held: + os.close(descriptor) + + def _resolve_commit(root: Path, ref: str) -> str: """Resolve one caller ref to its 40-character commit id. @@ -363,14 +436,8 @@ def _resolve_commit(root: Path, ref: str) -> str: if not isinstance(ref, str) or not ref or ref.startswith("-"): raise ValueError(f"invalid Git ref: {ref!r}") - result = subprocess.run( - ["git", "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], - cwd=root, - check=False, - capture_output=True, - text=True, - ) - commit = result.stdout.strip() + result = run_git(root, "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}", check=False) + commit = result.stdout.decode("utf-8", "replace").strip() if result.returncode != 0 or not GIT_COMMIT_PATTERN.fullmatch(commit): raise ValueError(f"Git ref {ref!r} does not name exactly one commit") return commit @@ -379,14 +446,9 @@ def _resolve_commit(root: Path, ref: str) -> str: def _git_bytes(root: Path, commit: str, relative_path: str) -> bytes: if not GIT_COMMIT_PATTERN.fullmatch(commit): raise ValueError(f"expected a resolved commit id, got {commit!r}") - result = subprocess.run( - # "./" resolves the path from cwd=root, so this works whether root is - # the repository root or packages/desktop inside the OpenAdapt monorepo. - ["git", "show", f"{commit}:./{relative_path}"], - cwd=root, - check=False, - capture_output=True, - ) + # "./" resolves the path from root, so this works whether root is the + # repository root or packages/desktop inside the OpenAdapt monorepo. + result = run_git(root, "show", f"{commit}:./{relative_path}", check=False) if result.returncode != 0: raise ValueError(f"Git commit {commit!r} does not contain {relative_path!r}") return result.stdout @@ -436,17 +498,20 @@ def validate_git_version_transform( raise ValueError(f"native version must be X.Y.Z, got {version!r}") base_commit = _resolve_commit(root, base_ref) candidate_commit = _resolve_commit(root, candidate_ref) - changed = subprocess.run( - # --relative: paths from root, limited to it (packages/desktop in the monorepo). - ["git", "diff", "--relative", "--name-only", f"{base_commit}..{candidate_commit}", "--"], - cwd=root, + # --relative: paths from root, limited to it (packages/desktop in the monorepo). + changed = run_git( + root, + "diff", + "--relative", + "--name-only", + f"{base_commit}..{candidate_commit}", + "--", check=False, - capture_output=True, - text=True, ) if changed.returncode != 0: raise ValueError("could not compare engine and native tag trees") - changed_paths = {line for line in changed.stdout.splitlines() if line} + listing = changed.stdout.decode("utf-8", "replace") + changed_paths = {line for line in listing.splitlines() if line} unexpected = changed_paths.difference(VERSION_TRANSFORM_PATHS) if unexpected: raise ValueError( diff --git a/packages/desktop/scripts/prepare_release.py b/packages/desktop/scripts/prepare_release.py index 9c283196c7..4a8e9c318d 100644 --- a/packages/desktop/scripts/prepare_release.py +++ b/packages/desktop/scripts/prepare_release.py @@ -25,11 +25,8 @@ import copy import datetime import difflib -import functools import json -import os import re -import shutil import subprocess import sys import tempfile @@ -81,53 +78,9 @@ 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 +# One helper starts every git process here and in the tests; see its docstring. +GitTimeout = native_release.GitTimeout +run_git = native_release.run_git def _git(root: Path, *args: str) -> str: diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index d7208a88b3..3cf264c1d5 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import subprocess from pathlib import Path import pytest @@ -162,3 +163,23 @@ def no_usage_stats_or_update_check(monkeypatch): monkeypatch.setenv("DO_NOT_TRACK", "1") monkeypatch.setenv("OPENADAPT_UPDATE_CHECK", "false") + + +@pytest.fixture +def no_subprocess_fork(monkeypatch: pytest.MonkeyPatch) -> None: + """Fail any subprocess that would fork pytest. + + By the time the release 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 native_release.run_git") + + monkeypatch.setattr(subprocess, "_fork_exec", refuse) diff --git a/packages/desktop/tests/test_native_release.py b/packages/desktop/tests/test_native_release.py index e4f2e89d82..e0379e0c78 100644 --- a/packages/desktop/tests/test_native_release.py +++ b/packages/desktop/tests/test_native_release.py @@ -24,6 +24,7 @@ native_version_at_ref, native_versions, python_distribution_names, + run_git, set_native_version, stage_artifacts, sync_native_version_from_engine, @@ -48,6 +49,9 @@ ) ROOT = Path(__file__).resolve().parents[1] +# These tests run in the same pytest process as the release-intent tests, so +# their git calls must not fork it either; see conftest.py. +pytestmark = pytest.mark.usefixtures("no_subprocess_fork") # Desktop's workflows run from the OpenAdapt monorepo root. MONOREPO_WORKFLOWS = ROOT.parents[1] / ".github" / "workflows" WORKFLOW_FILES = { @@ -557,14 +561,7 @@ def test_set_native_version_rejects_non_semver_input(tmp_path: Path) -> None: def _git(tmp_path: Path, *args: str) -> str: - result = subprocess.run( - ["git", *args], - cwd=tmp_path, - check=True, - capture_output=True, - text=True, - ) - return result.stdout.strip() + return run_git(tmp_path, *args).stdout.decode("utf-8").strip() def test_git_version_transform_requires_the_exact_reconstructed_tree(tmp_path: Path) -> None: @@ -1416,13 +1413,7 @@ def test_git_helpers_refuse_an_option_shaped_ref(tmp_path: Path) -> None: def test_native_version_at_ref_reads_git_objects_not_the_working_tree() -> None: - head = subprocess.run( - ["git", "rev-parse", "HEAD"], - cwd=ROOT, - check=True, - capture_output=True, - text=True, - ).stdout.strip() + head = _git(ROOT, "rev-parse", "HEAD") assert native_version_at_ref(head) == native_version() assert native_version_at_ref("HEAD") == native_version() diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index 96f708651d..59f8f28a59 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -5,6 +5,7 @@ import datetime import importlib.util import json +import os import re import shutil import signal @@ -47,6 +48,9 @@ def _load(name: str): check_release_intent = _load("check_release_intent") check_release_consistency = _load("check_release_consistency") +# Any subprocess in this module that would fork pytest fails; see conftest.py. +pytestmark = pytest.mark.usefixtures("no_subprocess_fork") + # These tests start thousands of real git processes, many of them from the # release scripts under test. Each git call gets no terminal input, no editor, @@ -115,32 +119,25 @@ def expire(_signum, _frame): signal.signal(signal.SIGALRM, previous) -@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. - """ +def _run_git(root: Path, *args: str, check: bool = False) -> subprocess.CompletedProcess[bytes]: + return prepare_release.run_git(root, *args, check=check) - 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") +def _git(root: Path, *args: str) -> str: + """Return a git command's output as text, with every line ending as ``\n``. - monkeypatch.setattr(subprocess, "_fork_exec", refuse) + A blob committed on Windows can hold CRLF, and writing that text back with + write_text there would turn each CRLF into CR CR LF. + """ + text = _run_git(root, *args, check=True).stdout.decode("utf-8") + return text.replace("\r\n", "\n").replace("\r", "\n").strip() -def _run_git(root: Path, *args: str, check: bool = False) -> subprocess.CompletedProcess[bytes]: - return prepare_release.run_git(root, *args, check=check) +def _blob(root: Path, spec: str) -> bytes: + """The exact bytes of ``:``.""" -def _git(root: Path, *args: str) -> str: - return _run_git(root, *args, check=True).stdout.decode("utf-8").strip() + return _run_git(root, "show", spec, check=True).stdout @pytest.mark.skipif(sys.platform == "win32", reason="Windows has no fork") @@ -156,6 +153,22 @@ def test_a_subprocess_that_would_fork_pytest_fails(tmp_path: Path) -> None: assert prepare_release.run_git(tmp_path, "--version").stdout.startswith(b"git version") +@pytest.mark.skipif(sys.platform == "win32", reason="Windows has no fork") +def test_git_does_not_fork_when_standard_input_is_closed(tmp_path: Path) -> None: + """With descriptor 0 closed, git's pipes would be numbered low and Python would fork.""" + + saved = os.dup(0) + try: + os.close(0) + result = prepare_release.run_git(tmp_path, "--version") + with pytest.raises(OSError): + os.fstat(0) # the call leaves the descriptor closed, as it found it + finally: + os.dup2(saved, 0) + os.close(saved) + assert result.stdout.startswith(b"git version") + + @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 @@ -165,7 +178,7 @@ def test_a_stuck_git_command_fails_with_its_name( 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) + monkeypatch.setattr(prepare_release.native_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") @@ -943,7 +956,7 @@ def test_exact_reversion_after_combination_discards_merged_feature_intent( ) -> None: base, origin, host = _two_sided_history(repo, "feat", False) _commit(repo, "merge: combine independent host edits") - host.write_text(_git(repo, "show", base + ":src/host.txt") + "\n") + host.write_bytes(_blob(repo, base + ":src/host.txt")) _commit(repo, "chore: restore the exact ambient host") head = _commit(repo, f"{subject}: unrelated retained change", touch="src/retained.txt") commits = prepare_release.commits_for_net_diff(repo, base, head) @@ -957,7 +970,7 @@ def test_test_merge_keeps_a_canceled_feature_out_of_surviving_intent( ) -> None: base, _origin, host = _two_sided_history(repo, "feat", False) _commit(repo, "merge: combine independent host edits") - host.write_text(_git(repo, "show", base + ":src/host.txt") + "\n") + host.write_bytes(_blob(repo, base + ":src/host.txt")) _commit(repo, "chore: restore exact ambient host") _commit(repo, f"{subject}: retained change", touch="src/retained.txt") branch = _git(repo, "branch", "--show-current")