From 757161fabf262bfccbf3eb939030f439810a5a47 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 11:02:57 -0500 Subject: [PATCH 1/4] ci(desktop): keep native-release git calls and their tests from forking native_release.py now owns the git helper, and its three git calls and the git calls in tests/test_native_release.py go through it. The fork guard moves to conftest.py and covers both release test modules. The helper also holds descriptors 0, 1 and 2 open for the length of a call when the process was started with one closed, because Python otherwise falls back to fork. --- packages/desktop/scripts/native_release.py | 111 ++++++++++++++---- packages/desktop/scripts/prepare_release.py | 53 +-------- packages/desktop/tests/conftest.py | 21 ++++ packages/desktop/tests/test_native_release.py | 21 +--- packages/desktop/tests/test_release_intent.py | 42 +++---- 5 files changed, 139 insertions(+), 109 deletions(-) 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..dd0bb0ce4d 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,26 +119,6 @@ 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. - """ - - 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) @@ -156,6 +140,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 +165,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") From d3b20c40827ae6c2b25e17a69c5268546a6f8423 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 11:39:02 -0500 Subject: [PATCH 2/4] test(desktop): restore exact host bytes in the reversion tests on Windows Since #2277 the test helper returns git output without text-mode newline translation. Two tests wrote a CRLF blob back with write_text, which on Windows turned each CRLF into CR CR LF, so the reversion was no longer exact and the feature commit stayed in the release intent. The tests now write the blob's bytes back, and the helper normalizes line endings as the text-mode call did. --- packages/desktop/tests/test_release_intent.py | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index 96f708651d..e8099e08c9 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -140,7 +140,20 @@ def _run_git(root: Path, *args: str, check: bool = False) -> subprocess.Complete def _git(root: Path, *args: str) -> str: - return _run_git(root, *args, check=True).stdout.decode("utf-8").strip() + """Return a git command's output as text, with every line ending as ``\n``. + + 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 _blob(root: Path, spec: str) -> bytes: + """The exact bytes of ``:``.""" + + return _run_git(root, "show", spec, check=True).stdout @pytest.mark.skipif(sys.platform == "win32", reason="Windows has no fork") @@ -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") From 71ad7dc91c3204dac0d50fa62bd9aaf5d305c48d Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 13:02:17 -0500 Subject: [PATCH 3/4] test(desktop): start every test subprocess without forking pytest The session now defaults close_fds to false, which lets Python start a child with posix_spawn, and fails any call that would still fork unless the test asks for the forking_allowed fixture. The summary prints how many subprocesses forked. The wheel tests no longer pass cwd, and the three installer launch tests that need a new session are the only ones allowed to fork. --- packages/desktop/tests/conftest.py | 78 +++++++++++++++---- .../tests/test_native_installer_smoke.py | 12 ++- packages/desktop/tests/test_native_release.py | 3 - packages/desktop/tests/test_release_intent.py | 3 - packages/desktop/tests/test_wheel_layout.py | 23 +++--- 5 files changed, 83 insertions(+), 36 deletions(-) diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index 3cf264c1d5..63ebe17525 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -165,21 +165,71 @@ def no_usage_stats_or_update_check(monkeypatch): monkeypatch.setenv("OPENADAPT_UPDATE_CHECK", "false") +# On the hosted macOS runners a forked copy of the pytest process sometimes never +# reached exec, and pytest then waited inside Popen until the job was cancelled. +# The whole session therefore starts subprocesses without forking. +# +# Python starts a child with posix_spawn instead of fork when the program path +# is absolute, no working directory or new session is asked for, and +# ``close_fds`` is false. Most calls here and in the engine fail only the last +# condition, because ``close_fds`` defaults to true, so the session changes that +# default. Python opens its own descriptors close-on-exec, so a child still +# inherits only its standard streams. A call that would fork anyway fails with +# the reason, unless the test asks for the ``forking_allowed`` fixture. +# Windows has no fork and is left alone. +_FORKS: list[str] = [] +_FORKING_ALLOWED = False + + +def _spawn_is_available() -> bool: + return bool(getattr(subprocess, "_USE_POSIX_SPAWN", False)) + + +@pytest.fixture(scope="session", autouse=True) +def _subprocesses_do_not_fork(): + if not _spawn_is_available(): + yield + return + + patch = pytest.MonkeyPatch() + real_init = subprocess.Popen.__init__ + real_fork_exec = subprocess._fork_exec + + def init(self, *args, **kwargs): + # close_fds is the eighth positional parameter of Popen. + if len(args) < 8 and "close_fds" not in kwargs and not kwargs.get("pass_fds"): + kwargs["close_fds"] = False + real_init(self, *args, **kwargs) + + def fork_exec(args, *rest, **named): + command = " ".join(os.fsdecode(part) for part in args) + if not _FORKING_ALLOWED: + raise AssertionError( + f"{command!r} would fork pytest. Give the program's absolute path, " + "do not pass cwd, start_new_session, preexec_fn or pass_fds, " + "and run git through native_release.run_git." + ) + _FORKS.append(command) + return real_fork_exec(args, *rest, **named) + + patch.setattr(subprocess.Popen, "__init__", init) + patch.setattr(subprocess, "_fork_exec", fork_exec) + yield + patch.undo() + + @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. - """ +def forking_allowed(): + """Let this test start subprocesses that Python can only start with fork.""" - if not getattr(subprocess, "_USE_POSIX_SPAWN", False): - return + global _FORKING_ALLOWED + _FORKING_ALLOWED = True + yield + _FORKING_ALLOWED = False - 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) +def pytest_terminal_summary(terminalreporter) -> None: + if _spawn_is_available(): + terminalreporter.write_line(f"subprocesses that forked pytest: {len(_FORKS)}") + for command in _FORKS: + terminalreporter.write_line(f" forked: {command[:200]}") diff --git a/packages/desktop/tests/test_native_installer_smoke.py b/packages/desktop/tests/test_native_installer_smoke.py index 1cfd35361c..02974b8535 100644 --- a/packages/desktop/tests/test_native_installer_smoke.py +++ b/packages/desktop/tests/test_native_installer_smoke.py @@ -591,13 +591,17 @@ def _fake_launcher(tmp_path: Path, name: str, python_body: str) -> Path: return launcher -def test_launch_probe_accepts_a_process_that_stays_alive(tmp_path: Path) -> None: +def test_launch_probe_accepts_a_process_that_stays_alive( + tmp_path: Path, forking_allowed: None +) -> None: launcher = _fake_launcher(tmp_path, "healthy", "import time\ntime.sleep(60)\n") smoke._launch_probe(launcher, run_seconds=1.0, timeout=30.0) -def test_launch_probe_rejects_a_startup_crash_and_retries_once(tmp_path: Path) -> None: +def test_launch_probe_rejects_a_startup_crash_and_retries_once( + tmp_path: Path, forking_allowed: None +) -> None: attempts = tmp_path / "attempts.log" body = ( "import pathlib, sys\n" @@ -618,7 +622,9 @@ def test_launch_probe_rejects_a_startup_crash_and_retries_once(tmp_path: Path) - assert attempts.read_text().count("attempt") == 2 -def test_launch_probe_reports_an_unlaunchable_executable(tmp_path: Path) -> None: +def test_launch_probe_reports_an_unlaunchable_executable( + tmp_path: Path, forking_allowed: None +) -> None: with pytest.raises(smoke.SmokeTestError, match="could not launch"): smoke._launch_probe(tmp_path / "absent", run_seconds=1.0, timeout=5.0) diff --git a/packages/desktop/tests/test_native_release.py b/packages/desktop/tests/test_native_release.py index e0379e0c78..8cf3e62a14 100644 --- a/packages/desktop/tests/test_native_release.py +++ b/packages/desktop/tests/test_native_release.py @@ -49,9 +49,6 @@ ) 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 = { diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index 59f8f28a59..79793236b2 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -48,9 +48,6 @@ 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, diff --git a/packages/desktop/tests/test_wheel_layout.py b/packages/desktop/tests/test_wheel_layout.py index 869818367c..cababd1fc5 100644 --- a/packages/desktop/tests/test_wheel_layout.py +++ b/packages/desktop/tests/test_wheel_layout.py @@ -39,8 +39,9 @@ def built_wheel(tmp_path_factory: pytest.TempPathFactory) -> Path: pytest.skip("uv is required to build the wheel") out_dir = tmp_path_factory.mktemp("wheel") subprocess.run( - [uv, "build", "--wheel", "--out-dir", str(out_dir)], - cwd=ROOT, + # The project is named as an argument, not through cwd, so Python can + # start uv without forking pytest (see conftest.py). + [uv, "build", "--wheel", "--out-dir", str(out_dir), str(ROOT)], check=True, capture_output=True, text=True, @@ -57,9 +58,7 @@ def test_wheel_installs_only_the_namespaced_package(built_wheel: Path) -> None: assert top_level == {IMPORT_PACKAGE, f"openadapt_desktop-{_version()}.dist-info"} -def test_console_script_runs_from_the_installed_wheel( - built_wheel: Path, tmp_path: Path -) -> None: +def test_console_script_runs_from_the_installed_wheel(built_wheel: Path, tmp_path: Path) -> None: with zipfile.ZipFile(built_wheel) as wheel: entry_points = next( wheel.read(name).decode("utf-8") @@ -69,20 +68,19 @@ def test_console_script_runs_from_the_installed_wheel( site = tmp_path / "site-packages" wheel.extractall(site) - scripts = dict( - line.split(" = ", 1) - for line in entry_points.splitlines() - if " = " in line - ) + scripts = dict(line.split(" = ", 1) for line in entry_points.splitlines() if " = " in line) assert scripts == {"openadapt-desktop": f"{IMPORT_PACKAGE}.cli:main"} module, function = scripts["openadapt-desktop"].split(":") # Put the extracted wheel first so the run proves the installed files work, - # not the editable checkout. ``-I`` keeps PYTHONPATH and the cwd out. + # not the editable checkout. ``-I`` keeps PYTHONPATH and the cwd out. The + # probe changes directory itself, because passing cwd would make Python + # fork pytest to start it (see conftest.py). probe = textwrap.dedent( f""" - import importlib, sys + import importlib, os, sys site = sys.argv[1] + os.chdir(os.path.dirname(site)) sys.path.insert(0, site) module = importlib.import_module({module!r}) assert module.__file__.startswith(site), module.__file__ @@ -92,7 +90,6 @@ def test_console_script_runs_from_the_installed_wheel( ) result = subprocess.run( [sys.executable, "-I", "-c", probe, str(site)], - cwd=tmp_path, capture_output=True, text=True, timeout=120, From af43e78d2d907d613bad46f8fe497d153446c8d2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Thu, 19 Nov 2026 18:06:19 -0500 Subject: [PATCH 4/4] test(desktop): give the engine's process tests Python's real subprocess defaults The session's close_fds default made the engine's own no-fork tests pass whatever the engine did. Those tests now ask for python_subprocess_defaults, which restores Popen's real behaviour for them, and their negative control passes close_fds=True explicitly. --- packages/desktop/tests/conftest.py | 19 ++++++++++++++++++- .../tests/test_engine/test_child_process.py | 6 +++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index 63ebe17525..cdfb7ce65c 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -176,8 +176,10 @@ def no_usage_stats_or_update_check(monkeypatch): # default. Python opens its own descriptors close-on-exec, so a child still # inherits only its standard streams. A call that would fork anyway fails with # the reason, unless the test asks for the ``forking_allowed`` fixture. -# Windows has no fork and is left alone. +# Windows has no fork and is left alone. Tests of how the engine itself starts a +# process ask for ``python_subprocess_defaults`` and get none of this. _FORKS: list[str] = [] +_REAL: dict[str, object] = {} _FORKING_ALLOWED = False @@ -212,10 +214,25 @@ def fork_exec(args, *rest, **named): _FORKS.append(command) return real_fork_exec(args, *rest, **named) + _REAL.update(init=real_init, fork_exec=real_fork_exec) patch.setattr(subprocess.Popen, "__init__", init) patch.setattr(subprocess, "_fork_exec", fork_exec) yield patch.undo() + _REAL.clear() + + +@pytest.fixture +def python_subprocess_defaults(monkeypatch: pytest.MonkeyPatch) -> None: + """Give this test Python's own subprocess behaviour, as the installed engine has it. + + A test that checks how production code starts a process must not get the + session's ``close_fds`` default, or it would pass whatever the code did. + """ + + if _REAL: + monkeypatch.setattr(subprocess.Popen, "__init__", _REAL["init"]) + monkeypatch.setattr(subprocess, "_fork_exec", _REAL["fork_exec"]) @pytest.fixture diff --git a/packages/desktop/tests/test_engine/test_child_process.py b/packages/desktop/tests/test_engine/test_child_process.py index 61ccb8e436..3b5f2b3ff5 100644 --- a/packages/desktop/tests/test_engine/test_child_process.py +++ b/packages/desktop/tests/test_engine/test_child_process.py @@ -12,6 +12,10 @@ from openadapt_desktop import child_process +# These tests check what the engine does with Python's real defaults, so they +# opt out of the test session's own no-fork setup (see tests/conftest.py). +pytestmark = pytest.mark.usefixtures("python_subprocess_defaults") + ENGINE = Path(child_process.__file__).resolve().parent STARTERS = {"run", "Popen", "call", "check_call", "check_output", "getoutput", "getstatusoutput"} OS_STARTERS = {"system", "popen", "fork", "forkpty", "posix_spawn", "posix_spawnp"} @@ -76,7 +80,7 @@ def test_run_starts_a_child_without_forking(fork_refused: None) -> None: ) assert done.returncode == 0 and done.stdout.strip() == "ready" with pytest.raises(AssertionError, match="would fork the engine"): - subprocess.run([sys.executable, "-c", "pass"]) + subprocess.run([sys.executable, "-c", "pass"], close_fds=True) def test_popen_with_pipes_starts_a_child_without_forking(fork_refused: None) -> None: