Skip to content

feat(cli): devops ci test selects tests from a coverage index built on demand by devops ci coverage --build-index #406

Closed

Description

@dan-petty

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 the coverage_index.py docstring, 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, :373 and :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=test database (: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.lock or .python-version changed (_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 the sysmon core by default on CPython 3.14 (SYSMON_DEFAULT, coverage/env.py:56; chosen at coverage/core.py:97-100). .python-version is 3.14.7.
    • pytest-cov 7.1.0 (uv.lock:2649-2650) --cov-context=test calls Coverage.switch_context for each test phase (pytest_cov/plugin.py:440-450).
    • Under sysmon that call only warns no-sysmon-context (coverage/control.py:802-808; supports_dynamic_contexts = False, coverage/core.py:120).
    • sysmon also stops reporting a line after its first hit (sysmon_line_lines returns DISABLE, 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=ctrace it credits all three.
    • So --cov-context=test on its own gives first-caller credit for nearly every line.
    • coverage picks ctrace by 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.
  • Cost of ctrace. The test subset was tests/test_ci.py, test_ci_cache.py, test_output.py and test_test_selection.py (114 tests), run serially with --cov=src at load 3-5.
    • ctrace with 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). A COVERAGE_CORE set in the shell never reaches pytest. run_subprocess takes an explicit env (:218-230), but _run in ci.py:172-185 does 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_index returns 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/cache uses in src) is credited only to the first test that reaches it on each xdist worker. Example: the autouse session fixture register_test_mock_provider (tests/conftest.py:57-60).
    • The module docstring (:18-21) claims "full recall by construction", which overstates this.
  • Non-test files under tests/. The text-based path passes any file under tests/ straight to pytest (test_selection.py:132-139). With only tests/conftest.py or 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

  1. Build on demand.
    • Add --build-index to devops ci coverage (ci.py:840-871).
      • It runs the argv devops ci coverage runs without the flag (today the literal list at :857-869; after refactor(ci): github ci runs the gate through devops ci from one check table #843, which lands first, the check table's test row) plus --cov-context=test, with COVERAGE_CORE=ctrace passed in that subprocess's environment through run_subprocess(env=...).
      • It always runs the whole suite and takes no test paths or filters.
    • Before pytest starts, record the content hash of every Python file under src/ and tests/, plus the four trigger files.
      • Use the git blob map that compute_workspace_fingerprint already computes (ci/cache.py:255-268: _index_blob_hashes plus _git_blob_hashes for the divergent paths), moved into one shared helper that both callers use.
    • 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.
    • In the builder, collapse contexts to test files in SQL, and normalize each distinct file.path once.
    • None of these change: the aggregate gate, devops ci coverage without the flag, and CI.
  2. 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) prunes cache/ 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_VERSION to 2, so a version-1 file reads as absent.
  3. Select.
    • devops ci test PATHS builds a changed set from:
      • the given paths;
      • every Python file under src/ or tests/, 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.
    • 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/ and tests/ are sent to select_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.
  4. Text-based path.
    • conftest.py follows 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.
  5. Docstring. Correct the module docstring (coverage_index.py:1-22). It must say that the index has to be built under the ctrace core, and state the import-time and first-caller limits.
  6. Help and docs. Update the devops ci test and devops ci coverage help text (lang/en/help.py:498-507; CIMessages in lang/en/messages.py:702-716), and regenerate docs/commands/ci.md with devops docs generate so devops docs check passes.
  7. Task file. docs/agent/tasks/task-406-deterministic-test-selection-from-changed-sources.md exists with Status: Backlog, Milestone: v0.2.25 and the original "coverage data already records" text. The delivering PR rewrites it as Done with the criteria below; the person-run checks are Pending a person: bullets with the exact commands. Changelog entry goes in changelog.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.md and docs/ROADMAP.md are not edited.

Effort: high. One pull request, landing after #843 (sequence #832 -> #843 -> #406).

Key Questions

  1. Where is the index built? Only by devops ci coverage --build-index.
    • Not in the gate. Contexts need the ctrace core, 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 test never builds it.
    • If a later coverage release supports contexts under sysmon, building in the gate is a new item with its own measurement.
  2. Why pass COVERAGE_CORE=ctrace in the environment instead of setting core in [tool.coverage.run]? The config setting would slow every coverage run, including the gate and CI. The variable reaches only the build: coverage copies COVERAGE_CORE into [run] core when it loads its configuration (coverage/config.py:717-721); coverage/core.py:34 is the fallback read taken only when the C tracer cannot be imported. Criterion 10's warning check shows if it stops working.
  3. 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).
  4. Per worktree or shared? Per worktree, keyed like the CI cache. The index describes one tree, and devops workspace clean prunes it along with the cache.
  5. 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.
  6. What about non-Python files and paths outside src/ and tests/? 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/ and tests/ (git ls-files '*.py').
    • The pre-push gate runs everything.
  7. 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.
  8. Should the selection size be capped to keep commits fast? No cap. The output prints the count, and criterion 11 records the spread. The -n choice for small selections belongs to the roadmap's "Serial Narrowed Test Runs and Per-File Latency Attribution" entry (docs/ROADMAP.md:1019).
  9. What about import-time code and first-caller credit? Out of scope here.
  10. 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.
  11. With no index, should devops ci test fall 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.
  12. 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.
  13. 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 test prints the index's age and the number of changed files, and names the rebuild command.
  14. 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 and devops roadmap render regenerates docs/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-853 and this item's entry at :1113-1116 are the render's concern.
  15. What does --build-index return 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 next devops ci test will still say "no index". The test run's own result is still printed. The plain devops ci coverage exit behaviour is unchanged.
  16. How does this compose with refactor(ci): github ci runs the gate through devops ci from one check table #843, which is in the same release and makes devops ci coverage run the check table's test row? refactor(ci): github ci runs the gate through devops ci from 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 through devops ci from one check table #843 -> feat(cli): devops ci test selects tests from a coverage index built on demand by devops ci coverage --build-index #406), and this item rebases on it: --build-index adds --cov-context=test to the table's test row, and refactor(ci): github ci runs the gate through devops ci from one check table #843's parity test keeps comparing coverage without --build-index. Criterion 1 is worded against the argv coverage runs 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 new tests/test_ci_build_index.py) with devops_cli.commands.ci._run and run_subprocess patched, using structural tuple assertions on (argv, env): devops ci coverage --build-index runs pytest with the argv devops ci coverage runs without the flag plus --cov-context=test, and with COVERAGE_CORE=ctrace in the env passed to run_subprocess; without the flag, the argv and environment are unchanged; the gate's test step argv (ci.py:373-390) is unchanged, asserted in tests/test_ci.py beside _run_all_checks_async (:493-513).
  • 2. The index is saved only after a clean run. Unit tests in a tmp_path git 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 from resolve_ci_cache_path; a failing run saves nothing; a runner that edits a tracked src/ 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.py to tests/test_a.py and tests/test_far.py, devops ci test src/a.py runs pytest with exactly those two targets and names the coverage index in its output. CliRunner with devops_cli.commands.ci._run and _get_project_root patched, as tests/test_test_selection.py:152-162 does.
  • 5. Changes since the build are handled. Unit tests: after the build, with src/b.py edited, devops ci test src/a.py also selects the tests that cover src/b.py; a newly added tests/test_new.py is selected and causes no fallback; with tests/test_far.py deleted after the build, devops ci test src/a.py passes only tests/test_a.py to pytest.
  • 6. Trigger files force a full run. Unit tests: devops ci test tests/conftest.py runs pytest with no targets, both with and without an index; with --no-fallback it exits 1 and names tests/conftest.py; with an index and pyproject.toml changed since the build, devops ci test src/a.py runs pytest with no targets and names pyproject.toml.
  • 7. With no index, devops ci test tests/helper.py runs the test files that import the helper, and never passes tests/helper.py to 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.py but not src/c.py, devops ci test src/a.py src/c.py runs the index's tests for src/a.py plus the text-based selector's tests for src/c.py; the existing cases in tests/test_test_selection.py and tests/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, and test_an_unmapped_test_helper_forces_a_full_run, :245). Shown by uv 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: run uv run devops ci coverage --build-index once on ext4 and record in the task file: that the output has no no-sysmon-context warning; 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 for core/cli.py, output/formatters/tables.py and ai/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 changed src/ files (git diff --name-only <sha>~1 <sha> -- src).
  • 12. uv run devops docs check passes after uv run devops docs generate regenerates docs/commands/ci.md with the new flag and help text; uv run devops ci passes; changelog.d/406.md is present and neither CHANGELOG.md nor docs/ROADMAP.md is changed (devops pr check-readiness).

Out of Scope

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.

Activity

  1. added this to the v0.2.23 milestone on Sep 22, 2026
  2. added
    type/feature
    scope/cli
    priority/p1-high
    on Sep 22, 2026
  3. modified the milestones: v0.2.23, v0.2.25 on Sep 24, 2026
  4. added a commit that references this issue on Sep 28, 2026
  5. modified the milestones: v0.2.25, v0.2.26 on Oct 1, 2026
  6. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    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.

  7. changed the title [-]feat(cli): deterministic test selection from changed sources[/-] [+]feat(cli): `devops ci test` selects tests from a coverage index built by the full gate[/+] on Oct 1, 2026
  8. changed the title [-]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`[/+] on Oct 2, 2026
  9. added
    status/in-progress
    on Oct 4, 2026
  10. added a commit that references this issue on Oct 4, 2026
  11. removed
    status/in-progress
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/clitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions