From e811a118f26452937c654a10c61484ddf81c80b3 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 03:29:42 +0000 Subject: [PATCH 1/3] fix(ci): bound the narrowed test workers and their collection The collection that counts the tests of a narrowed `devops ci test` run exited 1 when a selected module had snapshots, because a collection runs no test and syrupy found each snapshot unused. The run then went back to the file count, so the 7 modules of #4472 still ran with `-n 0`. The collection now gives `--snapshot-warn-unused`. The run gave an explicit `-n 4`, which skips `PYTEST_XDIST_AUTO_NUM_WORKERS`, so a runner pod with 1 CPU ran 4 workers. The run now starts at most the value of that variable, and a bound of 1 runs serially with no collection. More than 50 target modules with no `-k` filter also make no collection. The collection has its own timeout of 120 s, and its warning prints as text. On 1 CPU, a narrowed run of a 52-test module took 37 s before and 8 s after. --- docs/TESTING.md | 2 +- docs/commands/ci.md | 2 +- .../.openspec.yaml | 2 + .../design.md | 49 +++++ .../proposal.md | 52 +++++ .../specs/ci-test-workers/spec.md | 70 +++++++ .../tasks.md | 28 +++ .../devops_cli/tasks/ci_quality_gate.md | 2 +- src/devops_cli/commands/ci.py | 77 +++++-- src/devops_cli/config/defaults.py | 12 +- src/devops_cli/lang/en/help.py | 4 +- tests/commands/test_test_selection.py | 189 ++++++++++++++++-- 12 files changed, 445 insertions(+), 44 deletions(-) create mode 100644 openspec/changes/5606-narrowed-test-workers-fall-back-and/.openspec.yaml create mode 100644 openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md create mode 100644 openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md create mode 100644 openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md create mode 100644 openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md diff --git a/docs/TESTING.md b/docs/TESTING.md index ff23c92d90..0c9dae6504 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` 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`. +- 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 --snapshot-warn-unused`, with the same target list and `-k` filter as the run. A collection runs no test, so syrupy finds each snapshot of a selected module unused, and without `--snapshot-warn-unused` it exits 1. 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. Above that, it runs on the worker cap: `DEFAULT_CI_TEST_NARROWED_WORKERS` (4) workers, or the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` when it is smaller. A runner pod sets that variable to its CPU limit, and xdist reads it only for `-n auto` and `-n logical`, so the command applies it to the explicit `-n` of the run. The collection is a second pytest session, and pytest start-up is most of its time (6 to 8 s for 1 module on an idle host, 23 to 47 s for a narrowed selection at a high load). So the command starts it only when its count can change the worker count. A cap of 1 worker or less runs serially with no collection. More than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` target modules with no `-k` filter run on the cap with no collection, because each module collects one test at least. 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 that runs past `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` (120 s), prints a warning that names the command and the reason as text, and the number of test modules then decides. Up to `DEFAULT_CI_TEST_SERIAL_MAX_FILES` (12) modules run serially, and more run on the worker cap, 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 1bf843efce..f20db0896c 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 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. | +| `-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, never more than PYTEST_XDIST_AUTO_NUM_WORKERS, 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/5606-narrowed-test-workers-fall-back-and/.openspec.yaml b/openspec/changes/5606-narrowed-test-workers-fall-back-and/.openspec.yaml new file mode 100644 index 0000000000..be831cee61 --- /dev/null +++ b/openspec/changes/5606-narrowed-test-workers-fall-back-and/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-14 diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md b/openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md new file mode 100644 index 0000000000..b3130e55f8 --- /dev/null +++ b/openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md @@ -0,0 +1,49 @@ +# Design + +## Decisions + +- **Give the collection `--snapshot-warn-unused`, through one module constant `_SNAPSHOT_WARN_UNUSED` that the shard command also uses.**: A collection runs no test, so syrupy finds each snapshot of a selected module unused and exits 1. The shard rows already give the same option for the same reason (a shard leaves the snapshots of other shards unused), and one constant keeps the two the same. +- **Model syrupy in the fake answer, not only the argv.**: `_answer_collection_with_unused_snapshots` exits 1 when the collection argv lacks the option and 0 when it has it, with the 422 test ids in both outputs, as the real run printed. So the case fails when the option goes away, and it shows the result that the person sees: the workers and no warning. +- **Bound the workers with `PYTEST_XDIST_AUTO_NUM_WORKERS` in `_worker_cap`, as `min(DEFAULT_CI_TEST_NARROWED_WORKERS, value)`.**: A runner pod sets the variable to its CPU limit, because xdist counts the CPUs of the node (#2806). xdist reads it only for `-n auto` and `-n logical`, and the narrowed run gives an explicit `-n`. The function ignores a value that `int()` refuses, as `pytest_xdist_auto_num_workers` of xdist does. +- **Read the name of the variable from `WORKERS_VARIABLE` of `src/devops_cli/roadmap/implement/implement_size.py`, imported in the function body.**: The Service sets the variable from that name, and the gate check `tests/gate/k8s_checks/job_admission_policy.py` imports it from there. The function body already imports `collected_items` from the roadmap package in the same way, so the startup imports of `devops ci` do not change. +- **Run serially with no collection when the cap is 1 or less.**: `-n 1` starts one xdist worker, which costs a start-up and runs no test in parallel, and the collection cannot change a serial answer. A value of 0 is the serial run that xdist gives for 0. +- **Run on the cap with no collection when more than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` target modules have no `-k` filter.**: Each target module collects one test at least, so the count is above the limit and the collection cannot change the answer. A change to a shared source module selects many test modules, and its collection is the largest: the whole suite took 55 s to collect. A `-k` filter can leave fewer tests, so a selection with a filter still collects. +- **Keep the collection for all other selections, and keep the limit of 50 tests.**: The issue asks to bound the collection, not to remove it. Up to 50 target modules can collect more than 50 tests, as the 7 modules of #4472 collect 422, and only the collection finds that. +- **Set `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` to 120 s.**: The start-up of pytest is most of the time of a collection: pytest reported 0.31 s to 1.03 s of collection for the 7 modules of #4472, in sessions of 7.1 s and 21.6 s. Measured wall time on 16 CPUs: 6.2 s to 7.9 s for 1 module, 7.1 s for the 7 modules at a load of 6, 21.6 s for the 7 modules with a cold cache, 55 s for the whole suite, and 23 s to 47 s for a narrowed selection at a high load (the vet of #5606). 120 s is above 2.5 times the slowest narrowed sample and far below the 1800 s timeout of the run, so the inner limit fires first and the run continues on the file count. +- **Print the warning of a failed collection with `safe=True`.**: The warning holds the command, with the targets and the `-k` value. Without `safe=True`, Rich reads `[/x]` as a closing tag and raises `MarkupError`, and reads `[bold]` as a style and hides it. +- **Put the 12-module boundary back as a parametrized case of the fallback, with 12 and 13 modules.**: The file count decides only when the collection gives no count, so the boundary of `DEFAULT_CI_TEST_SERIAL_MAX_FILES` is a property of the fallback. The case that #5547 deleted asserted the same 12 and 13. +- **Add a `--repeat` case to the cases that make no collection.**: `_run_shuffled_repeats` returns before the worker choice, and the case keeps that order. +- **Remove `PYTEST_XDIST_AUTO_NUM_WORKERS` for each test of `tests/commands/test_test_selection.py` with the fixture `no_worker_bound`, which `pytestmark` names.**: A runner Job sets the variable, and the tests of this module run in that Job when a change selects them. Without the fixture, a Job with 1 CPU gives `-n 0` and no collection, and the cases that expect the cap or a collection fail. The fixture is local to the module, so the hermetic floor and the other tests do not change. +- **Read `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` through the `defaults` module in the body of the timeout case.**: `devops ci fail-to-pass` replays the changed tests on the base. A module-level import of the new constant stops the collection of the module on the base, and no case runs there. + +## Measurements + +The narrowed run of one 52-test module, `uv run devops ci test tests/roadmap/test_roadmap_claim.py`, end to end, on this host (16 CPUs, load 0.4 to 2.7, two runs each): + +| Run | Before (`origin/main` b15faabb7) | After (this change) | +| --- | --- | --- | +| 1 CPU (`taskset -c 3`), `PYTEST_XDIST_AUTO_NUM_WORKERS=1` | 37.2 s, 37.7 s: collection, then `-n 4` | 8.6 s, 8.4 s: `-n 0`, no collection | +| 16 CPUs, variable not set | 20.6 s, 20.9 s: collection, then `-n 4` | 22.3 s, 21.9 s: collection, then `-n 4` | + +For reference, `-n 0` of the same module took 7.9 s and 8.4 s on 1 CPU, and 8.4 s and 8.8 s on 16 CPUs. The 52 tests ran in 0.3 s serially, and in 6.9 s to 7.7 s on 4 workers, so a pytest start-up of 6 s to 8 s is most of each session. + +The selection of #4472, `uv run devops ci test` with its 7 modules, ran on this change with no collection warning and exited 0: `4 workers [422 items]`, `422 passed in 62.53s`, 78 s end to end, at a load of 6. Its collection alone, `uv run pytest -n 0 --collect-only -q --snapshot-warn-unused` with the 7 modules, exited 0 with `422 tests collected` in 7.1 s. + +The scoped run of this change, `uv run devops ci test` with the 3 changed source files and the changed test module, selected 166 test modules: it made no collection and ran `4 workers [5834 items]`, `5834 passed in 175.16s`, 185 s end to end. + +## Rejected alternatives + +- **Accept exit 1 of the collection when its output holds test ids.**: Exit 1 is pytest's `TESTS_FAILED`, which any plugin can set through the session status, and syrupy is only one of them. The code does not name the cause, so the command cannot tell a syrupy exit from a real failure. `--snapshot-warn-unused` removes the cause. +- **Run the collection with `-p no:syrupy`.**: The run itself loads syrupy. The design of #4472 makes the collection the run's own command, so that the count follows the run, and a second form of the command can drift from it. +- **Give the run `-n auto` or `-n logical` and let xdist read the variable.**: The root conftest wraps `pytest_xdist_auto_num_workers` so that such a run waits for a gate slot (#4525), and with no variable it starts up to the CPUs of one gate slot, 16 on this host, against the cap of 4 that #1669 measured. +- **Use `-n 1` for a cap of 1.**: It starts one worker process for no parallel gain. `-n 0` runs the tests in the pytest process. +- **Skip the collection for more than `DEFAULT_CI_TEST_SERIAL_MAX_FILES` (12) target modules.**: That changes the rule of #4472 instead of bounding its cost: 13 to 50 modules can collect 50 tests or fewer, and the collected count then runs them serially. Only more than 50 modules prove more than 50 tests. +- **Remove `PYTEST_XDIST_AUTO_NUM_WORKERS` in the hermetic floor of `tests/conftest.py`.**: The floor runs for each test of the suite, and a test that starts a real pytest child would lose the bound of its pod. Only the tests of this module read the variable through the command. +- **Keep `DEFAULT_SUBPROCESS_TIMEOUT_SECONDS` for the collection.**: It is 1800 s, the same limit as the run, so a collection that hangs uses the time of the run and the outer limit fires first. +- **Lower the limit of 50 tests, or size the workers by the time of the tests.**: The 52-test module above ran in 8 s serially and in 22 s with the collection and 4 workers, so a count of tests is a poor sign of the work. That is a change of the rule of #4472 and needs a source of test times, which the project does not keep; the issue does not ask for it. + +## Unchanged references + +- `src/devops_cli/roadmap/implement/implement_size.py` (definition): `WORKERS_VARIABLE` keeps its home, and the command imports it from there. +- `src/devops_cli/roadmap/implement/implement_step.py` (other collection): Its test-form check runs `uv run pytest --collect-only -q -- ` with no `-n 0`, so `addopts` gives `-n logical`. syrupy then gets no report from the xdist workers and skips the check of unused snapshots: `tests/output/test_output.py` printed `1 snapshot unused.` and exited 0. So that check does not have defect 1, and this change does not touch it. +- `openspec/changes/archive/2026-11-13-4472-a-narrowed-ci-test-runs-many/design.md` (archived design): It records the decisions of #4472 as they were, and this design records what changed. diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md b/openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md new file mode 100644 index 0000000000..00c1259646 --- /dev/null +++ b/openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md @@ -0,0 +1,52 @@ +# Proposal: #5606 + +## Why + +The fix of #4472 counts the tests of a narrowed `devops ci test` run with a second pytest session, and chooses the workers from that count. Three defects stop it (#5606): + +- A collection runs no test, so syrupy finds each snapshot of a selected module unused and exits 1. The command reads exit 1 as a failed collection and goes back to the file count. So the 7 modules of #4472 still run with `-n 0`. +- The run gives an explicit `-n 4`, and xdist reads `PYTEST_XDIST_AUTO_NUM_WORKERS` only for `-n auto` and `-n logical`. So a runner pod with 1 CPU runs 4 workers on that CPU. +- Each narrowed run starts the collection, also when its count cannot change the worker count, and the collection has the 1800 s timeout of the run. + +## What Changes + +- `_collection_cmd` in `src/devops_cli/commands/ci.py` adds `--snapshot-warn-unused`, the option that the shard rows already give, through one module constant `_SNAPSHOT_WARN_UNUSED`. +- A new `_worker_cap` gives `DEFAULT_CI_TEST_NARROWED_WORKERS`, or the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` when it is smaller. It ignores a value that is no whole number, as xdist does. +- `_narrowed_workers(targets, keyword)` starts the collection only when the count can change the answer. A cap of 1 or less runs `-n 0`. More than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` target modules with no `-k` filter run on the cap. In all other cases the collection decides, and the file count decides when the collection gives no count. +- `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` (120 s) joins `src/devops_cli/config/defaults.py` with the measured times in its comment, and the collection uses it. +- The warning of a failed collection prints with `safe=True`, so brackets in a target or a `-k` value print as text. +- `src/devops_cli/lang/en/help.py` adds the bound of `PYTEST_XDIST_AUTO_NUM_WORKERS` to the `-n` help, and `docs/commands/ci.md` is regenerated. +- `docs/TESTING.md` and `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md` state the new rule. +- `tests/commands/test_test_selection.py` adds the cases of #5606, puts the 12-module boundary back as a case of the fallback, and adds a `--repeat` case that makes no collection. +- The `-n` value that a run gets changes, so the change has a delta of `ci-test-workers`. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `ci-test-workers`: Collected tests choose the workers, Collection uses the run selection, Collection failure falls back (modified); Collection only when its count can change the workers, Repeat runs make no collection (added). + +## Impact + +- Code: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/lang/en/help.py` +- Documents: `docs/TESTING.md`, `docs/commands/ci.md`, `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md` +- Tests: `tests/commands/test_test_selection.py` +- A runner Job with 1 CPU runs a narrowed selection serially with no collection: a 52-test module took 37 s before and 8 s after on 1 CPU (`design.md`). + +## Feasibility + +- `git -C log -1 origin/main` gave `b15faabb7 chore(main): release 0.136.1`, and `src/devops_cli/commands/ci.py:1941` on that commit is `def _collection_cmd(targets: list[str], keyword: str | None) -> list[str]:`, which returns `uv run pytest -n 0 --collect-only -q ` with no syrupy option. +- `uv run pytest -n 0 --collect-only -q` on the 7 modules of #4472, with pytest 9.2.0, pytest-xdist 3.8.0 and syrupy 7.0.0, printed `4 snapshots unused.`, `Re-run pytest with --snapshot-update to delete unused snapshots.` and `422 tests collected in 1.03s`, and exited 1. The same command with `--snapshot-warn-unused` exited 0, and `collected_items` read 422 tests from its output. So the premise of defect 1 holds. +- `pytest_xdist_auto_num_workers` in the installed `xdist/plugin.py` reads `PYTEST_XDIST_AUTO_NUM_WORKERS` and ignores a value that `int()` refuses. xdist calls that hook only for `-n auto` and `-n logical`, and `_narrowed_workers` on `origin/main` returns the literal `str(DEFAULT_CI_TEST_NARROWED_WORKERS)`. With `PYTEST_XDIST_AUTO_NUM_WORKERS=1` and `taskset -c 3`, `uv run devops ci test tests/roadmap/test_roadmap_claim.py` printed `created: 4/4 workers`. So the premise of defect 2 holds. +- The same run took 37.2 s and 37.7 s, and `-n 0` on the same CPU took 7.9 s and 8.4 s. So the collection and the 4 workers cost about 29 s on 1 CPU, and the premise of defect 3 holds on this host. +- `_collected_test_count` on `origin/main` passes `DEFAULT_SUBPROCESS_TIMEOUT_SECONDS` (1800 s) and calls `print_warning` with no `safe=True`. `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md:69` states the file-count rule. `tests/commands/test_test_selection.py` on `origin/main` has no 12-module case and no `--repeat` case. So the minor points of the issue hold. +- No newer issue or commit replaces this item: `git log origin/main` after 2126dc642 holds only release commits and #5594 with its revert #5601, which do not touch `src/devops_cli/commands/ci.py`. + +## Existing Tool Considered + +pytest-xdist is the open tool that starts the workers, and syrupy is the open tool that checks the snapshots. The fix uses the options that both give: `--snapshot-warn-unused` of syrupy, and `PYTEST_XDIST_AUTO_NUM_WORKERS`, the bound that xdist itself reads. No open tool chooses the workers of a narrowed run, so the change writes about 30 lines of policy in the command module. Cost: about 3,000 tokens to write, 3,000 tokens to keep and fix, and 3 hours of elapsed time. It deletes no internal code: it changes `_narrowed_workers` and keeps the fallback to the file count. diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md b/openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md new file mode 100644 index 0000000000..6881e95c1d --- /dev/null +++ b/openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md @@ -0,0 +1,70 @@ +## MODIFIED 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. It SHALL start no more workers than the worker cap: `DEFAULT_CI_TEST_NARROWED_WORKERS`, or the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` when that value is a smaller whole number. It SHALL ignore a value that is no whole number, as xdist does. + +#### 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`. + +#### Scenario: Worker bound of a pod with 2 CPUs +- **WHEN** `PYTEST_XDIST_AUTO_NUM_WORKERS` is 2 and the 7 selected files collect 399 tests. +- **THEN** The command runs pytest with `-n 2`. + +#### Scenario: Selected module with unused snapshots +- **WHEN** The 7 selected files collect 422 tests, and the collection exits 1 without `--snapshot-warn-unused` and 0 with it, as syrupy does for a selected module that has snapshots. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and prints no collection warning. + +### Requirement: Collection uses the run selection +The command MUST collect tests with the same target list and keyword filter that it passes to pytest, and with `--snapshot-warn-unused`, so that the snapshots that a collection leaves unused do not fail it. + +#### Scenario: Collection command arguments +- **WHEN** The caller passes two test files and `-k slow`. +- **THEN** The collection command holds both file paths, `-k slow` and `--snapshot-warn-unused`. + +### Requirement: Collection failure falls back +When pytest collection fails or runs past `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`, the command SHALL fall back to the file-count rule and continue: up to `DEFAULT_CI_TEST_SERIAL_MAX_FILES` test modules run with `-n 0`, and more modules run on the worker cap. The warning SHALL show the collection command as text, not as Rich markup. An exit code 5, which says that no test was collected, is a count of zero and no failure. + +#### Scenario: Collection error at the file bound +- **WHEN** The collection command exits with code 3 for a selection of 12 test files. +- **THEN** The command runs pytest with `-n 0` and prints a warning that names the collection 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: Collection timeout +- **WHEN** The collection command runs past its timeout for a selection of 13 test files. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and prints a warning that names a timeout of `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`. + +#### Scenario: Brackets in the keyword filter +- **WHEN** The collection command exits with code 3 and the caller passes `-k noop[/x]`. +- **THEN** The command exits 0 and the warning shows `noop[/x]` as it is. + +#### 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. + +## ADDED Requirements + +### Requirement: Collection only when its count can change the workers +The command SHALL start no collection when the count cannot change the worker count. A worker cap of 1 or less SHALL run pytest with `-n 0`. More than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` target modules with no `-k` filter SHALL run on the worker cap, because each module collects one test at least. + +#### Scenario: Worker bound of a pod with 1 CPU +- **WHEN** `PYTEST_XDIST_AUTO_NUM_WORKERS` is 1 and the 7 selected files collect 399 tests. +- **THEN** The command runs pytest with `-n 0` and makes no collection call. + +#### Scenario: More target modules than the test limit +- **WHEN** The caller passes `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` + 1 test files and no `-k`. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and makes no collection call. + +#### Scenario: More target modules than the test limit with a filter +- **WHEN** The caller passes `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` + 1 test files and `-k noop`. +- **THEN** The command makes one collection call. + +### Requirement: Repeat runs make no collection +A `--repeat` run SHALL run each repeat with `-n 0` and make no collection call. + +#### Scenario: Repeat run +- **WHEN** The caller passes `--repeat 2 --seed 1` and one test file. +- **THEN** The command makes no collection call. diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md b/openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md new file mode 100644 index 0000000000..4056a6283a --- /dev/null +++ b/openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md @@ -0,0 +1,28 @@ +# Tasks + +## 1. Count the tests of a narrowed run only when the count can change the workers + +Kind: behavior. Reads: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/roadmap/implement/implement_size.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/help.py`, `docs/commands/ci.md`, `tests/commands/test_test_selection.py`. + +- [x] 1.1 Write the failing cases first in `tests/commands/test_test_selection.py`: the 7 modules of #4472 with a collection that exits 1 without `--snapshot-warn-unused` and 0 with it run on `DEFAULT_CI_TEST_NARROWED_WORKERS` with no warning; `PYTEST_XDIST_AUTO_NUM_WORKERS` of 1 and 0 run `-n 0` with no collection, 2 runs `-n 2`, and 16 and a value that is no number run on 4; 51 target modules with no `-k` make no collection, and 50 modules or a `-k` filter collect; a failed collection with `-k noop[/x]` exits 0 and shows `noop[/x]`; the timeout warning names `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`, read through `defaults` in the body of the test; and the collection argv holds `--snapshot-warn-unused`. Add the fixture `no_worker_bound` to `pytestmark`, so a runner pod's bound does not reach the other cases + - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` fails on the base +- [x] 1.2 Add `_SNAPSHOT_WARN_UNUSED` to `src/devops_cli/commands/ci.py` and give it to `_collection_cmd` and the shard command. Add `_worker_cap`, which bounds `DEFAULT_CI_TEST_NARROWED_WORKERS` with `PYTEST_XDIST_AUTO_NUM_WORKERS`, and give `_narrowed_workers(targets, keyword)` the two skips of the collection. Add `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` (120 s) with the measured times to `src/devops_cli/config/defaults.py`, use it in `_collected_test_count`, and print its warning with `safe=True`. Add the bound to the `-n` help in `src/devops_cli/lang/en/help.py`, and regenerate `docs/commands/ci.md` with `uv run devops docs generate` + - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py tests/commands/test_ci.py tests/commands/test_ci_repeat.py` passes + +## 2. Put back the boundary and repeat cases + +Kind: other. Reads: `tests/commands/test_test_selection.py`. Changes: `tests/commands/test_test_selection.py`. + +- [x] 2.1 Parametrize `test_a_failed_collection_falls_back_to_the_file_count_with_a_warning` with 12 test modules, which run `-n 0`, and 13, which run on `DEFAULT_CI_TEST_NARROWED_WORKERS`. Add a `--repeat 2 --seed 1` case to `test_a_run_that_chooses_its_workers_by_other_means_makes_no_collection` + - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` passes + +## 3. State the rule in the documents + +Kind: other. Reads: `docs/TESTING.md`, `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md`. Changes: `docs/TESTING.md`, `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md`. + +- [x] 3.1 State the collection option, the worker cap, the two skips of the collection, its timeout and the text warning in `docs/TESTING.md`, and replace the file-count rule of `src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md` with the collected-test rule + - Verification: `$ uv run devops ci --check --only docs` passes + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md index c9d247888e..2a1f5d8c03 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md @@ -66,7 +66,7 @@ devops ci 1. **Fix Errors Progressively**: Resolve linting and formatting first, then type checking, then unit tests, and finally documentation sync. 2. **Synchronize Docs**: If the docs gate reports discrepancies, run `devops docs generate` to regenerate markdown reference files. -3. **Parallel Test Execution**: `devops ci test` runs the full suite on every logical CPU via `pytest-xdist`; a run narrowed to a few test files (`devops ci test `) runs serially, and a larger selection on a few workers. pytest-timeout fails a test that hangs, so no run stalls on one. +3. **Parallel Test Execution**: `devops ci test` runs the full suite on every logical CPU via `pytest-xdist`. A run narrowed to the tests that it selects (`devops ci test `) counts the tests with a short collection first: up to 50 collected tests run serially, and more tests run on 4 workers at most, never more than `PYTEST_XDIST_AUTO_NUM_WORKERS`. A run with a bound of 1 CPU runs serially and makes no collection. pytest-timeout fails a test that hangs, so no run stalls on one. 4. **Pre-Commit Enforcement**: Pre-commit hooks run essential subsets of `devops ci` on `git commit`. The pre-push hooks run `uv run devops ci --check --only lint,format,domain`, and `uv run devops ci --check --only actionlint,zizmor` when the push changes a workflow. Push only when they pass, and never use `--no-verify`. --- diff --git a/src/devops_cli/commands/ci.py b/src/devops_cli/commands/ci.py index a1aa8f4f6a..a1dbb229e5 100644 --- a/src/devops_cli/commands/ci.py +++ b/src/devops_cli/commands/ci.py @@ -49,6 +49,7 @@ DEFAULT_CI_BANDIT_NICENESS, DEFAULT_CI_JOB_TIME_RUNS, DEFAULT_CI_MUTATE_TIMEOUT_SECONDS, + DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS, DEFAULT_CI_TEST_NARROWED_WORKERS, DEFAULT_CI_TEST_REPEAT_RUNS, DEFAULT_CI_TEST_SERIAL_MAX_FILES, @@ -108,6 +109,10 @@ def invoke(self, ctx: Any) -> Any: # a reviewed nosec marker that names its rules and a reason (#1538). `tests/` keeps # DEFAULT_BANDIT_SEVERITY. _BANDIT_SOURCE_SEVERITY: Final[str] = "low" +# syrupy fails a pytest session that leaves a snapshot of a collected module unused. A shard runs a +# part of the suite and a collection runs no test, so both give this option, which makes that +# failure a warning (#5606). +_SNAPSHOT_WARN_UNUSED: Final[str] = "--snapshot-warn-unused" def _get_project_root() -> Path: @@ -694,7 +699,7 @@ def _resolve_pytest_cmd(*, shard: int = 1, shards: int = 1) -> list[str]: *cmd, "--cov-report=", "--cov-fail-under=0", - "--snapshot-warn-unused", + _SNAPSHOT_WARN_UNUSED, f"-r{CONST_CI_SHARD_SUMMARY_CHARS}", f"--junitxml={CONST_CI_SHARD_JUNIT_PATH}", *shard_test_files(shard, shards, _get_project_root()), @@ -1940,8 +1945,16 @@ def _build_test_cmd( 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] + quiet, with the same targets and `-k` filter, so the count follows what the run would run. + A collection runs no test, so syrupy finds each snapshot of a selected module unused, and + `--snapshot-warn-unused` keeps that from an exit 1 that hides the count (#5606).""" + return [ + *_build_test_cmd("0", False, keyword, False, None), + "--collect-only", + "-q", + _SNAPSHOT_WARN_UNUSED, + *targets, + ] def _collected_test_count(targets: list[str], keyword: str | None) -> int | None: @@ -1955,11 +1968,11 @@ def _collected_test_count(targets: list[str], keyword: str | None) -> int | None try: result = asyncio.run( _run_in_own_session( - cmd, _get_project_root(), DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, True, None + cmd, _get_project_root(), DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS, True, None ) ) except subprocess.TimeoutExpired: - reason = f"a timeout after {DEFAULT_SUBPROCESS_TIMEOUT_SECONDS:g}s" + reason = f"a timeout after {DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS:g}s" except asyncio.CancelledError: raise typer.Exit(CONST_EXIT_CANCELLED) from None else: @@ -1970,25 +1983,52 @@ def _collected_test_count(targets: list[str], keyword: str | None) -> int | None 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)) + print_warning( + MESSAGES.ci.test_collection_failed.format(command=shlex.join(cmd), reason=reason), + safe=True, + ) return None -def _narrowed_workers(targets: list[str] | None, collected: int | None = None) -> str | None: +def _worker_cap() -> int: + """The most workers of a narrowed run: DEFAULT_CI_TEST_NARROWED_WORKERS, or the value of + PYTEST_XDIST_AUTO_NUM_WORKERS when it is smaller. A runner pod sets that variable to its CPU + limit, because xdist counts the CPUs of the node, and xdist reads it only for `-n auto` or + `-n logical`, never for the explicit `-n` of a narrowed run (#2806, #5606). xdist ignores a + value that is no whole number, and so does this.""" + from devops_cli.roadmap.implement.implement_size import WORKERS_VARIABLE + + try: + bound = int(os.environ.get(WORKERS_VARIABLE, "")) + except ValueError: + return DEFAULT_CI_TEST_NARROWED_WORKERS + return min(DEFAULT_CI_TEST_NARROWED_WORKERS, bound) + + +def _narrowed_workers(targets: list[str] | None, keyword: str | 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 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).""" + tests, where each xdist worker's start-up and collection cost more than it saves; and the + worker cap above that (#4472). + + The collection is a second pytest session, so the run starts it only when its count can + change the answer (#5606). A cap of one worker or less is a serial run. Each target module + collects one test at least, so more than DEFAULT_CI_TEST_SERIAL_MAX_TESTS target modules with + no `-k` filter take the cap. When the collection gives no count, the number of test modules + decides, up to DEFAULT_CI_TEST_SERIAL_MAX_FILES.""" 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: + cap = _worker_cap() + if cap <= 1: return "0" - return str(DEFAULT_CI_TEST_NARROWED_WORKERS) + if not keyword and len(targets) > DEFAULT_CI_TEST_SERIAL_MAX_TESTS: + return str(cap) + collected = _collected_test_count(targets, keyword) + if collected is None: + parallel = len(targets) > DEFAULT_CI_TEST_SERIAL_MAX_FILES + else: + parallel = collected > DEFAULT_CI_TEST_SERIAL_MAX_TESTS + return str(cap) if parallel else "0" def _head_seed(root: Path) -> int: @@ -2066,10 +2106,7 @@ def test( _run_shuffled_repeats(_build_test_cmd("0", verbose, k, x, None), targets, repeat, seed) return - workers = numprocesses - if workers is None: - collected = _collected_test_count(targets, k) if targets else None - workers = _narrowed_workers(targets, collected) + workers = numprocesses if numprocesses is not None else _narrowed_workers(targets, k) 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 91083013f6..8ffec6e26c 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -495,9 +495,19 @@ # 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. +# only when that collection fails, or when more target modules than this limit, with no `-k` +# filter, hold more tests than it (#5606). DEFAULT_CI_TEST_SERIAL_MAX_TESTS: Final[int] = 50 +# The most workers of a narrowed run, and fewer when PYTEST_XDIST_AUTO_NUM_WORKERS is smaller +# (#5606): a runner pod sets it to its CPU limit, and an explicit `-n` skips it. DEFAULT_CI_TEST_NARROWED_WORKERS: Final[int] = 4 +# The time limit of the collection that counts the tests of a narrowed run (#5606). The collection +# is a second pytest session, and the start-up of pytest is most of its time. Measured wall time: +# 6 to 8 s for 1 module and 7 s for the 7 modules of #4472 at a load of 1 to 6 on 16 CPUs, 22 s for +# the 7 modules with a cold cache, 55 s for the whole suite, and 23 to 47 s for a narrowed +# selection at a high load. 120 s is above 2.5 times the slowest narrowed sample and far below the +# 1800 s limit of the run, so it fires first and the run falls back to the file count. +DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS: Final[float] = 120.0 # `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`. DEFAULT_CI_JOB_TIME_RUNS: Final[int] = 20 diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index 6a31cbbd6a..c96106b661 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -897,8 +897,8 @@ class CICommandHelp: stop_fail: str = "Stop after first failure." num_workers: str = ( "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." + "runs serially up to 50 collected tests and on a few workers above them, never more than " + "PYTEST_XDIST_AUTO_NUM_WORKERS, 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/tests/commands/test_test_selection.py b/tests/commands/test_test_selection.py index 19f928c7f8..51924b14d7 100644 --- a/tests/commands/test_test_selection.py +++ b/tests/commands/test_test_selection.py @@ -32,13 +32,14 @@ module_path_for_source, select_tests_for_sources, ) +from devops_cli.roadmap.implement.implement_size import WORKERS_VARIABLE from tests.support.ci_root import tracked_blobs 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 -pytestmark = pytest.mark.usefixtures("refuse_nested_test_runs") +pytestmark = pytest.mark.usefixtures("refuse_nested_test_runs", "no_worker_bound") runner = CliRunner() @@ -50,6 +51,18 @@ # 1800 s timeout of `devops ci test`. _ISSUE_TEST_MODULES = 7 _ISSUE_COLLECTED_TESTS = 399 +# The tests that the same 7 modules collected on the base of #5606, where syrupy found 4 unused +# snapshots and the collection exited 1. +_ISSUE_COLLECTED_TESTS_ON_THE_BASE = 422 +# syrupy's option that makes a snapshot which no test of the session reads a warning, not exit 1. +_SNAPSHOT_WARN_UNUSED = "--snapshot-warn-unused" + + +@pytest.fixture +def no_worker_bound(monkeypatch: pytest.MonkeyPatch) -> None: + """Remove the worker bound that a runner pod sets to its CPU limit, so that a narrowed run + starts up to DEFAULT_CI_TEST_NARROWED_WORKERS workers unless the test sets the bound (#5606).""" + monkeypatch.delenv(WORKERS_VARIABLE, raising=False) @pytest.fixture @@ -94,12 +107,31 @@ def _collection_calls(process_fake: ProcessFake) -> list[list[str]]: return [list(call.argv) for call in process_fake.calls if _COLLECTION_MARK in call.argv] +def _collected_ids(tests: int) -> str: + """The quiet collection output of `tests` test ids, one on each line.""" + return "".join(f"tests/test_selected_{number}.py::test_noop\n" for number in range(tests)) + + 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 ""), + ProcessAnswer( + returncode=returncode, stdout=_collected_ids(tests) if returncode == 0 else "" + ), + ) + + +def _answer_collection_with_unused_snapshots(process_fake: ProcessFake, tests: int) -> None: + """Answer the collection as syrupy does when a selected module has snapshots: a collection + runs no test, so every snapshot is unused, and pytest prints the `tests` ids and exits 1, + unless the collection gives `--snapshot-warn-unused` (#5606).""" + output = f"{_collected_ids(tests)}4 snapshots unused.\n{tests} tests collected in 0.31s\n" + process_fake.answer( + lambda call: _COLLECTION_MARK in call.argv, + lambda call: ProcessAnswer( + returncode=0 if _SNAPSHOT_WARN_UNUSED in call.argv else 1, stdout=output + ), ) @@ -624,6 +656,108 @@ def test_a_few_test_modules_that_collect_many_tests_run_on_the_capped_workers( ) +def test_a_selection_with_unused_snapshots_still_runs_on_the_capped_workers( + process_fake: ProcessFake, project: Path +) -> None: + """A collection runs no test, so syrupy finds each snapshot of a selected module unused and + exits 1, unless the collection gives `--snapshot-warn-unused`. The 7 test modules of #4472 hold + such a module and collect 422 tests: the run counts them and takes + DEFAULT_CI_TEST_NARROWED_WORKERS workers, with no warning. Before the fix, the exit 1 sent the + run back to the file count, which ran the 7 modules serially (#5606).""" + modules = _test_modules(project, _ISSUE_TEST_MODULES) + _answer_collection_with_unused_snapshots(process_fake, _ISSUE_COLLECTED_TESTS_ON_THE_BASE) + + result = runner.invoke(ci_app, ["test", *modules]) + + assert ( + result.exit_code, + [_worker_options(argv) for argv in _pytest_runs(process_fake)], + _COLLECTION_WARNING in " ".join(result.output.split()), + ) == (0, [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]], False) + + +@pytest.mark.parametrize( + ("bound", "collections", "workers"), + [ + pytest.param("1", 0, "0", id="one-cpu"), + pytest.param("0", 0, "0", id="zero"), + pytest.param("2", 1, "2", id="two-cpus"), + pytest.param("16", 1, str(DEFAULT_CI_TEST_NARROWED_WORKERS), id="more-cpus-than-the-cap"), + pytest.param("many", 1, str(DEFAULT_CI_TEST_NARROWED_WORKERS), id="not-a-number"), + ], +) +def test_the_worker_bound_of_the_pod_caps_the_workers_of_a_narrowed_run( + monkeypatch: pytest.MonkeyPatch, + process_fake: ProcessFake, + project: Path, + bound: str, + collections: int, + workers: str, +) -> None: + """A runner pod sets PYTEST_XDIST_AUTO_NUM_WORKERS to its CPU limit, and an explicit `-n` + skips that variable, so the run starts the smaller of the variable and + DEFAULT_CI_TEST_NARROWED_WORKERS. A bound of one CPU or less runs serially, and a collection + cannot change that, so the run makes none. xdist ignores a value that is no whole number, and + so does the run (#5606).""" + monkeypatch.setenv(WORKERS_VARIABLE, bound) + 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, + len(_collection_calls(process_fake)), + [_worker_options(argv) for argv in _pytest_runs(process_fake)], + ) == (0, collections, [[["-n", workers]]]) + + +@pytest.mark.parametrize( + ("extra_modules", "keyword", "collections"), + [ + pytest.param(0, (), 1, id="at-the-limit"), + pytest.param(1, (), 0, id="past-the-limit"), + pytest.param(1, ("-k", "noop"), 1, id="past-the-limit-with-a-keyword"), + ], +) +def test_more_target_modules_than_the_collected_test_limit_make_no_collection( + process_fake: ProcessFake, + project: Path, + extra_modules: int, + keyword: tuple[str, ...], + collections: int, +) -> None: + """Each target module collects one test at least, so more than + DEFAULT_CI_TEST_SERIAL_MAX_TESTS target modules with no `-k` filter collect more tests than + the limit: the file count decides, and the run takes DEFAULT_CI_TEST_NARROWED_WORKERS workers + with no collection. A `-k` filter can leave fewer tests, and so can a selection at the limit, + so both collect (#5606).""" + serial_max_tests = defaults.DEFAULT_CI_TEST_SERIAL_MAX_TESTS + modules = _test_modules(project, serial_max_tests + extra_modules) + _answer_collection(process_fake, serial_max_tests + 1) + + result = runner.invoke(ci_app, ["test", *keyword, *modules]) + + assert ( + result.exit_code, + len(_collection_calls(process_fake)), + [_worker_options(argv) for argv in _pytest_runs(process_fake)], + ) == (0, collections, [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]]) + + +def test_the_collection_warning_shows_the_brackets_of_a_keyword_as_text( + process_fake: ProcessFake, project: Path +) -> None: + """The warning of a failed collection names its command as text, so the brackets of a `-k` + value or of a target print as they are, and are no Rich markup that hides them or stops the + run (#5606).""" + _answer_collection(process_fake, 0, returncode=3) + + result = runner.invoke(ci_app, ["test", "-k", "noop[/x]", "tests/test_secrets.py"]) + + assert (result.exit_code, "noop[/x]" in " ".join(result.output.split())) == (0, True) + + def test_a_selection_past_the_collected_test_limit_runs_on_the_capped_workers( process_fake: ProcessFake, project: Path ) -> None: @@ -656,7 +790,8 @@ 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).""" + the tests the run would collect (#4472), and gives `--snapshot-warn-unused`, so the snapshots + that it leaves unused do not fail it (#5606).""" _answer_collection(process_fake, 5) result = runner.invoke( @@ -668,8 +803,9 @@ def test_the_collection_repeats_the_targets_and_the_keyword_of_the_run( result.exit_code, _keyword_options(collection), sorted(arg for arg in collection if arg.startswith("tests/")), + _SNAPSHOT_WARN_UNUSED in collection, _keyword_options(_pytest_runs(process_fake)[0]), - ) == (0, ["slow"], ["tests/test_secrets.py", "tests/test_unrelated.py"], ["slow"]) + ) == (0, ["slow"], ["tests/test_secrets.py", "tests/test_unrelated.py"], True, ["slow"]) def test_a_collection_that_matches_no_test_runs_serially_without_a_warning( @@ -688,20 +824,32 @@ def test_a_collection_that_matches_no_test_runs_serially_without_a_warning( assert _COLLECTION_WARNING not in result.output +@pytest.mark.parametrize( + ("modules", "workers"), + [ + pytest.param(DEFAULT_CI_TEST_SERIAL_MAX_FILES, "0", id="at-the-file-limit"), + pytest.param( + DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1, + str(DEFAULT_CI_TEST_NARROWED_WORKERS), + id="past-the-file-limit", + ), + ], +) def test_a_failed_collection_falls_back_to_the_file_count_with_a_warning( - process_fake: ProcessFake, project: Path + process_fake: ProcessFake, project: Path, modules: int, workers: str ) -> 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) + """A collection that fails prints a warning that names it and keeps the file-count rule: up + to DEFAULT_CI_TEST_SERIAL_MAX_FILES test modules run serially, and one module more takes + DEFAULT_CI_TEST_NARROWED_WORKERS workers, where a count of zero would run serially (#1669, + #4472).""" + paths = _test_modules(project, modules) _answer_collection(process_fake, 0, returncode=3) - result = runner.invoke(ci_app, ["test", *modules]) + result = runner.invoke(ci_app, ["test", *paths]) assert (result.exit_code, [_worker_options(argv) for argv in _pytest_runs(process_fake)]) == ( 0, - [[["-n", str(DEFAULT_CI_TEST_NARROWED_WORKERS)]]], + [[["-n", workers]]], ) assert _COLLECTION_WARNING in " ".join(result.output.split()) @@ -709,9 +857,12 @@ def test_a_failed_collection_falls_back_to_the_file_count_with_a_warning( 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).""" + """A collection that outlives its own timeout, DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS, + 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). The test reads the timeout through `defaults` when it runs, so this module + also imports on a base that does not have it (#5606).""" + timeout = f"a timeout after {defaults.DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS:g}s" modules = _test_modules(project, DEFAULT_CI_TEST_SERIAL_MAX_FILES + 1) async def outlive_the_timeout(spawn: RecordedSpawn) -> None: @@ -723,11 +874,12 @@ async def outlive_the_timeout(spawn: RecordedSpawn) -> None: result = runner.invoke(ci_app, ["test", *modules]) runs = [spawn for spawn in spawns if _COLLECTION_MARK not in spawn.argv] + output = " ".join(result.output.split()) 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()) + assert (_COLLECTION_WARNING in output, timeout in output) == (True, True) def test_a_collection_cancelled_by_a_stop_signal_exits_as_cancelled( @@ -766,13 +918,14 @@ def test_a_dry_run_plans_the_workers_without_collecting( [ pytest.param((), id="full-suite"), pytest.param(("-n", "2", "tests/test_secrets.py"), id="workers-given"), + pytest.param(("--repeat", "2", "--seed", "1", "tests/test_secrets.py"), id="repeat"), ], ) 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).""" + """A run with no paths keeps addopts' `-n logical`, a given `-n` is kept as it is, and a + `--repeat` run is serial, so none of them starts a collection (#4472, #5606).""" result = runner.invoke(ci_app, ["test", *args]) assert (result.exit_code, _collection_calls(process_fake)) == (0, []) From af8b69472ed8af047e14b7a715f66a3f6f11301c Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 03:36:39 +0000 Subject: [PATCH 2/3] test(ci): pin the timeout of the narrowed test collection The process fake now must receive DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS for the collection. The timeout case only read the reason text, so a collection with the 1800 s timeout of the run passed it. The knowledge-base page also names the second skip of the collection (#5606). --- .../devops_cli/tasks/ci_quality_gate.md | 2 +- tests/commands/test_test_selection.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md index 2a1f5d8c03..c63ba4d893 100644 --- a/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md +++ b/src/devops_cli/ai/knowledge_base/devops_cli/tasks/ci_quality_gate.md @@ -66,7 +66,7 @@ devops ci 1. **Fix Errors Progressively**: Resolve linting and formatting first, then type checking, then unit tests, and finally documentation sync. 2. **Synchronize Docs**: If the docs gate reports discrepancies, run `devops docs generate` to regenerate markdown reference files. -3. **Parallel Test Execution**: `devops ci test` runs the full suite on every logical CPU via `pytest-xdist`. A run narrowed to the tests that it selects (`devops ci test `) counts the tests with a short collection first: up to 50 collected tests run serially, and more tests run on 4 workers at most, never more than `PYTEST_XDIST_AUTO_NUM_WORKERS`. A run with a bound of 1 CPU runs serially and makes no collection. pytest-timeout fails a test that hangs, so no run stalls on one. +3. **Parallel Test Execution**: `devops ci test` runs the full suite on every logical CPU via `pytest-xdist`. A run narrowed to the tests that it selects (`devops ci test `) counts the tests with a short collection first: up to 50 collected tests run serially, and more tests run on 4 workers at most, never more than `PYTEST_XDIST_AUTO_NUM_WORKERS`. A run with a bound of 1 CPU runs serially and makes no collection. A selection of more than 50 test modules with no `-k` filter also makes no collection: it runs on the workers. pytest-timeout fails a test that hangs, so no run stalls on one. 4. **Pre-Commit Enforcement**: Pre-commit hooks run essential subsets of `devops ci` on `git commit`. The pre-push hooks run `uv run devops ci --check --only lint,format,domain`, and `uv run devops ci --check --only actionlint,zizmor` when the push changes a workflow. Push only when they pass, and never use `--no-verify`. --- diff --git a/tests/commands/test_test_selection.py b/tests/commands/test_test_selection.py index 51924b14d7..c437f1d335 100644 --- a/tests/commands/test_test_selection.py +++ b/tests/commands/test_test_selection.py @@ -808,6 +808,25 @@ def test_the_collection_repeats_the_targets_and_the_keyword_of_the_run( ) == (0, ["slow"], ["tests/test_secrets.py", "tests/test_unrelated.py"], True, ["slow"]) +def test_the_collection_runs_under_its_own_short_timeout( + process_fake: ProcessFake, project: Path +) -> None: + """The collection gets DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS, not the timeout of the run, + so a collection that hangs stops before the run's own limit and the file count decides + (#5606). The test reads the timeout through `defaults` when it runs, so this module also + imports on a base that does not have it.""" + _answer_collection(process_fake, 5) + + result = runner.invoke(ci_app, ["test", "tests/test_secrets.py"]) + + timeouts = [call.timeout for call in process_fake.calls if _COLLECTION_MARK in call.argv] + assert (result.exit_code, timeouts) == ( + 0, + [defaults.DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS], + ) + assert timeouts[0] < defaults.DEFAULT_SUBPROCESS_TIMEOUT_SECONDS + + def test_a_collection_that_matches_no_test_runs_serially_without_a_warning( process_fake: ProcessFake, project: Path ) -> None: From 6e21f7d1ed64c6995c15a5ba9a9552064765875d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 14 Nov 2026 03:32:47 +0000 Subject: [PATCH 3/3] docs(openspec): archive the change (#5606) --- .../.openspec.yaml | 0 .../design.md | 2 +- .../proposal.md | 0 .../specs/ci-test-workers/spec.md | 0 .../tasks.md | 3 +- openspec/specs/ci-test-workers/spec.md | 50 +++++++++++++++++-- 6 files changed, 49 insertions(+), 6 deletions(-) rename openspec/changes/{5606-narrowed-test-workers-fall-back-and => archive/2026-11-14-5606-narrowed-test-workers-fall-back-and}/.openspec.yaml (100%) rename openspec/changes/{5606-narrowed-test-workers-fall-back-and => archive/2026-11-14-5606-narrowed-test-workers-fall-back-and}/design.md (99%) rename openspec/changes/{5606-narrowed-test-workers-fall-back-and => archive/2026-11-14-5606-narrowed-test-workers-fall-back-and}/proposal.md (100%) rename openspec/changes/{5606-narrowed-test-workers-fall-back-and => archive/2026-11-14-5606-narrowed-test-workers-fall-back-and}/specs/ci-test-workers/spec.md (100%) rename openspec/changes/{5606-narrowed-test-workers-fall-back-and => archive/2026-11-14-5606-narrowed-test-workers-fall-back-and}/tasks.md (86%) diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/.openspec.yaml b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/.openspec.yaml similarity index 100% rename from openspec/changes/5606-narrowed-test-workers-fall-back-and/.openspec.yaml rename to openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/.openspec.yaml diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/design.md similarity index 99% rename from openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md rename to openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/design.md index b3130e55f8..139459569c 100644 --- a/openspec/changes/5606-narrowed-test-workers-fall-back-and/design.md +++ b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/design.md @@ -40,7 +40,7 @@ The scoped run of this change, `uv run devops ci test` with the 3 changed source - **Skip the collection for more than `DEFAULT_CI_TEST_SERIAL_MAX_FILES` (12) target modules.**: That changes the rule of #4472 instead of bounding its cost: 13 to 50 modules can collect 50 tests or fewer, and the collected count then runs them serially. Only more than 50 modules prove more than 50 tests. - **Remove `PYTEST_XDIST_AUTO_NUM_WORKERS` in the hermetic floor of `tests/conftest.py`.**: The floor runs for each test of the suite, and a test that starts a real pytest child would lose the bound of its pod. Only the tests of this module read the variable through the command. - **Keep `DEFAULT_SUBPROCESS_TIMEOUT_SECONDS` for the collection.**: It is 1800 s, the same limit as the run, so a collection that hangs uses the time of the run and the outer limit fires first. -- **Lower the limit of 50 tests, or size the workers by the time of the tests.**: The 52-test module above ran in 8 s serially and in 22 s with the collection and 4 workers, so a count of tests is a poor sign of the work. That is a change of the rule of #4472 and needs a source of test times, which the project does not keep; the issue does not ask for it. +- **Lower the limit of 50 tests, or size the workers by the time of the tests.**: The 52-test module above ran in 8 s serially and in 22 s with the collection and 4 workers, so a count of tests is a poor sign of the work. That is a change of the rule of #4472 and needs a source of test times, which the project does not keep; the issue does not ask for it, and #5612 tracks it. ## Unchanged references diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/proposal.md similarity index 100% rename from openspec/changes/5606-narrowed-test-workers-fall-back-and/proposal.md rename to openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/proposal.md diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md similarity index 100% rename from openspec/changes/5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md rename to openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/specs/ci-test-workers/spec.md diff --git a/openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/tasks.md similarity index 86% rename from openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md rename to openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/tasks.md index 4056a6283a..f7a48eec15 100644 --- a/openspec/changes/5606-narrowed-test-workers-fall-back-and/tasks.md +++ b/openspec/changes/archive/2026-11-14-5606-narrowed-test-workers-fall-back-and/tasks.md @@ -4,7 +4,7 @@ Kind: behavior. Reads: `src/devops_cli/commands/ci.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/roadmap/implement/implement_size.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/help.py`, `docs/commands/ci.md`, `tests/commands/test_test_selection.py`. -- [x] 1.1 Write the failing cases first in `tests/commands/test_test_selection.py`: the 7 modules of #4472 with a collection that exits 1 without `--snapshot-warn-unused` and 0 with it run on `DEFAULT_CI_TEST_NARROWED_WORKERS` with no warning; `PYTEST_XDIST_AUTO_NUM_WORKERS` of 1 and 0 run `-n 0` with no collection, 2 runs `-n 2`, and 16 and a value that is no number run on 4; 51 target modules with no `-k` make no collection, and 50 modules or a `-k` filter collect; a failed collection with `-k noop[/x]` exits 0 and shows `noop[/x]`; the timeout warning names `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`, read through `defaults` in the body of the test; and the collection argv holds `--snapshot-warn-unused`. Add the fixture `no_worker_bound` to `pytestmark`, so a runner pod's bound does not reach the other cases +- [x] 1.1 Write the failing cases first in `tests/commands/test_test_selection.py`: the 7 modules of #4472 with a collection that exits 1 without `--snapshot-warn-unused` and 0 with it run on `DEFAULT_CI_TEST_NARROWED_WORKERS` with no warning; `PYTEST_XDIST_AUTO_NUM_WORKERS` of 1 and 0 run `-n 0` with no collection, 2 runs `-n 2`, and 16 and a value that is no number run on 4; 51 target modules with no `-k` make no collection, and 50 modules or a `-k` filter collect; a failed collection with `-k noop[/x]` exits 0 and shows `noop[/x]`; the collection call gets `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` as its timeout, and the timeout warning names it, both read through `defaults` in the body of the test; and the collection argv holds `--snapshot-warn-unused`. Add the fixture `no_worker_bound` to `pytestmark`, so a runner pod's bound does not reach the other cases - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py` fails on the base - [x] 1.2 Add `_SNAPSHOT_WARN_UNUSED` to `src/devops_cli/commands/ci.py` and give it to `_collection_cmd` and the shard command. Add `_worker_cap`, which bounds `DEFAULT_CI_TEST_NARROWED_WORKERS` with `PYTEST_XDIST_AUTO_NUM_WORKERS`, and give `_narrowed_workers(targets, keyword)` the two skips of the collection. Add `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS` (120 s) with the measured times to `src/devops_cli/config/defaults.py`, use it in `_collected_test_count`, and print its warning with `safe=True`. Add the bound to the `-n` help in `src/devops_cli/lang/en/help.py`, and regenerate `docs/commands/ci.md` with `uv run devops docs generate` - Verification: `$ uv run devops ci test tests/commands/test_test_selection.py tests/commands/test_ci.py tests/commands/test_ci_repeat.py` passes @@ -25,4 +25,5 @@ Kind: other. Reads: `docs/TESTING.md`, `src/devops_cli/ai/knowledge_base/devops_ ## Workflow follow-up +- The rule of 50 collected tests stays: a 52-test module of fast tests runs 2.5 times slower on 4 workers than serially on 16 CPUs (#5612). - Pending a person: review the diff in tuicr (tuicr -r ..HEAD). diff --git a/openspec/specs/ci-test-workers/spec.md b/openspec/specs/ci-test-workers/spec.md index 276e1015a1..f1a441ee0f 100644 --- a/openspec/specs/ci-test-workers/spec.md +++ b/openspec/specs/ci-test-workers/spec.md @@ -6,12 +6,20 @@ How `devops ci test` chooses the number of pytest workers for a run that given p ## 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. +`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. It SHALL start no more workers than the worker cap: `DEFAULT_CI_TEST_NARROWED_WORKERS`, or the value of `PYTEST_XDIST_AUTO_NUM_WORKERS` when that value is a smaller whole number. It SHALL ignore a value that is no whole number, as xdist does. #### 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`. +#### Scenario: Worker bound of a pod with 2 CPUs +- **WHEN** `PYTEST_XDIST_AUTO_NUM_WORKERS` is 2 and the 7 selected files collect 399 tests. +- **THEN** The command runs pytest with `-n 2`. + +#### Scenario: Selected module with unused snapshots +- **WHEN** The 7 selected files collect 422 tests, and the collection exits 1 without `--snapshot-warn-unused` and 0 with it, as syrupy does for a selected module that has snapshots. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and prints no collection warning. + ### 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. @@ -27,19 +35,31 @@ The worker decision SHALL count only the tests that match the `-k` filter. - **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. +The command MUST collect tests with the same target list and keyword filter that it passes to pytest, and with `--snapshot-warn-unused`, so that the snapshots that a collection leaves unused do not fail it. #### 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`. +- **THEN** The collection command holds both file paths, `-k slow` and `--snapshot-warn-unused`. ### 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. +When pytest collection fails or runs past `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`, the command SHALL fall back to the file-count rule and continue: up to `DEFAULT_CI_TEST_SERIAL_MAX_FILES` test modules run with `-n 0`, and more modules run on the worker cap. The warning SHALL show the collection command as text, not as Rich markup. An exit code 5, which says that no test was collected, is a count of zero and no failure. + +#### Scenario: Collection error at the file bound +- **WHEN** The collection command exits with code 3 for a selection of 12 test files. +- **THEN** The command runs pytest with `-n 0` and prints a warning that names the collection 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: Collection timeout +- **WHEN** The collection command runs past its timeout for a selection of 13 test files. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and prints a warning that names a timeout of `DEFAULT_CI_TEST_COLLECTION_TIMEOUT_SECONDS`. + +#### Scenario: Brackets in the keyword filter +- **WHEN** The collection command exits with code 3 and the caller passes `-k noop[/x]`. +- **THEN** The command exits 0 and the warning shows `noop[/x]` as it is. + #### 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. @@ -57,3 +77,25 @@ 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. + +### Requirement: Collection only when its count can change the workers +The command SHALL start no collection when the count cannot change the worker count. A worker cap of 1 or less SHALL run pytest with `-n 0`. More than `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` target modules with no `-k` filter SHALL run on the worker cap, because each module collects one test at least. + +#### Scenario: Worker bound of a pod with 1 CPU +- **WHEN** `PYTEST_XDIST_AUTO_NUM_WORKERS` is 1 and the 7 selected files collect 399 tests. +- **THEN** The command runs pytest with `-n 0` and makes no collection call. + +#### Scenario: More target modules than the test limit +- **WHEN** The caller passes `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` + 1 test files and no `-k`. +- **THEN** The command runs pytest with `-n DEFAULT_CI_TEST_NARROWED_WORKERS` and makes no collection call. + +#### Scenario: More target modules than the test limit with a filter +- **WHEN** The caller passes `DEFAULT_CI_TEST_SERIAL_MAX_TESTS` + 1 test files and `-k noop`. +- **THEN** The command makes one collection call. + +### Requirement: Repeat runs make no collection +A `--repeat` run SHALL run each repeat with `-n 0` and make no collection call. + +#### Scenario: Repeat run +- **WHEN** The caller passes `--repeat 2 --seed 1` and one test file. +- **THEN** The command makes no collection call.