Repository navigation
Description
Problem Statement
devops ci test PATHS runs only the tests it thinks cover the given files. The devops-ci-test-changed pre-commit hook calls it with the staged Python files (.pre-commit-config.yaml:62-68, types: [python] at :67). The pre-push hook (:70-77), the aggregate gate (commands/ci.py:373-390) and CI (.github/workflows/ci.yml:97) all run the whole suite.
The selection is based on text, not coverage. select_tests_for_sources (core/test_selection.py:112-165) takes the union of conventional test file names and a regex grep for imports of the changed module. The original body said "coverage data already records which tests touch which modules". It does not:
- No gate or CI command passes
--cov-context. The flag appears only in thecoverage_index.pydocstring, its test fixture and the roadmap (grep -rn cov-context src tests .github). - The gate deletes
.data/.coverage*(_clean_coverage_artifacts,ci.py:222-242, called at:316,:373and:473).
#446 measured the grep against per-test coverage, over 387 source files and 317 test files: mean recall 65.0%, median 66.7%, 10th percentile 11% (core/coverage_index.py:6-11). This was not re-measured. It is not known which coverage core that run used (see Coverage core below). If it used the default, its covering counts are low.
At ef21785 the grep picks 4 test files for core/cli.py, where #446 counted 38 covering files. It picks none for output/formatters/tables.py or ai/text_utils.py. An unmapped source escalates to the full suite only when nothing at all was selected (_resolve_test_targets, ci.py:749-776; --fallback on by default at :807-809). Otherwise it is only reported. So the risk is a partial pick: the hook passes after running only a small part of what exercises the change.
#446 delivered core/coverage_index.py in v0.2.23 (added by ea49d6e). It does three things:
- It builds a reverse index (source file → test files that executed it) from a
--cov-context=testdatabase (:158-200). - It stores the index with a format version (
INDEX_FORMAT_VERSION = 1,:42;save_index/load_index,:203-227). - It selects tests from the index (
select_from_index,:257-297).
It falls back to a full run when:
- the index is absent or in an older format (
:217-218,:247-248); - a test file was added since the build (
staleness_reason,:240-254); conftest.py,pyproject.toml,uv.lockor.python-versionchanged (_FULL_RUN_TRIGGERS,:46;:273-276);- a changed path is outside
src/(:287-290); - a changed source is not in the index (
:292-294).
Nothing outside tests/test_coverage_index.py calls it (grep -rn coverage_index src finds only the module itself).
The wiring has to close these gaps:
- Coverage core. The locked coverage 7.16.1 (
uv.lock:501-502) uses thesysmoncore by default on CPython 3.14 (SYSMON_DEFAULT,coverage/env.py:56; chosen atcoverage/core.py:97-100)..python-versionis 3.14.7.- pytest-cov 7.1.0 (
uv.lock:2649-2650)--cov-context=testcallsCoverage.switch_contextfor each test phase (pytest_cov/plugin.py:440-450). - Under
sysmonthat call only warnsno-sysmon-context(coverage/control.py:802-808;supports_dynamic_contexts = False,coverage/core.py:120). sysmonalso stops reporting a line after its first hit (sysmon_line_linesreturnsDISABLE,coverage/sysmon.py:418-430).- Reproduced in a scratch project where three test files call one function. Under the default core the database credits only the first test file. With
COVERAGE_CORE=ctraceit credits all three. - So
--cov-context=teston its own gives first-caller credit for nearly every line. - coverage picks
ctraceby itself only for config-driven contexts ([run] dynamic_context;coverage/core.py:78-79,control.py:596), which pytest-cov does not use, and which as a config setting would reach every run.
- pytest-cov 7.1.0 (
- Cost of
ctrace. The test subset wastests/test_ci.py,test_ci_cache.py,test_output.pyandtest_test_selection.py(114 tests), run serially with--cov=srcat load 3-5.ctracewith contexts took 20.6-23.7 s. The default core took 14.0-15.1 s.- That is 31-57% more wall time and 23-45% more CPU time.
- The full gate takes about 2 minutes on ext4 (fix(ci): devops ci quality gate finishes within five minutes #748, delivered), and a gate change may add at most 5% to its test step. So the gate cannot build the index.
- Environment isolation. Subprocesses get a filtered environment (
DEFAULT_ALLOWED_ENV_VARS,core/process.py:27-84;build_subprocess_env,:123-146). ACOVERAGE_COREset in the shell never reaches pytest.run_subprocesstakes an explicitenv(:218-230), but_runinci.py:172-185does not pass one, so the build must add it. - Staleness. The only staleness check is for added test files. A file edited since the build can create a test→module link the index does not have. A later change to that module then selects too few tests.
- Build speed. The builder calls
Path.resolve()once per database row (_normalize_source_path,coverage_index.py:98-115, called at:182). One call took 378 µs on this host under load (load average 24 on 16 cores). A full-suite context database has hundreds of thousands of (file, context) rows. - Removed test files. The index lists test files as they stood at build time, and
select_from_indexreturns them unchecked (:295). A test file deleted or renamed since the build reaches pytest, which exits 4 (file not found) and fails the hook. Confirmed in a scratch project with the locked pytest 9.1.1 (uv.lock:2621-2622). - Import-time and first-caller code. Even under
ctrace, the index is exact only for code that runs inside a test's own context:- Import-time lines have the empty context, and the builder drops them (
WHERE c.context != '',:176). Example:new_typer(core/cli.py:172), which 44 command modules call at import. - A session fixture or a memoized function (43
lru_cache/cacheuses insrc) is credited only to the first test that reaches it on each xdist worker. Example: the autouse session fixtureregister_test_mock_provider(tests/conftest.py:57-60). - The module docstring (
:18-21) claims "full recall by construction", which overstates this.
- Import-time lines have the empty context, and the builder drops them (
- Non-test files under
tests/. The text-based path passes any file undertests/straight to pytest (test_selection.py:132-139). With onlytests/conftest.pyor a helper module staged, pytest collects nothing and exits 5, which fails the hook. Confirmed in a scratch project with the locked pytest 9.1.1.
Proposed Solution
- Build on demand.
- Add
--build-indextodevops ci coverage(ci.py:840-871).- It runs the argv
devops ci coverageruns without the flag (today the literal list at:857-869; after refactor(ci): github ci runs the gate throughdevops cifrom one check table #843, which lands first, the check table's test row) plus--cov-context=test, withCOVERAGE_CORE=ctracepassed in that subprocess's environment throughrun_subprocess(env=...). - It always runs the whole suite and takes no test paths or filters.
- It runs the argv
- Before pytest starts, record the content hash of every Python file under
src/andtests/, plus the four trigger files.- Use the git blob map that
compute_workspace_fingerprintalready computes (ci/cache.py:255-268:_index_blob_hashesplus_git_blob_hashesfor the divergent paths), moved into one shared helper that both callers use.
- Use the git blob map that
- After a passing run:
- Build the index from
.data/.coverage([tool.coverage.run] data_file,pyproject.toml:108-110). - Take the hashes again. Save only if they match. Otherwise print the files that changed, save nothing and exit 1 (key question 15).
- Write the file atomically (temp file plus
os.replace). - Print the time spent building and saving.
- Build the index from
- In the builder, collapse contexts to test files in SQL, and normalize each distinct
file.pathonce. - None of these change: the aggregate gate,
devops ci coveragewithout the flag, and CI.
- Add
- Store.
- Keep one index per worktree, in the CI cache's directory and keyed by worktree the same way (
resolve_ci_cache_path,ci/cache.py:65-88:data.cache_dir, default.data/cache, file name suffixed with the worktree hash).devops workspace clean(clean_workspace,commands/workspace.py:289) prunescache/under the data directory (core/cleanup.py:184-194). - The stored file adds the hashes recorded at build time and a build timestamp.
- Bump
INDEX_FORMAT_VERSIONto 2, so a version-1 file reads as absent.
- Keep one index per worktree, in the CI cache's directory and keyed by worktree the same way (
- Select.
devops ci test PATHSbuilds a changed set from:- the given paths;
- every Python file under
src/ortests/, and every trigger file, that was added, removed or changed since the build (current blob map against the stored hashes).
- Other paths stay ignored, as today (
test_selection.py:141-143). - If the set has a trigger file:
- run the full suite, and name the file and
devops ci coverage --build-index; - with
--no-fallback, exit 1 and name the file.
- run the full suite, and name the file and
- Otherwise, map each path:
- a test file that exists selects itself;
- a removed path under
tests/selects nothing; - a non-test module under
tests/selects the test files that import it; - a
src/file in the index selects its covering tests; - any other
src/file goes to today's text-based selector.
- Only paths under
src/andtests/are sent toselect_from_index. - Drop selected test files that no longer exist.
- A source that nothing maps is reported. Today's rule still applies: with
--fallback, the full suite runs only when nothing at all was selected (ci.py:764-776). - Drop the rule that a test file added since the build invalidates the index (
staleness_reason,coverage_index.py:240-254). The added file is in the changed set and selects itself. - Each run prints:
- which selector answered for each source;
- the index's age;
- how many files changed since it was built.
- With no index, the output also prints the command that builds one.
- Text-based path.
conftest.pyfollows the trigger rule.- A non-test module under
tests/maps to the test files that import it (_find_tests_importing_helper,coverage_index.py:79-95). - If none import it, it is reported as unmapped.
- Docstring. Correct the module docstring (
coverage_index.py:1-22). It must say that the index has to be built under thectracecore, and state the import-time and first-caller limits. - Help and docs. Update the
devops ci testanddevops ci coveragehelp text (lang/en/help.py:498-507;CIMessagesinlang/en/messages.py:702-716), and regeneratedocs/commands/ci.mdwithdevops docs generatesodevops docs checkpasses. - Task file.
docs/agent/tasks/task-406-deterministic-test-selection-from-changed-sources.mdexists withStatus: Backlog,Milestone: v0.2.25and the original "coverage data already records" text. The delivering PR rewrites it asDonewith the criteria below; the person-run checks arePending a person:bullets with the exact commands. Changelog entry goes inchangelog.d/406.md.
Scope
Files: src/devops_cli/commands/ci.py (test, coverage, _resolve_test_targets, _run env passing), src/devops_cli/core/coverage_index.py, src/devops_cli/core/test_selection.py, src/devops_cli/ci/cache.py (shared content-hash helper), src/devops_cli/lang/en/help.py, src/devops_cli/lang/en/messages.py, docs/commands/ci.md, tests/test_coverage_index.py, tests/test_test_selection.py (and tests/test_ci.py for the gate argv), the task file, changelog.d/406.md.
Constraints:
- The index is advisory only. It narrows only
devops ci test PATHS. The aggregate gate, the pre-push hook, the gate cache and CI keep the full suite, and none of them changes. - No change to the gate's argv or cost.
- New tests take at most 1 s in total. They stay offline and do not run real coverage, a cluster or real scanners; use the sqlite fixture instead.
- No new dependency. Structural tuple equality assertions (AGENTS.md:101).
- No legacy shims: an old index reads as absent, and there is no migration code.
CHANGELOG.mdanddocs/ROADMAP.mdare not edited.
Effort: high. One pull request, landing after #843 (sequence #832 -> #843 -> #406).
Key Questions
- Where is the index built? Only by
devops ci coverage --build-index.- Not in the gate. Contexts need the
ctracecore, which measured 31-57% slower on a test subset, against a 5% allowance for a gate change. - This departs from the roadmap's older entry "generate the index as part of the full run" (
docs/ROADMAP.md:852); the item's own entry (:1114-1116) already says the build is on demand. devops ci testnever builds it.- If a later coverage release supports contexts under
sysmon, building in the gate is a new item with its own measurement.
- Not in the gate. Contexts need the
- Why pass
COVERAGE_CORE=ctracein the environment instead of settingcorein[tool.coverage.run]? The config setting would slow every coverage run, including the gate and CI. The variable reaches only the build: coverage copiesCOVERAGE_COREinto[run] corewhen it loads its configuration (coverage/config.py:717-721);coverage/core.py:34is the fallback read taken only when the C tracer cannot be imported. Criterion 10's warning check shows if it stops working. - Why not use pytest-testmon? testmon turns its own tracking off when coverage is running. It would need a second full run without coverage. The coverage run already produces the data, and no new dependency is needed (neither testmon nor diff-cover is locked today).
- Per worktree or shared? Per worktree, keyed like the CI cache. The index describes one tree, and
devops workspace cleanprunes it along with the cache. - When is the index stale? Only a format-version mismatch makes the whole index unusable. Files changed since the build are added to the changed set instead.
- This handles links created by edited Python code: any new test→module path starts at an edited file, which is then in the set.
- Removed files are in the set too, and a removed test file is never passed to pytest.
- What about non-Python files and paths outside
src/andtests/? They stay ignored, as today (test_selection.py:141-143).- The hook passes only Python files (
.pre-commit-config.yaml:67). - The repository has no tracked Python files outside
src/andtests/(git ls-files '*.py'). - The pre-push gate runs everything.
- The hook passes only Python files (
- Do the pre-push gate, the gate cache or CI narrow their runs? No. They keep the full suite, and fix(ci): the gate cache certifies only the tree it checked #838 rules out a subset shortcut in the cache.
- Should the selection size be capped to keep commits fast? No cap. The output prints the count, and criterion 11 records the spread. The
-nchoice for small selections belongs to the roadmap's "Serial Narrowed Test Runs and Per-File Latency Attribution" entry (docs/ROADMAP.md:1019). - What about import-time code and first-caller credit? Out of scope here.
- Selection is only advisory, because the pre-push gate runs the full suite.
- The docstring states the limit.
- The split-off fix(ci): coverage index treats module-level and import-time changes as unindexed #884 makes these cases fall back before the index is ever used as the only run.
- Should the index be built after a failed run? No. A failing run can skip a whole test file at collection, so that file's links would be missing.
- With no index, should
devops ci testfall back to the full suite or to the text-based selector? The text-based selector, as the roadmap says (docs/ROADMAP.md:852,:1115). The original body asked for a full-suite fallback. Selection is advisory and the pre-push gate runs everything, so falling back to today's behaviour loses nothing. - Should a source that nothing maps force the full suite when other sources were selected? No. Keep today's rule (
ci.py:764-776): the source is reported, and the full suite runs only when nothing at all was selected. - Who builds the index, and when? A person or agent, whenever they want narrow commits.
- An old index stays safe: every file changed since the build joins the changed set, so an old index only selects more.
devops ci testprints the index's age and the number of changed files, and names the rebuild command.
- Should the roadmap be updated? No. Since feat(github): github-sourced roadmap, migration and generated roadmap view (
devops roadmap migrate,render) #739 GitHub is the roadmap's source anddevops roadmap renderregeneratesdocs/ROADMAP.md(its header;docs/commands/roadmap.md), and an item pull request never edits that file (docs/agent/tasks/README.md, rule 5). The older entry at:848-853and this item's entry at:1113-1116are the render's concern. - What does
--build-indexreturn when the tree changed during the run and nothing was saved? Exit 1, naming the changed files (owner decision, 2026-10-02). The flag is run on demand for the index; an exit 0 would hide that the nextdevops ci testwill still say "no index". The test run's own result is still printed. The plaindevops ci coverageexit behaviour is unchanged. - How does this compose with refactor(ci): github ci runs the gate through
devops cifrom one check table #843, which is in the same release and makesdevops ci coveragerun the check table's test row? refactor(ci): github ci runs the gate throughdevops cifrom one check table #843 lands first (sequence refactor(ci): ci installs nothing on the runner, and live bubblewrap tests skip where bwrap is missing #832 -> refactor(ci): github ci runs the gate throughdevops cifrom one check table #843 -> feat(cli):devops ci testselects tests from a coverage index built on demand bydevops ci coverage --build-index#406), and this item rebases on it:--build-indexadds--cov-context=testto the table's test row, and refactor(ci): github ci runs the gate throughdevops cifrom one check table #843's parity test keeps comparingcoveragewithout--build-index. Criterion 1 is worded against the argvcoverageruns without the flag, so it holds against the table as well as against today's literal list.
Acceptance Criteria
- 1. The build command is exact. Unit tests in
tests/test_test_selection.py(or a newtests/test_ci_build_index.py) withdevops_cli.commands.ci._runandrun_subprocesspatched, using structural tuple assertions on(argv, env):devops ci coverage --build-indexruns pytest with the argvdevops ci coverageruns without the flag plus--cov-context=test, and withCOVERAGE_CORE=ctracein theenvpassed torun_subprocess; without the flag, the argv and environment are unchanged; the gate's test step argv (ci.py:373-390) is unchanged, asserted intests/test_ci.pybeside_run_all_checks_async(:493-513). - 2. The index is saved only after a clean run. Unit tests in a
tmp_pathgit repo, with a patched runner that writes a minimal context database (the shape of_coverage_db,tests/test_coverage_index.py:20-35): a passing run saves the index at the per-worktree path fromresolve_ci_cache_path; a failing run saves nothing; a runner that edits a trackedsrc/file during the run saves nothing, prints the changed file, and exits 1 (key question 15). - 3. The builder normalizes once per distinct path. Unit test: a database with 2,000 rows over 3 distinct paths calls the normalizer 3 times (spy on
_normalize_source_path) and gives the same index as before. - 4. With an index mapping
src/a.pytotests/test_a.pyandtests/test_far.py,devops ci test src/a.pyruns pytest with exactly those two targets and names the coverage index in its output.CliRunnerwithdevops_cli.commands.ci._runand_get_project_rootpatched, astests/test_test_selection.py:152-162does. - 5. Changes since the build are handled. Unit tests: after the build, with
src/b.pyedited,devops ci test src/a.pyalso selects the tests that coversrc/b.py; a newly addedtests/test_new.pyis selected and causes no fallback; withtests/test_far.pydeleted after the build,devops ci test src/a.pypasses onlytests/test_a.pyto pytest. - 6. Trigger files force a full run. Unit tests:
devops ci test tests/conftest.pyruns pytest with no targets, both with and without an index; with--no-fallbackit exits 1 and namestests/conftest.py; with an index andpyproject.tomlchanged since the build,devops ci test src/a.pyruns pytest with no targets and namespyproject.toml. - 7. With no index,
devops ci test tests/helper.pyruns the test files that import the helper, and never passestests/helper.pyto pytest. Unit test. - 8. The text-based fallback works per source. Unit tests: with no index, a version-1 index, or a source missing from the index, the output says the text-based selector answered for that source; with an index containing
src/a.pybut notsrc/c.py,devops ci test src/a.py src/c.pyruns the index's tests forsrc/a.pyplus the text-based selector's tests forsrc/c.py; the existing cases intests/test_test_selection.pyandtests/test_coverage_index.py(34 tests between them at HEAD) still pass, changed only where the staleness rule changed (test_a_new_test_file_invalidates_the_index,:134, andtest_an_unmapped_test_helper_forces_a_full_run,:245). Shown byuv run pytest -n 0 tests/test_test_selection.py tests/test_coverage_index.py. - 9. New and changed tests take at most 1 s together on one worker (setup, call and teardown), not counting the session fixture setup that the first test in any run pays (2.6-7.4 s measured at HEAD, host-dependent). Shown by
uv run pytest -n 0 --durations=0 tests/test_coverage_index.py tests/test_test_selection.py(plus any new test file); baseline at HEAD is 34 tests in 5-10 s wall time, slowest call 0.16-0.31 s. The result is recorded in the task file. - 10. The real build works.
Pending a person:runuv run devops ci coverage --build-indexonce on ext4 and record in the task file: that the output has nono-sysmon-contextwarning; the build-and-save time the command prints, which must be 5 s or less; how many test files the index and the text-based selector each pick forcore/cli.py,output/formatters/tables.pyandai/text_utils.py. - 11. The task file records selection sizes.
Pending a person:using the index from criterion 10 and a scratch script that is not committed, for each of the last 20 first-parent commits on the release branch, count the test files each selector picks for that commit's changedsrc/files (git diff --name-only <sha>~1 <sha> -- src). - 12.
uv run devops docs checkpasses afteruv run devops docs generateregeneratesdocs/commands/ci.mdwith the new flag and help text;uv run devops cipasses;changelog.d/406.mdis present and neitherCHANGELOG.mdnordocs/ROADMAP.mdis changed (devops pr check-readiness).
Out of Scope
- Building the index in the gate, the pre-push hook, the gate cache or CI (key questions 1 and 7).
- Import-time and first-caller code falling back before the index is used: fix(ci): coverage index treats module-level and import-time changes as unindexed #884 (split off, backlog).
- A cap on selection size and the
-nchoice for small selections: roadmap "Serial Narrowed Test Runs and Per-File Latency Attribution" (docs/ROADMAP.md:1019). - Re-measuring feat(ci): build the covering-test index from coverage instead of guessing #446's recall figures.
.data/coverage.xmland diff-cover (feat(ci): changed-line coverage on pull requests (diff-cover) #850).- Any edit to
CHANGELOG.mdordocs/ROADMAP.md.
Dependencies
Sequence in v0.2.26: #832 -> #843 -> #406. This item keeps v0.2.26 for now; whether it moves to v0.2.28 is decided at the v0.2.25 cut. If it moves, it lands after the v0.2.27 chain #885 -> #838 -> #858, so none of those items rebases on it and every "whichever lands second" line below resolves to this item rebasing.
- refactor(ci): github ci runs the gate through
devops cifrom one check table #843 (v0.2.26): lands before this item. It moves the gate argv into one check table and makesdevops ci coveragerun the table's test row; this item rebases on it and adds--build-indexto that row (key question 16). - refactor(ci): ci installs nothing on the runner, and live bubblewrap tests skip where bwrap is missing #832 (v0.2.26): lands before refactor(ci): github ci runs the gate through
devops cifrom one check table #843. It touches.github/workflows/ci.yml,pyproject.toml(a pytest marker) and sandbox tests only; itspyproject.tomlchange is a runtime trigger for the index, not a shared edit. - fix(ci):
devops cichecks run for real under their own--dry-run#885 (v0.2.27): adds dry-run guards to_run(ci.py:172-185) and_execute_check_async, and a guard around the coverage cleanup; this item changes_run's env passing, so whichever lands second rebases. - fix(ci): the gate cache certifies only the tree it checked #838 (v0.2.27): takes the workspace fingerprint before and after the gate in
ci/cache.py; whichever lands second rebases the shared content-hash helper. fix(ci): the gate cache certifies only the tree it checked #838 also rules out a subset shortcut in the cache (key question 7). - fix(cli): cli start-up imports no telemetry when the bridge is off, and timing tests stop asserting host speed #858 (v0.2.27): picks one pytest worker setting for the gate's test row (
ci.py:374-376). This item does not change the gate argv, but criterion 1 asserts it; whichever lands second updates that assertion. - Related, not in the planned releases: feat(ci): build the covering-test index from coverage instead of guessing #446 (delivered the index module, v0.2.23); fix(ci): devops ci quality gate finishes within five minutes #748 (delivered: the gate's 5-minute budget); fix(test): the test network guard refuses loopback connects to services the test did not start #837 (delivered, task file Done; edited
tests/conftest.py); feat(ci): shuffled repeat runs of a pull request's changed test files #852 (backlog, depends on this item); feat(ci): changed-line coverage on pull requests (diff-cover) #850 (backlog, reads.data/coverage.xml); fix(ci): coverage index treats module-level and import-time changes as unindexed #884 (backlog, split-off). - Roadmap entries without issues that build on this item: "Change-Triggered Gate Re-Run With Delta Scorecard" (
docs/ROADMAP.md:1007) and "Serial Narrowed Test Runs and Per-File Latency Attribution" (:1019).
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
docs(roadmap): per-check CI cache scoping has no benefit and is unsafe (
feat(release): v0.2.23 (#681)
dan-petty commentedon Oct 1, 2026
Moved from v0.2.25 to v0.2.26 to make room for the seven P1 items left open in the shipped v0.2.23, which were committed earlier. The roadmap-job items placed in v0.2.25 stay, and this item is among the oldest of the rest.
[-]feat(cli): deterministic test selection from changed sources[/-][+]feat(cli): `devops ci test` selects tests from a coverage index built by the full gate[/+][-]feat(cli): `devops ci test` selects tests from a coverage index built by the full gate[/-][+]feat(cli): `devops ci test` selects tests from a coverage index built on demand by `devops ci coverage --build-index`[/+]feat(ci): select tests from on-demand coverage reverse index (#406) (#…
feat(release): v0.2.26 (#1178)
feat(test): devops test and devops ci test choose tests through one s…
feat(release): v0.2.37 (#1720)