From 8669b6eb2f5a83018791c67004f5166b0a8324cf Mon Sep 17 00:00:00 2001 From: "devops-cli-service[bot]" <349441588+devops-cli-service[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:36:42 +0000 Subject: [PATCH 1/5] fix(ci): Skip the collection in the tests that read the pytest run (#4472) --- .../tasks.md | 6 +- src/devops_cli/commands/ci.py | 55 ++++++- src/devops_cli/config/defaults.py | 5 + src/devops_cli/lang/en/help.py | 5 +- src/devops_cli/lang/en/messages.py | 4 + tests/commands/test_ci.py | 17 ++- tests/commands/test_ci_repeat.py | 6 +- tests/commands/test_test_selection.py | 144 +++++++++++++++--- 8 files changed, 209 insertions(+), 33 deletions(-) diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md index 2b49466555..7167be4b94 100644 --- a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md +++ b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md @@ -4,16 +4,16 @@ Kind: behavior. Reads: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/lang/en/help.py`, `src/devops_cli/roadmap/implement/implement_test_form.py`, `tests/commands/test_test_selection.py`, `tests/support/fakes/process.py`, `tests/support/session_spawns.py`. Changes: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/lang/en/help.py`, `tests/commands/test_test_selection.py`. -- [ ] 1.1 Add the failing case `tests/commands/test_test_selection.py::test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers` and replace `tests/commands/test_test_selection.py::test_a_selection_past_the_serial_limit_runs_on_the_capped_workers` with it, because the file count no longer decides alone +- [x] 1.1 Add the failing case `tests/commands/test_test_selection.py::test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers` and replace `tests/commands/test_test_selection.py::test_a_selection_past_the_serial_limit_runs_on_the_capped_workers` with it, because the file count no longer decides alone - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` fails on the base -- [ ] 1.2 Write the failing cases first in `tests/commands/test_test_selection.py`: import `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` and `ProcessAnswer`, make `_pytest_runs` and `_started_runs` skip a child that holds `--collect-only`, and answer the collection with `process_fake.answer` and a matcher on `--collect-only` whose `ProcessAnswer` stdout holds one test id on each line. A collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1` ids runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`; a collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` ids runs serially; a collection that exits 5 runs serially and prints no warning; a collection that exits 3 over 13 target files prints the warning and runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`, because the file-count rule gives 4 workers above 12 files while a count of zero gives `-n 0`; a `-k slow` selection passes `-k slow` to the collection and to the run; a given `-n` and a run with no paths make no collection call. Then add `DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50` beside the file-count constant with a comment that states the rule, add the collection-failure warning to the CI messages beside `repeat_seed_unavailable`, and rewrite the `-n` help text to say that the collected tests choose the workers. Add `_collection_cmd(targets, keyword)`, which returns `[*_build_test_cmd("0", False, keyword, False, None), "--collect-only", "-q", *targets]`, and `_collected_test_count(targets, keyword)`, which returns None in a dry run, starts the command with `asyncio.run(_run_in_own_session(cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None))`, returns 0 on exit 5, returns None with the warning on `subprocess.TimeoutExpired` or any other non-zero exit, re-raises `asyncio.CancelledError` as `typer.Exit(CONST_EXIT_CANCELLED)`, and otherwise returns `collected_items(stdout)`. Give `_narrowed_workers(targets, collected)` the collected count and keep the count of test modules for the None case +- [x] 1.2 Write the failing cases first in `tests/commands/test_test_selection.py`: import `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` and `ProcessAnswer`, make `_pytest_runs` and `_started_runs` skip a child that holds `--collect-only`, and answer the collection with `process_fake.answer` and a matcher on `--collect-only` whose `ProcessAnswer` stdout holds one test id on each line. A collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1` ids runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`; a collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` ids runs serially; a collection that exits 5 runs serially and prints no warning; a collection that exits 3 over 13 target files prints the warning and runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`, because the file-count rule gives 4 workers above 12 files while a count of zero gives `-n 0`; a `-k slow` selection passes `-k slow` to the collection and to the run; a given `-n` and a run with no paths make no collection call. Then add `DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50` beside the file-count constant with a comment that states the rule, add the collection-failure warning to the CI messages beside `repeat_seed_unavailable`, and rewrite the `-n` help text to say that the collected tests choose the workers. Add `_collection_cmd(targets, keyword)`, which returns `[*_build_test_cmd("0", False, keyword, False, None), "--collect-only", "-q", *targets]`, and `_collected_test_count(targets, keyword)`, which returns None in a dry run, starts the command with `asyncio.run(_run_in_own_session(cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None))`, returns 0 on exit 5, returns None with the warning on `subprocess.TimeoutExpired` or any other non-zero exit, re-raises `asyncio.CancelledError` as `typer.Exit(CONST_EXIT_CANCELLED)`, and otherwise returns `collected_items(stdout)`. Give `_narrowed_workers(targets, collected)` the collected count and keep the count of test modules for the None case - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` passes ## 2. Skip the collection in the tests that read the pytest run Kind: other. Reads: `tests/commands/test_ci.py`, `tests/commands/test_ci_repeat.py`, `tests/support/session_spawns.py`, `src/devops_cli/commands/ci.py`. Changes: `tests/commands/test_ci.py`, `tests/commands/test_ci_repeat.py`. -- [ ] 2.1 In `tests/commands/test_ci.py`, update `test_staged_sources_select_the_worktrees_tests` so that its `runs` list drops a child that holds `--collect-only`, because the collection is now the first pytest child. Give `-n 2` to `test_a_test_run_past_its_timeout_fails_naming_its_command_and_timeout` and to the invocation that `_run_recording_handlers` makes, which serves `test_a_run_takes_over_ctrl_c_sigterm_and_sighup_and_hands_them_back`, `test_a_run_off_the_main_thread_sets_no_signal_handler` and `test_an_ignored_hangup_stays_ignored_through_a_run`. Add `-n 2` to the default argv of `_devops_ci_test`, which serves `test_a_signal_to_devops_ci_test_lets_pytest_tear_down_then_stops_its_group` and `test_a_second_signal_to_devops_ci_test_cannot_skip_the_sigkill`, so their fake `uv` is the child that waits for the signal. In `tests/commands/test_ci_repeat.py`, drop a call that holds `--collect-only` from what `_invoke` returns, so `test_the_gate_and_a_plain_run_stay_in_file_order` keeps the one run that it compares +- [x] 2.1 In `tests/commands/test_ci.py`, update `test_staged_sources_select_the_worktrees_tests` so that its `runs` list drops a child that holds `--collect-only`, because the collection is now the first pytest child. Give `-n 2` to `test_a_test_run_past_its_timeout_fails_naming_its_command_and_timeout` and to the invocation that `_run_recording_handlers` makes, which serves `test_a_run_takes_over_ctrl_c_sigterm_and_sighup_and_hands_them_back`, `test_a_run_off_the_main_thread_sets_no_signal_handler` and `test_an_ignored_hangup_stays_ignored_through_a_run`. Add `-n 2` to the default argv of `_devops_ci_test`, which serves `test_a_signal_to_devops_ci_test_lets_pytest_tear_down_then_stops_its_group` and `test_a_second_signal_to_devops_ci_test_cannot_skip_the_sigkill`, so their fake `uv` is the child that waits for the signal. In `tests/commands/test_ci_repeat.py`, drop a call that holds `--collect-only` from what `_invoke` returns, so `test_the_gate_and_a_plain_run_stay_in_file_order` keeps the one run that it compares - Verification: `$ uv run devops ci test tests/commands/test_ci.py tests/commands/test_ci_repeat.py` passes ## 3. Describe the collected-test worker rule in the docs diff --git a/src/devops_cli/commands/ci.py b/src/devops_cli/commands/ci.py index 26319bc688..bb3be7ed90 100644 --- a/src/devops_cli/commands/ci.py +++ b/src/devops_cli/commands/ci.py @@ -52,6 +52,7 @@ DEFAULT_CI_TEST_NARROWED_WORKERS, DEFAULT_CI_TEST_REPEAT_RUNS, DEFAULT_CI_TEST_SERIAL_MAX_FILES, + DEFAULT_CI_TEST_SERIAL_MAX_TESTS, DEFAULT_PYTHON_VERSION, DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, ) @@ -1930,13 +1931,54 @@ def _build_test_cmd( return cmd -def _narrowed_workers(targets: list[str] | None) -> str | None: +def _collection_cmd(targets: list[str], keyword: str | None) -> list[str]: + """The command that collects the tests the run selects: the run's own command, serially and + quiet, with the same targets and `-k` filter, so the count follows what the run would run.""" + return [*_build_test_cmd("0", False, keyword, False, None), "--collect-only", "-q", *targets] + + +def _collected_test_count(targets: list[str], keyword: str | None) -> int | None: + """The number of tests that the selection collects, which chooses the workers; None when a + dry run collects nothing, or when the collection timed out or failed, so that the file count + decides (#4472). pytest's exit 5 is a collection of no test, as a `-k` filter that matches + none gives, and so a count of zero.""" + if is_dry_run(): + return None + cmd = _collection_cmd(targets, keyword) + try: + result = asyncio.run( + _run_in_own_session( + cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None + ) + ) + except subprocess.TimeoutExpired: + reason = f"a timeout after {DEFAULT_SUBPROCESS_TIMEOUT_SECONDS:g}s" + except asyncio.CancelledError: + raise typer.Exit(CONST_EXIT_CANCELLED) from None + else: + if result.returncode == 0: + from devops_cli.roadmap.implement.implement_test_form import collected_items + + return collected_items(result.stdout or "") + if result.returncode == 5: + return 0 + reason = f"exit code {result.returncode}" + print_warning(MESSAGES.ci.test_collection_failed.format(command=shlex.join(cmd), reason=reason)) + return None + + +def _narrowed_workers(targets: list[str] | None, collected: int | None = None) -> str | None: """The `-n` of a run given none (#1669): none for the full suite, so addopts' `-n logical` - applies; serial for a selection of up to DEFAULT_CI_TEST_SERIAL_MAX_FILES test modules, - where each xdist worker's start-up and collection cost more than it saves; and - DEFAULT_CI_TEST_NARROWED_WORKERS workers above that.""" + applies; serial for a selection of no more than DEFAULT_CI_TEST_SERIAL_MAX_TESTS collected + tests, where each xdist worker's start-up and collection cost more than it saves; and + DEFAULT_CI_TEST_NARROWED_WORKERS workers above that. When the collection gave no count, the + number of test modules decides, up to DEFAULT_CI_TEST_SERIAL_MAX_FILES (#4472).""" if targets is None: return None + if collected is not None: + if collected <= DEFAULT_CI_TEST_SERIAL_MAX_TESTS: + return "0" + return str(DEFAULT_CI_TEST_NARROWED_WORKERS) if len(targets) <= DEFAULT_CI_TEST_SERIAL_MAX_FILES: return "0" return str(DEFAULT_CI_TEST_NARROWED_WORKERS) @@ -2017,7 +2059,10 @@ def test( _run_shuffled_repeats(_build_test_cmd("0", verbose, k, x, None), targets, repeat, seed) return - workers = numprocesses if numprocesses is not None else _narrowed_workers(targets) + workers = numprocesses + if workers is None: + collected = _collected_test_count(targets, k) if targets else None + workers = _narrowed_workers(targets, collected) cmd = _build_test_cmd(workers, verbose, k, x, targets) with _gate_slot(workers is None): passed = _run(cmd, own_session=True) diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 2d50dce44a..91083013f6 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -492,6 +492,11 @@ # about the same CPU. A source module selects a median of 3 test modules and a p90 of 12; 90% # select at most 12. DEFAULT_CI_TEST_SERIAL_MAX_FILES: Final[int] = 12 +# The collected tests below which a narrowed run given no `-n` runs serially (#4472): the issue's +# selection of 7 test modules held 399 slow tests, which ran serially past the 1800 s timeout. +# The count is the run's own collection, narrowed by its `-k` filter; the file count above decides +# only when that collection fails. +DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50 DEFAULT_CI_TEST_NARROWED_WORKERS: Final[int] = 4 # `devops ci job-time` (#2699): how many of the last runs of the test job its mean covers. The # issue #3050 states the mean over 20 runs of `main`. diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index 50ee14c949..6a31cbbd6a 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -896,8 +896,9 @@ class CICommandHelp: filter_keyword: str = "Filter tests by keyword expression." stop_fail: str = "Stop after first failure." num_workers: str = ( - "Number of parallel worker processes. Unset, a run narrowed to a few test files runs " - "serially, a larger selection on a few workers, and the full suite on every logical CPU." + "Number of parallel worker processes. Unset, a run narrowed to the tests that it selects " + "runs serially up to 50 collected tests and on a few workers above them, and the full " + "suite on every logical CPU." ) test_paths: str = ( "Source or test files, or directories of src/ or tests/, to verify. Narrows the run to " diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index 9d8b03d2e6..55c5dfa241 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -2116,6 +2116,10 @@ class CIMessages: "supported yet." ) repeat_seed_unavailable: str = "Could not read HEAD to derive a shuffle seed; pass --seed." + test_collection_failed: str = ( + "Could not collect the selected tests, so the workers follow the number of test files: " + "{command} failed with {reason}." + ) run_timed_out: str = ( "{command} ran past its {timeout} timeout and was stopped with every process it started." ) diff --git a/tests/commands/test_ci.py b/tests/commands/test_ci.py index 2c55252dd0..97e2e17016 100644 --- a/tests/commands/test_ci.py +++ b/tests/commands/test_ci.py @@ -1944,7 +1944,11 @@ def test_staged_sources_select_the_worktrees_tests( result = runner.invoke(app, ["test", "src/pkg/widget.py"]) - runs = [call for call in process_fake.calls if "pytest" in call.argv] + runs = [ + call + for call in process_fake.calls + if "pytest" in call.argv and "--collect-only" not in call.argv + ] assert ( result.exit_code, [("tests/test_widget.py" in call.argv, call.cwd) for call in runs], @@ -2532,7 +2536,7 @@ async def outlive_the_timeout(_spawn: RecordedSpawn) -> None: raise TimeoutError spawns = record_spawns(monkeypatch, on_communicate=outlive_the_timeout) - result = runner.invoke(app, ["test", "tests/test_x.py"]) + result = runner.invoke(app, ["test", "-n", "2", "tests/test_x.py"]) timed_out = MESSAGES.ci.run_timed_out.format( command=shlex.join(spawns[0].argv), timeout=f"{DEFAULT_SUBPROCESS_TIMEOUT_SECONDS:g}s" @@ -2565,7 +2569,7 @@ async def record_handlers(_spawn: RecordedSpawn) -> None: raise OSError("the run's output could not be read") record_spawns(monkeypatch, on_communicate=record_handlers) - return runner.invoke(app, ["test", "tests/test_x.py"]).exit_code, during + return runner.invoke(app, ["test", "-n", "2", "tests/test_x.py"]).exit_code, during @pytest.mark.usefixtures("narrowed_project", "default_signal_dispositions") @@ -2624,9 +2628,12 @@ def test_an_ignored_hangup_stays_ignored_through_a_run(monkeypatch: pytest.Monke def _devops_ci_test( - project: Path, fake_uv: Path, log: Path, args: tuple[str, ...] = ("test", "tests/test_x.py") + project: Path, + fake_uv: Path, + log: Path, + args: tuple[str, ...] = ("test", "-n", "2", "tests/test_x.py"), ) -> subprocess.Popen[bytes]: - """`devops ci` with `args`, `test tests/test_x.py` by default, the real command in a process + """`devops ci` with `args`, `test -n 2 tests/test_x.py` by default, the real command in a process of its own, with `fake_uv` first on PATH and telemetry off, so it opens no socket; its output goes to `log`. The tree under test's `src` leads its PYTHONPATH, so it runs that tree's devops-cli, not whichever the console script's install points at, as a replay on another tree diff --git a/tests/commands/test_ci_repeat.py b/tests/commands/test_ci_repeat.py index 7c24ebc7e0..a8c88abde1 100644 --- a/tests/commands/test_ci_repeat.py +++ b/tests/commands/test_ci_repeat.py @@ -68,7 +68,11 @@ async def record_in_session(spawn: RecordedSpawn) -> None: with pytest.MonkeyPatch.context() as monkeypatch: record_spawns(monkeypatch, on_communicate=record_in_session) result = runner.invoke(CI, ["test", *args]) - ran = [(list(call.argv), call.cwd) for call in process_fake.calls] + ran = [ + (list(call.argv), call.cwd) + for call in process_fake.calls + if "--collect-only" not in call.argv + ] return result, [*ran, *spawned] diff --git a/tests/commands/test_test_selection.py b/tests/commands/test_test_selection.py index 3ae5909ad3..7b5b932daa 100644 --- a/tests/commands/test_test_selection.py +++ b/tests/commands/test_test_selection.py @@ -21,6 +21,7 @@ from devops_cli.config.defaults import ( DEFAULT_CI_TEST_NARROWED_WORKERS, DEFAULT_CI_TEST_SERIAL_MAX_FILES, + DEFAULT_CI_TEST_SERIAL_MAX_TESTS, ) from devops_cli.core.coverage_index import CoverageIndex, save_index from devops_cli.core.test_selection import ( @@ -30,7 +31,7 @@ select_tests_for_sources, ) from tests.support.ci_root import tracked_blobs -from tests.support.fakes.process import ProcessFake +from tests.support.fakes.process import ProcessAnswer, ProcessFake from tests.support.paths import REPO_ROOT, TESTS_ROOT from tests.support.session_spawns import RecordedSpawn, record_spawns from tests.support.trees import parse_python_file @@ -39,6 +40,11 @@ runner = CliRunner() +# The option that tells the collection which chooses the workers from the pytest run itself. +_COLLECTION_MARK = "--collect-only" +# The opening words of the warning that a failed collection prints. +_COLLECTION_WARNING = "Could not collect the selected tests" + @pytest.fixture def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: @@ -68,8 +74,27 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: def _pytest_runs(process_fake: ProcessFake) -> list[list[str]]: - """The command line of each pytest run the command started, in order.""" - return [list(call.argv) for call in process_fake.calls if "pytest" in call.argv] + """The command line of each pytest run the command started, in order; the collection that + chooses the workers is no run.""" + return [ + list(call.argv) + for call in process_fake.calls + if "pytest" in call.argv and _COLLECTION_MARK not in call.argv + ] + + +def _collection_calls(process_fake: ProcessFake) -> list[list[str]]: + """The command line of each pytest collection the command started, in order.""" + return [list(call.argv) for call in process_fake.calls if _COLLECTION_MARK in call.argv] + + +def _answer_collection(process_fake: ProcessFake, tests: int, *, returncode: int = 0) -> None: + """Answer the collection with `tests` collected test ids, or with `returncode` and no id.""" + ids = "".join(f"tests/test_selected_{number}.py::test_noop\n" for number in range(tests)) + process_fake.answer( + lambda call: _COLLECTION_MARK in call.argv, + ProcessAnswer(returncode=returncode, stdout=ids if returncode == 0 else ""), + ) # ───────────────────────────────────────────────────────────────────────────── @@ -529,15 +554,21 @@ def _worker_options(argv: list[str]) -> list[list[str]]: return [argv[at : at + 2] for at, arg in enumerate(argv) if arg in ("-n", "--numprocesses")] +def _keyword_options(argv: list[str]) -> list[str]: + """The values of the `-k` options of a command line.""" + return [argv[at + 1] for at, arg in enumerate(argv) if arg == "-k"] + + def _started_runs( monkeypatch: pytest.MonkeyPatch, project: Path, *args: str ) -> tuple[int, list[RecordedSpawn]]: - """`devops ci test ` run from the project, its exit code and the children it started, - doubled at `asyncio.create_subprocess_exec`, so none of them is real.""" + """`devops ci test ` run from the project, its exit code and the pytest children it + started, doubled at `asyncio.create_subprocess_exec`, so none of them is real; the collection + that chooses the workers is no run.""" monkeypatch.chdir(project) spawns = record_spawns(monkeypatch) result = runner.invoke(ci_app, ["test", *args]) - return result.exit_code, spawns + return result.exit_code, [spawn for spawn in spawns if _COLLECTION_MARK not in spawn.argv] def _test_modules(project: Path, count: int) -> list[str]: @@ -569,21 +600,100 @@ def test_a_narrowed_run_chooses_its_workers_and_the_full_suite_keeps_addopts( assert (exit_code, [_worker_options(spawn.argv) for spawn in spawns]) == (0, [workers]) -def test_a_selection_past_the_serial_limit_runs_on_the_capped_workers( - monkeypatch: pytest.MonkeyPatch, project: Path +def test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers( + process_fake: ProcessFake, project: Path ) -> None: - """A selection of up to DEFAULT_CI_TEST_SERIAL_MAX_FILES test modules runs serially, where - starting workers costs more than it saves; one module more runs on - DEFAULT_CI_TEST_NARROWED_WORKERS workers, never on every logical CPU (#1669).""" + """A selection that collects more than DEFAULT_CI_TEST_SERIAL_MAX_TESTS tests runs on + DEFAULT_CI_TEST_NARROWED_WORKERS workers, never on every logical CPU, and one that collects + no more runs serially, where starting workers costs more than it saves; the 13 test modules + of the selection would give the capped workers by the file count alone (#1669, #4472).""" modules = _test_modules(project, DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1) - _code, at_limit = _started_runs(monkeypatch, project, *modules[:-1]) - _code, past_limit = _started_runs(monkeypatch, project, *modules) + _answer_collection(process_fake, DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1) + past_exit_code = runner.invoke(ci_app, ["test", *modules]).exit_code + _answer_collection(process_fake, DEFAULT_CI_TEST_SERIAL_MAX_TESTS) + at_limit_exit_code = runner.invoke(ci_app, ["test", *modules]).exit_code - assert [_worker_options(spawn.argv) for spawn in at_limit + past_limit] == [ - [["-n", "0"]], - [["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]], - ] + assert ( + past_exit_code, + at_limit_exit_code, + [_worker_options(argv) for argv in _pytest_runs(process_fake)], + ) == ( + 0, + 0, + [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]], [["-n", "0"]]], + ) + + +def test_the_collection_repeats_the_targets_and_the_keyword_of_the_run( + process_fake: ProcessFake, project: Path +) -> None: + """The collection collects the same targets and the same `-k` filter as the run, so it counts + the tests the run would collect (#4472).""" + _answer_collection(process_fake, 5) + + result = runner.invoke( + ci_app, ["test", "-k", "slow", "tests/test_secrets.py", "tests/test_unrelated.py"] + ) + + collection = _collection_calls(process_fake)[0] + assert ( + result.exit_code, + _keyword_options(collection), + sorted(arg for arg in collection if arg.startswith("tests/")), + _keyword_options(_pytest_runs(process_fake)[0]), + ) == (0, ["slow"], ["tests/test_secrets.py", "tests/test_unrelated.py"], ["slow"]) + + +def test_a_collection_that_matches_no_test_runs_serially_without_a_warning( + process_fake: ProcessFake, project: Path +) -> None: + """pytest exits 5 when the selection collects no test, as a `-k` filter that matches none + gives; that is a count of zero, so the run is serial and no warning names a failure (#4472).""" + _answer_collection(process_fake, 0, returncode=5) + + result = runner.invoke(ci_app, ["test", "-k", "no-such-test", "tests/test_secrets.py"]) + + assert (result.exit_code, [_worker_options(argv) for argv in _pytest_runs(process_fake)]) == ( + 0, + [[["-n", "0"]]], + ) + assert _COLLECTION_WARNING not in result.output + + +def test_a_failed_collection_falls_back_to_the_file_count_with_a_warning( + process_fake: ProcessFake, project: Path +) -> None: + """A collection that fails prints a warning that names it and keeps the file-count rule: 13 + test modules are more than DEFAULT_CI_TEST_SERIAL_MAX_FILES, so the run takes + DEFAULT_CI_TEST_NARROWED_WORKERS workers, where a count of zero would run serially (#4472).""" + modules = _test_modules(project, DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1) + _answer_collection(process_fake, 0, returncode=3) + + result = runner.invoke(ci_app, ["test", *modules]) + + assert (result.exit_code, [_worker_options(argv) for argv in _pytest_runs(process_fake)]) == ( + 0, + [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]], + ) + assert _COLLECTION_WARNING in " ".join(result.output.split()) + + +@pytest.mark.parametrize( + "args", + [ + pytest.param((), id="full-suite"), + pytest.param(("-n", "2", "tests/test_secrets.py"), id="workers-given"), + ], +) +def test_a_run_that_chooses_its_workers_by_other_means_makes_no_collection( + process_fake: ProcessFake, project: Path, args: tuple[str, ...] +) -> None: + """A run with no paths keeps addopts' `-n logical`, and a given `-n` is kept as it is, so + neither starts a collection (#4472).""" + result = runner.invoke(ci_app, ["test", *args]) + + assert (result.exit_code, _collection_calls(process_fake)) == (0, []) def test_the_test_run_starts_pytest_in_a_session_of_its_own( From 624f26c8b50f0a5b9e69ce4b803acc87cc92fb5e Mon Sep 17 00:00:00 2001 From: "devops-cli-service[bot]" <349441588+devops-cli-service[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:46:01 +0000 Subject: [PATCH 2/5] fix(ci): Describe the collected-test worker rule in the docs (#4472) --- docs/TESTING.md | 2 +- docs/commands/ci.md | 2 +- openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/TESTING.md b/docs/TESTING.md index ce8457bdbd..216be6bf27 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -167,7 +167,7 @@ Every new test follows these rules. Some of them name a path, fixture or check t - `devops ci test ` runs only the tests a change reaches, and so does `devops test run --changed`, over the files changed since the branch left `main`, committed or not. A test module is reached when it is named for a changed module, at any depth, or imports it. A test module that only sits in the directory mirroring the module's package is not reached. - `devops ci test` takes a directory too. A directory of `tests/` runs the test modules (`test_*.py`) inside it at any depth, and not its helper modules. A directory of `src/` selects tests for the Python modules inside it, as for a list of files. It refuses a path that does not exist, a directory that gives no module, and a directory outside `src/` and `tests/`, with exit status 1 and an error that names the path, whatever `--fallback` says. A file that exists and maps to no test, such as `README.md`, still exits 0 with a note, and a trigger file that is gone, such as a deleted `conftest.py`, still forces the full run (#2868). -- Given no `-n`, a narrowed `devops ci test` runs serially for up to `DEFAULT_CI_TEST_SERIAL_MAX_FILES` test modules, where starting xdist workers costs more than it saves, and on `DEFAULT_CI_TEST_NARROWED_WORKERS` workers above that; the full suite, and the fallback to it, run on `addopts`' `-n logical`. A direct `uv run pytest` with `-n logical` or `-n auto` waits for a gate slot in the `pytest_xdist_auto_num_workers` wrapper of the root conftest, and starts at most the CPUs of one slot (#4525). Any run with workers distributes its tests with `addopts`' `--dist worksteal`: a worker that runs out of tests takes half the tests another worker has not started, so a block of slow tests handed to one worker late in the run no longer keeps the others waiting for it. It runs pytest in a session of its own, so a timeout, Ctrl-C, SIGTERM or SIGHUP stops pytest and its workers with `uv`: a timeout with SIGTERM, a signal by first forwarding the SIGINT a terminal would have sent, so pytest runs its teardown, then SIGTERM and SIGKILL, which a second signal brings forward and cannot skip. The run takes over all three signals through `loop.add_signal_handler`, so each one wakes the run's event loop wherever it lands, only cancels the run, and raises no KeyboardInterrupt in the middle of the stop. A test that drives `devops ci test` doubles `asyncio.create_subprocess_exec` with `record_spawns` from `tests/support/session_spawns.py`, and asks for `refuse_nested_test_runs`, which fails any real `uv` or pytest it would start. +- Given no `-n`, a narrowed `devops ci test` collects the tests that it selects before it starts them. The collection command is `uv run pytest -n 0 --collect-only -q`, with the same target list and `-k` filter as the run. The run is serial, `-n 0`, for up to `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` (50) collected tests, where the start-up of xdist workers costs more than it saves. It runs on `DEFAULT_CI_TEST_NARROWED_WORKERS` workers above that. The `-k` filter changes the count, so a selection of 399 tests that `-k slow` narrows to 5 runs serially. A collection that exits 5, the exit pytest gives when no test matches, is a count of zero. That run is serial and prints no warning. A collection that fails or times out prints a warning that names the command and the reason, and the number of test modules then decides. Up to `DEFAULT_CI_TEST_SERIAL_MAX_FILES` (12) modules run serially, and more run on `DEFAULT_CI_TEST_NARROWED_WORKERS` workers, so a failed collection over 13 target files runs on 4 workers. A given `-n`, a run with no paths, a dry run and a `--repeat` run make no collection call and keep their worker choice. The full suite, and the fallback to it, run on `addopts`' `-n logical`. A direct `uv run pytest` with `-n logical` or `-n auto` waits for a gate slot in the `pytest_xdist_auto_num_workers` wrapper of the root conftest, and starts at most the CPUs of one slot (#4525). Any run with workers distributes its tests with `addopts`' `--dist worksteal`: a worker that runs out of tests takes half the tests another worker has not started, so a block of slow tests handed to one worker late in the run no longer keeps the others waiting for it. It runs pytest in a session of its own, so a timeout, Ctrl-C, SIGTERM or SIGHUP stops pytest and its workers with `uv`: a timeout with SIGTERM, a signal by first forwarding the SIGINT a terminal would have sent, so pytest runs its teardown, then SIGTERM and SIGKILL, which a second signal brings forward and cannot skip. The run takes over all three signals through `loop.add_signal_handler`, so each one wakes the run's event loop wherever it lands, only cancels the run, and raises no KeyboardInterrupt in the middle of the stop. A test that drives `devops ci test` doubles `asyncio.create_subprocess_exec` with `record_spawns` from `tests/support/session_spawns.py`, and asks for `refuse_nested_test_runs`, which fails any real `uv` or pytest it would start. The collection starts through that same edge, so a test that answers the run answers the collection too. A helper that reads the pytest run skips the child that holds `--collect-only`. - A test module that replays a shared set computes the replay once in a module-scoped fixture and gives each case its own parametrized item, so a narrowed run stays inside the budget and xdist can distribute the cases. - With a fresh coverage index (`devops ci coverage --build-index`), `devops ci test` selects the test modules that executed each changed module the index holds, in place of name-and-import matching. A module the index does not hold, a missing or stale index, and `devops test run --changed` select by name and import. So a test that should run for a module executes the module's code inside the test, not only on import, and names the module or imports it. - A change that can alter tests that never import it runs the whole suite: `conftest.py`, `pyproject.toml`, `uv.lock`, `.python-version`, and a helper module under `tests/` that reaches every test, as the next rule says. `devops ci test`, and so the commit hook, runs the whole suite for any `conftest.py` it is given, at any depth, and under `--no-fallback` refuses any of these files instead. `devops test run --changed` narrows a conftest below `tests/`: one that only defines fixtures selects its own directory, and one that binds a `pytest_*` hook, which pytest calls for every test, selects the whole suite. diff --git a/docs/commands/ci.md b/docs/commands/ci.md index 5e9ab652e6..1bf843efce 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -48,7 +48,7 @@ devops ci test [OPTIONS] | `--verbose`, `-v` | `boolean` | - | Enable detailed logging output. | | `-k` | `string` | - | Filter tests by keyword expression. | | `-x` | `boolean` | - | Stop after first failure. | -| `-n`, `--numprocesses` | `string` | - | Number of parallel worker processes. Unset, a run narrowed to a few test files runs serially, a larger selection on a few workers, and the full suite on every logical CPU. | +| `-n`, `--numprocesses` | `string` | - | Number of parallel worker processes. Unset, a run narrowed to the tests that it selects runs serially up to 50 collected tests and on a few workers above them, and the full suite on every logical CPU. | | `--fallback` / `--no-fallback` | `boolean` | `True` | Run the full suite when a changed source has no covering tests, rather than reporting success without verifying it. | | `--repeat` | `integer` | `0` | Run the selected test files N times, one run after another on one process (-n is ignored), each in a shuffled order, with seeds counting up from --seed. 0 runs them once in file order. Refuses the whole suite. | | `--seed` | `integer` | - | First shuffle seed for --repeat. Defaults to one derived from HEAD's commit hash; has no effect without --repeat. | diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md index 7167be4b94..23dc440881 100644 --- a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md +++ b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md @@ -20,9 +20,9 @@ Kind: other. Reads: `tests/commands/test_ci.py`, `tests/commands/test_ci_repeat. Kind: other. Reads: `docs/TESTING.md`, `docs/commands/ci.md`, `src/devops_cli/lang/en/help.py`. Changes: `docs/TESTING.md`, `docs/commands/ci.md`. -- [ ] 3.1 Replace the file-count sentence of `docs/TESTING.md` with the collected-test rule: the collection command, the threshold of 50 collected tests, the `-k` filter, an empty collection, the fallback on a failure with its 13-file example, and the runs that make no collection call. State that a test that drives the command answers the collection through the process edge it already doubles. Then regenerate the command pages with `uv run devops docs generate`, which rewrites `docs/commands/ci.md` from the changed help text +- [x] 3.1 Replace the file-count sentence of `docs/TESTING.md` with the collected-test rule: the collection command, the threshold of 50 collected tests, the `-k` filter, an empty collection, the fallback on a failure with its 13-file example, and the runs that make no collection call. State that a test that drives the command answers the collection through the process edge it already doubles. Then regenerate the command pages with `uv run devops docs generate`, which rewrites `docs/commands/ci.md` from the changed help text - Verification: `$ uv run devops ci docs` passes -- [ ] 3.2 Edit `docs/TESTING.md` and regenerate `docs/commands/ci.md` with `uv run devops docs generate` +- [x] 3.2 Edit `docs/TESTING.md` and regenerate `docs/commands/ci.md` with `uv run devops docs generate` - Verification: `$ uv run devops ci docs` passes ## Workflow follow-up From e3104c364ecb75d8273649960bd7badff36ca0ee Mon Sep 17 00:00:00 2001 From: "devops-cli-service[bot]" <349441588+devops-cli-service[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:08:17 +0000 Subject: [PATCH 3/5] fix(ci): Make check Tests & Coverage pass (#4472) --- tests/commands/test_test_selection.py | 57 +++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/commands/test_test_selection.py b/tests/commands/test_test_selection.py index 7b5b932daa..01b2892b45 100644 --- a/tests/commands/test_test_selection.py +++ b/tests/commands/test_test_selection.py @@ -3,6 +3,7 @@ from __future__ import annotations import ast +import asyncio from pathlib import Path from typing import NoReturn @@ -15,6 +16,7 @@ from devops_cli.config.constants import ( CONST_CI_SLOWEST_TESTS_SHOWN, CONST_CONFTEST_FILENAME, + CONST_EXIT_CANCELLED, CONST_FULL_RUN_TRIGGER_NAMES, CONST_TESTS_ROOT_DIR, ) @@ -679,6 +681,61 @@ def test_a_failed_collection_falls_back_to_the_file_count_with_a_warning( assert _COLLECTION_WARNING in " ".join(result.output.split()) +def test_a_collection_that_times_out_falls_back_to_the_file_count_with_a_warning( + monkeypatch: pytest.MonkeyPatch, project: Path +) -> None: + """A collection that outlives its timeout prints a warning that names it and keeps the + file-count rule, so the run still starts: 13 test modules take + DEFAULT_CI_TEST_NARROWED_WORKERS workers, where a count of zero would run serially (#4472).""" + modules = _test_modules(project, DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1) + + async def outlive_the_timeout(spawn: RecordedSpawn) -> None: + if _COLLECTION_MARK in spawn.argv: + raise TimeoutError + + monkeypatch.chdir(project) + spawns = record_spawns(monkeypatch, on_communicate=outlive_the_timeout) + result = runner.invoke(ci_app, ["test", *modules]) + + runs = [spawn for spawn in spawns if _COLLECTION_MARK not in spawn.argv] + assert (result.exit_code, [_worker_options(spawn.argv) for spawn in runs]) == ( + 0, + [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]], + ) + assert _COLLECTION_WARNING in " ".join(result.output.split()) + + +def test_a_collection_cancelled_by_a_stop_signal_exits_as_cancelled( + monkeypatch: pytest.MonkeyPatch, project: Path +) -> None: + """Ctrl-C, SIGTERM or SIGHUP during the collection exits as cancelled, as it does during the + run, so a stopped collection is no failed collection that falls back (#4472).""" + + async def cancel_the_collection(spawn: RecordedSpawn) -> None: + if _COLLECTION_MARK in spawn.argv: + raise asyncio.CancelledError + + monkeypatch.chdir(project) + spawns = record_spawns(monkeypatch, on_communicate=cancel_the_collection) + result = runner.invoke(ci_app, ["test", "src/devops_cli/security/secrets.py"]) + + assert (result.exit_code, [_COLLECTION_MARK in spawn.argv for spawn in spawns]) == ( + CONST_EXIT_CANCELLED, + [True], + ) + + +def test_a_dry_run_plans_the_workers_without_collecting( + process_fake: ProcessFake, project: Path +) -> None: + """A dry run starts no child, so it cannot count the collected tests: it plans the run with + the worker count that the file count gives and starts no collection (#4472).""" + result = runner.invoke(ci_app, ["test", "--dry-run", "src/devops_cli/security/secrets.py"]) + + assert (result.exit_code, _collection_calls(process_fake)) == (0, []) + assert "pytest -n 0" in " ".join(result.stdout.split()) + + @pytest.mark.parametrize( "args", [ From ec8d84461806901d06dc299ff33bfc1818e691c1 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 01:42:30 +0000 Subject: [PATCH 4/5] fix(ci): Prove the collected-test worker rule on the base (#4472) The test module imported DEFAULT_CI_TEST_SERIAL_MAX_TESTS at module level. That name is not on the base, so the Fail-to-Pass replay could not collect the module and no case of it ran there. The boundary case now reads the limit from the defaults module in its body. A new case runs the selection of the issue, 7 test modules that collect 399 tests. The file count gives it -n 0 on the base, and the head gives it the capped workers. --- .../design.md | 1 + .../tasks.md | 4 +-- tests/commands/test_test_selection.py | 33 ++++++++++++++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md b/openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md index 7b8169b269..3f6b0115e6 100644 --- a/openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md +++ b/openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md @@ -8,6 +8,7 @@ - **Start the collection through `_run_in_own_session`, the runner the run itself uses.**: One edge starts both children, the process runner seam answers both in the tests, and `tests/support/session_spawns.py:def record_spawns` doubles the same start. - **Give the collection-failure case 13 target files, more than `DEFAULT_CI_TEST_SERIAL_MAX_FILES`.**: `src/devops_cli/commands/ci.py:1940:if len(targets) <= DEFAULT_CI_TEST_SERIAL_MAX_FILES:` gives `-n 0` at 12 files or fewer, so a 7-file case cannot tell the file-count fallback from a count of zero; at 13 files the fallback gives `-n 4` and the test asserts the rule that ran. - **Treat pytest's exit code 5 as a count of zero and as no collection failure.**: A `-k` filter that matches no test is no failure of the collection, so the command runs `-n 0` with no warning; the fallback scenario names exit code 3, so no test reads two answers from one exit code. +- **Prove the fix with the selection of the issue, and read the new limit from the `defaults` module in the body of a test.**: `devops ci fail-to-pass` replays the changed tests on the base, and only a test that fails in its call phase proves the fix. A module-level import of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` stops the collection of `tests/commands/test_test_selection.py` on the base, so no case of the module runs there. The 13-file cases get `-n 4` from the file count on the base too. The case of 7 test modules that collect 399 tests shows the defect, because the base gives it `-n 0`. - **Skip a child that holds `--collect-only` in the test helpers that read the pytest run.**: `tests/commands/test_test_selection.py:70:def _pytest_runs(process_fake: ProcessFake) -> list[list[str]]:` and `tests/commands/test_ci.py:1947:runs = [call for call in process_fake.calls if "pytest" in call.argv]` take the first pytest child as the run, and the collection is now the first one. - **Give `-n 2` to the tests that read the run's own child.**: A given `-n` makes no collection call, so the helpers `_run_recording_handlers` and `_devops_ci_test` and the timeout case keep the child they signal, time out and record. - **Make no collection call in a dry run.**: A dry run renders the planned command and starts nothing, so a collection there would answer with a plan and no count. diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md index 23dc440881..cfcff4b595 100644 --- a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md +++ b/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md @@ -4,9 +4,9 @@ Kind: behavior. Reads: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/lang/en/help.py`, `src/devops_cli/roadmap/implement/implement_test_form.py`, `tests/commands/test_test_selection.py`, `tests/support/fakes/process.py`, `tests/support/session_spawns.py`. Changes: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/lang/en/messages.py`, `src/devops_cli/lang/en/help.py`, `tests/commands/test_test_selection.py`. -- [x] 1.1 Add the failing case `tests/commands/test_test_selection.py::test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers` and replace `tests/commands/test_test_selection.py::test_a_selection_past_the_serial_limit_runs_on_the_capped_workers` with it, because the file count no longer decides alone +- [x] 1.1 Add the failing case `tests/commands/test_test_selection.py::test_a_few_test_modules_that_collect_many_tests_run_on_the_capped_workers`, the selection of the issue: 7 test modules whose collection answers 399 test ids run on `DEFAULT_CI_TEST_NARROWED_WORKERS`, where the file count gives `-n 0`. Add the failing case `tests/commands/test_test_selection.py::test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers` and replace `tests/commands/test_test_selection.py::test_a_selection_past_the_serial_limit_runs_on_the_capped_workers` with it, because the file count no longer decides alone - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` fails on the base -- [x] 1.2 Write the failing cases first in `tests/commands/test_test_selection.py`: import `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` and `ProcessAnswer`, make `_pytest_runs` and `_started_runs` skip a child that holds `--collect-only`, and answer the collection with `process_fake.answer` and a matcher on `--collect-only` whose `ProcessAnswer` stdout holds one test id on each line. A collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1` ids runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`; a collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` ids runs serially; a collection that exits 5 runs serially and prints no warning; a collection that exits 3 over 13 target files prints the warning and runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`, because the file-count rule gives 4 workers above 12 files while a count of zero gives `-n 0`; a `-k slow` selection passes `-k slow` to the collection and to the run; a given `-n` and a run with no paths make no collection call. Then add `DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50` beside the file-count constant with a comment that states the rule, add the collection-failure warning to the CI messages beside `repeat_seed_unavailable`, and rewrite the `-n` help text to say that the collected tests choose the workers. Add `_collection_cmd(targets, keyword)`, which returns `[*_build_test_cmd("0", False, keyword, False, None), "--collect-only", "-q", *targets]`, and `_collected_test_count(targets, keyword)`, which returns None in a dry run, starts the command with `asyncio.run(_run_in_own_session(cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None))`, returns 0 on exit 5, returns None with the warning on `subprocess.TimeoutExpired` or any other non-zero exit, re-raises `asyncio.CancelledError` as `typer.Exit(CONST_EXIT_CANCELLED)`, and otherwise returns `collected_items(stdout)`. Give `_narrowed_workers(targets, collected)` the collected count and keep the count of test modules for the None case +- [x] 1.2 Write the failing cases first in `tests/commands/test_test_selection.py`: import `ProcessAnswer` and the `devops_cli.config.defaults` module, and read `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` from that module in the body of the test, so that the module imports on the base and its cases fail there in their call phase, make `_pytest_runs` and `_started_runs` skip a child that holds `--collect-only`, and answer the collection with `process_fake.answer` and a matcher on `--collect-only` whose `ProcessAnswer` stdout holds one test id on each line. A collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1` ids runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`; a collection of `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` ids runs serially; a collection that exits 5 runs serially and prints no warning; a collection that exits 3 over 13 target files prints the warning and runs on `DEFAULT_CI_TEST_NARROWED_WORKERS`, because the file-count rule gives 4 workers above 12 files while a count of zero gives `-n 0`; a `-k slow` selection passes `-k slow` to the collection and to the run; a given `-n` and a run with no paths make no collection call. Then add `DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50` beside the file-count constant with a comment that states the rule, add the collection-failure warning to the CI messages beside `repeat_seed_unavailable`, and rewrite the `-n` help text to say that the collected tests choose the workers. Add `_collection_cmd(targets, keyword)`, which returns `[*_build_test_cmd("0", False, keyword, False, None), "--collect-only", "-q", *targets]`, and `_collected_test_count(targets, keyword)`, which returns None in a dry run, starts the command with `asyncio.run(_run_in_own_session(cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None))`, returns 0 on exit 5, returns None with the warning on `subprocess.TimeoutExpired` or any other non-zero exit, re-raises `asyncio.CancelledError` as `typer.Exit(CONST_EXIT_CANCELLED)`, and otherwise returns `collected_items(stdout)`. Give `_narrowed_workers(targets, collected)` the collected count and keep the count of test modules for the None case - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` passes ## 2. Skip the collection in the tests that read the pytest run diff --git a/tests/commands/test_test_selection.py b/tests/commands/test_test_selection.py index 01b2892b45..19f928c7f8 100644 --- a/tests/commands/test_test_selection.py +++ b/tests/commands/test_test_selection.py @@ -13,6 +13,7 @@ from devops_cli.ci.cache import resolve_coverage_index_path from devops_cli.commands.ci import app as ci_app from devops_cli.commands.ci import get_check_spec +from devops_cli.config import defaults from devops_cli.config.constants import ( CONST_CI_SLOWEST_TESTS_SHOWN, CONST_CONFTEST_FILENAME, @@ -23,7 +24,6 @@ from devops_cli.config.defaults import ( DEFAULT_CI_TEST_NARROWED_WORKERS, DEFAULT_CI_TEST_SERIAL_MAX_FILES, - DEFAULT_CI_TEST_SERIAL_MAX_TESTS, ) from devops_cli.core.coverage_index import CoverageIndex, save_index from devops_cli.core.test_selection import ( @@ -46,6 +46,10 @@ _COLLECTION_MARK = "--collect-only" # The opening words of the warning that a failed collection prints. _COLLECTION_WARNING = "Could not collect the selected tests" +# The selection of #4472: 7 test modules that held 399 slow tests and ran serially past the +# 1800 s timeout of `devops ci test`. +_ISSUE_TEST_MODULES = 7 +_ISSUE_COLLECTED_TESTS = 399 @pytest.fixture @@ -602,18 +606,39 @@ def test_a_narrowed_run_chooses_its_workers_and_the_full_suite_keeps_addopts( assert (exit_code, [_worker_options(spawn.argv) for spawn in spawns]) == (0, [workers]) +def test_a_few_test_modules_that_collect_many_tests_run_on_the_capped_workers( + process_fake: ProcessFake, project: Path +) -> None: + """The selection of the issue, 7 test modules that collect 399 tests, runs on + DEFAULT_CI_TEST_NARROWED_WORKERS workers. 7 modules are no more than + DEFAULT_CI_TEST_SERIAL_MAX_FILES, so the file count alone ran them serially, past the + 1800 s timeout of the command (#4472).""" + modules = _test_modules(project, _ISSUE_TEST_MODULES) + _answer_collection(process_fake, _ISSUE_COLLECTED_TESTS) + + result = runner.invoke(ci_app, ["test", *modules]) + + assert (result.exit_code, [_worker_options(argv) for argv in _pytest_runs(process_fake)]) == ( + 0, + [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]], + ) + + def test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers( process_fake: ProcessFake, project: Path ) -> None: """A selection that collects more than DEFAULT_CI_TEST_SERIAL_MAX_TESTS tests runs on DEFAULT_CI_TEST_NARROWED_WORKERS workers, never on every logical CPU, and one that collects no more runs serially, where starting workers costs more than it saves; the 13 test modules - of the selection would give the capped workers by the file count alone (#1669, #4472).""" + of the selection would give the capped workers by the file count alone (#1669, #4472). The + test reads the limit through `defaults` when it runs, so this module also imports on a base + that does not have the limit.""" + serial_max_tests = defaults.DEFAULT_CI_TEST_SERIAL_MAX_TESTS modules = _test_modules(project, DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1) - _answer_collection(process_fake, DEFAULT_CI_TEST_SERIAL_MAX_TESTS + 1) + _answer_collection(process_fake, serial_max_tests + 1) past_exit_code = runner.invoke(ci_app, ["test", *modules]).exit_code - _answer_collection(process_fake, DEFAULT_CI_TEST_SERIAL_MAX_TESTS) + _answer_collection(process_fake, serial_max_tests) at_limit_exit_code = runner.invoke(ci_app, ["test", *modules]).exit_code assert ( From 665a80b9bb86722129d95c19d7c539c7420dcf94 Mon Sep 17 00:00:00 2001 From: "devops-cli-service[bot]" <349441588+devops-cli-service[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:46:16 +0000 Subject: [PATCH 5/5] docs(openspec): archive the change (#4472) --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/ci-test-workers/spec.md | 0 .../tasks.md | 0 openspec/specs/ci-test-workers/spec.md | 59 +++++++++++++++++++ 6 files changed, 59 insertions(+) rename openspec/changes/{4472-a-narrowed-ci-test-runs-many => archive/2026-11-13-4472-a-narrowed-ci-test-runs-many}/.openspec.yaml (100%) rename openspec/changes/{4472-a-narrowed-ci-test-runs-many => archive/2026-11-13-4472-a-narrowed-ci-test-runs-many}/design.md (100%) rename openspec/changes/{4472-a-narrowed-ci-test-runs-many => archive/2026-11-13-4472-a-narrowed-ci-test-runs-many}/proposal.md (100%) rename openspec/changes/{4472-a-narrowed-ci-test-runs-many => archive/2026-11-13-4472-a-narrowed-ci-test-runs-many}/specs/ci-test-workers/spec.md (100%) rename openspec/changes/{4472-a-narrowed-ci-test-runs-many => archive/2026-11-13-4472-a-narrowed-ci-test-runs-many}/tasks.md (100%) create mode 100644 openspec/specs/ci-test-workers/spec.md diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/.openspec.yaml b/openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/.openspec.yaml similarity index 100% rename from openspec/changes/4472-a-narrowed-ci-test-runs-many/.openspec.yaml rename to openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/.openspec.yaml diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md b/openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/design.md similarity index 100% rename from openspec/changes/4472-a-narrowed-ci-test-runs-many/design.md rename to openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/design.md diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/proposal.md b/openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/proposal.md similarity index 100% rename from openspec/changes/4472-a-narrowed-ci-test-runs-many/proposal.md rename to openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/proposal.md diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/specs/ci-test-workers/spec.md b/openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/specs/ci-test-workers/spec.md similarity index 100% rename from openspec/changes/4472-a-narrowed-ci-test-runs-many/specs/ci-test-workers/spec.md rename to openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/specs/ci-test-workers/spec.md diff --git a/openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md b/openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/tasks.md similarity index 100% rename from openspec/changes/4472-a-narrowed-ci-test-runs-many/tasks.md rename to openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/tasks.md diff --git a/openspec/specs/ci-test-workers/spec.md b/openspec/specs/ci-test-workers/spec.md new file mode 100644 index 0000000000..276e1015a1 --- /dev/null +++ b/openspec/specs/ci-test-workers/spec.md @@ -0,0 +1,59 @@ +# ci-test-workers Specification + +## Purpose +How `devops ci test` chooses the number of pytest workers for a run that given paths narrow, so that a selection of many slow tests runs in parallel and a tiny selection stays serial. + +## Requirements + +### Requirement: Collected tests choose the workers +`devops ci test` SHALL choose the worker count of a run given no `-n` from the number of tests that the selection collects, not from the number of files. + +#### Scenario: Many tests in few files +- **WHEN** The selected files collect more than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` tests and the caller gives no `-n`. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS`. + +### Requirement: Small selections stay serial +`devops ci test` SHALL run pytest with `-n 0` when the selection collects no more than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` tests. + +#### Scenario: Few collected tests +- **WHEN** The selected files collect 12 tests and the caller gives no `-n`. +- **THEN** The command runs pytest with `-n 0`. + +### Requirement: Keyword filter changes the count +The worker decision SHALL count only the tests that match the `-k` filter. + +#### Scenario: Keyword filter leaves few tests +- **WHEN** The selected files collect 399 tests and `-k` matches 5 tests. +- **THEN** The command runs pytest with `-n 0`. + +### Requirement: Collection uses the run selection +The command MUST collect tests with the same target list and keyword filter that it passes to pytest. + +#### Scenario: Collection command arguments +- **WHEN** The caller passes two test files and `-k slow`. +- **THEN** The collection command holds both file paths and `-k slow`. + +### Requirement: Collection failure falls back +When pytest collection fails or times out, the command SHALL fall back to the file-count rule and continue. An exit code 5, which says that no test was collected, is a count of zero and no failure. + +#### Scenario: Collection error above the file bound +- **WHEN** The collection command exits with code 3 for a selection of 13 test files. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` from the file-count rule and prints a warning that names the collection failure. + +#### Scenario: No test matches the filter +- **WHEN** The collection command exits with code 5 for the selection. +- **THEN** The command runs pytest with `-n 0` and prints no collection warning. + +### Requirement: Explicit workers win +An explicit `-n` value from the caller MUST override the automatic worker count. + +#### Scenario: Explicit worker count +- **WHEN** The caller passes `-n 2` for a selection of 399 tests. +- **THEN** The command runs pytest with `-n 2` and makes no collection call. + +### Requirement: Full suite keeps addopts +A run with no paths SHALL pass no `-n` value, so `addopts` applies. + +#### Scenario: Full suite run +- **WHEN** The caller passes no paths. +- **THEN** The command runs pytest with no `-n` option and makes no collection call.