Skip to content

Run only the tests a PR can affect, keep coverage whole-repo - #1588

Open
jhnwu3 wants to merge 5 commits into
masterfrom
ci/affected-tests
Open

jhnwu3 wants to merge 5 commits into
masterfrom
ci/affected-tests

Conversation

@jhnwu3

@jhnwu3 jhnwu3 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Why

PR CI runs every test module (338 now) on every push, and that cost grows with each new dataset, model or task. Most PRs touch one leaf module.

What changes

Test selection. tools/select_tests.py maps changed files to the test modules that import them, transitively. It rebuilds the import graph from source on every run (about 3 s, nothing cached).

  • Names imported through re-exporting __init__s (from pyhealth.models import RNN) resolve to the module that defines them. Otherwise every test would depend on every file.
  • If a PR only adds or removes re-exports in an __init__.py, the selector picks just the importers of those names, so new-model and new-dataset PRs stay small.
  • Lazy __getattr__ imports, function-level imports and attribute access on module aliases are followed. Bare uses such as getattr(medcode, name) fall back to the whole package.
  • examples/ is part of the import graph, so tests that import an example (from examples.survival_pipeline import ...) are selected when it changes, and so are tests reached through examples that import pyhealth.
  • Config and data files, and files under docs/ and examples/, also map to the modules or tests that name them. Seven tests load an example script or check a docs page this way.
  • The job summary lists each selected test with the import chain that selected it.

Fail-safes.

  • Build and CI config, tests/base.py, conftest.py, anything import pyhealth loads, and unrecognised paths run the full suite. So does the full-ci label: add it, then re-run the job.
  • Partial runs first compile everything and import every subpackage the core tests use (today all but pyhealth.nlp, which the NLP job runs). This catches import-time errors in modules no selected test uses.
  • Master pushes, manual dispatches and a new weekly schedule always run everything.

Coverage stays whole-repo. Full runs on master upload .coverage as the coverage-baseline artifact (90 days). A PR finds the newest baseline its merge commit contains and selects tests against that same commit. tools/coverage_report.py then merges the two data sets:

  • Files changed since the baseline use this run's data only.
  • All other files take the union of both, since skipped tests depend on nothing that changed.

The total and per-file numbers match a full run. One exception: if a change makes an unchanged file lose coverage, the merge keeps the baseline's lines for it. Without a baseline, the PR runs everything.

Downstream.

  • coverage.yml: the comment now says "Ran N of M test modules…" (new field, strictly validated).
  • ai-review.yml: the coverage parser accepts the report step's new first line alongside the old one, so runs from before this merges still parse.
  • No labeled trigger. A run whose jobs are all skipped would become the PR's latest test run and block /review and /merge.

Expected effect

Replaying the last 60 master commits, each against its own tree:

  • The median PR runs 6% of test modules (mean 7%).
  • 5 PRs run none, and none need the full suite.
  • Timed against the latest full master run's per-module durations, the median PR's test job drops from about 18 min to about 2 min.
  • A new model typically runs 4–6 modules and a new dataset about 20.

Changes to shared modules (processors, medcode, utils) still select most tests. That's real: processors are looked up by name and code systems by getattr.

Verification

  • tests/core/test_select_tests.py: 22 selector tests on a synthetic repo, including examples imported as modules and the --github-output format, all passing.
  • tests/core/test_coverage_report.py: the merge rules on hand-built coverage data (union for unchanged files, fresh data only for changed ones, deleted ones dropped).
  • Coverage merge checked in a toy repo: selected tests plus the baseline gave the same total and per-file coverage as a full run.
  • The parsers in coverage.yml and ai-review.yml, run under Node, read the new output under both the new and old step headers.
  • Not yet verified: the real suite and the workflow on GitHub. This PR edits test.yml, so it runs the full suite and its coverage comment is suppressed by design. The first PRs after merge will also run everything until master's first full run saves a baseline.

Contributor-facing

docs/how_to_contribute.rst gets a "Which Tests CI Runs" section, and make testaffected runs the same selection locally.

🤖 Generated with Claude Code

PR CI ran every test module on every push. tools/select_tests.py now maps
the changed files to the test modules that import them, using an import
graph rebuilt from source on each run (~0.3 s, nothing stored). Names
imported through re-exporting package __init__s resolve to their defining
module, so a change to one model doesn't select every test that imports
from pyhealth.models. Build/CI config, tests/base.py, conftest.py, anything
`import pyhealth` loads, and unrecognised paths run everything, as does the
full-ci label. Partial runs first import every subpackage, which catches
import-time breakage in modules no selected test uses.

Coverage: full runs on master upload .coverage as an artifact; PR runs
merge their partial data with it (tools/coverage_report.py), so the total
and per-file numbers match a full run. Without a baseline, a PR runs
everything. coverage.yml notes how many tests ran; ai-review.yml accepts
the report step's new header alongside the old one.

Master, manual dispatches and a new weekly schedule always run everything.
Replaying the last 60 master commits, the median PR runs 7% of the suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jhnwu3 jhnwu3 added the status: manual Pending maintainer's review label Nov 23, 2026
@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Test Coverage

Coverage not available: this PR modifies .github/workflows/test.yml, so its coverage output is not reported.

Workflow run · ddb4f9e

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 43d00e6

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. Selecting only the tests a PR can affect, while keeping coverage whole-repo through a merged baseline, should make PR CI much cheaper as the suite grows. The design is thoughtful, with its fail-safes, import-chain summary and local make testaffected. It is close, but a few blocking problems remain.

To get this merged:

  1. Some tests read files that the selector ignores. IGNORE_PREFIXES drops examples/ and docs/. But tests/core/test_tcga_rna_seq.py imports example scripts, test_pbc_neural_fine_gray_example.py reads examples/pbc_neural_fine_gray/*, and test_processor_compatibility.py reads docs/api/processors/compatibility.rst. A PR that edits those files would skip those tests. Please make the selector map those paths to the tests that reference them, for example by using the same "modules naming the file" lookup it uses for config files. Alternatively, remove those paths from the ignore list. Also correct the claim in docs/how_to_contribute.rst that a docs-only change runs none, since it isn't true for that page.
  2. The OWNED_TREES entry "skills/" names a tree and a test module (tests.core.test_skills_install) that don't seem to exist in this repo. Please remove it, or fix it to point at something real, so the comment isn't misleading.
  3. tools/coverage_report.py sets the reported total, but its merge logic has no committed test. It was only checked in a toy repo. Please add a small test, for example one that builds two small coverage data files and checks the merged result. It should cover changed files taking only the fresh data, unchanged files taking the union, and deleted files being dropped. Coverage for tools/ isn't reported, so I couldn't check it against the 80% bar.

Optional suggestions:

  • The description says the smoke step imports "every subpackage", but smoke_imports only imports subpackages that the core tests use. Please align the wording or the code.
  • Strings such as mock.patch targets and registry names aren't followed. The docs mention this for getattr and registry lookups, and a short note on mock.patch would help too.
  • The workflow hasn't run on GitHub yet, as you noted. A maintainer should watch the first runs after merge.

Reviewed commit 43d00e6

jhnwu3 and others added 2 commits November 23, 2026 12:30
The pixi env may not ship a pytest script, and then a bare `pytest` resolves
to whatever virtualenv is next on PATH, running the tests under the wrong
interpreter. CI is unaffected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Files under docs/ and examples/ were ignored, but seven test modules
  load an example script or check a docs page. A change there now selects
  the modules naming both the tree and the file (usually none).
- Drop the skills/ OWNED_TREES entry: that tree and its test exist only on
  an older branch, not master.
- Factor the coverage merge into coverage_report.merge() and test it on
  hand-built data files: union for unchanged files, fresh data only for
  changed ones, deleted ones dropped. That test caught purge_files()
  leaving deleted files measured with no lines; the merge now copies the
  baseline's kept files instead.
- The import check covers the subpackages the core tests use, not every
  one; say so. Mention mock.patch targets among the string references
  selection can't follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit eff1153

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this contribution. Running only the tests a PR can affect, while keeping whole-repo coverage by merging with master's baseline, would cut CI time a lot. The fail-safes, the baseline lookup and the selector tests are well thought out.

To get this merged:

  • Examples imported as modules are skipped. In tools/select_tests.py, _classify sends examples/ and docs/ paths to graph.referencing("examples", "<file name>"). That needs the literal file name, such as survival_pipeline.py, to appear in the test source. tests/core/test_survival_pipeline.py and test_survival_benchmark.py use from examples.survival_pipeline import ... and from examples.survival_benchmark import run_baselines. Neither contains the .py file name, so changes to those examples select no tests. Please also match tests that import the example as a module (the dotted name, or the stem together with examples). Alternatively, give such files a fallback. Then add a case to test_select_tests.py for an example that a test imports with from examples.x import ....

Optional suggestions:

  • Confirm that branch coverage is off in pyproject.toml. The merge in coverage_report.py copies line data only, so branch data would be lost.
  • Add a test for main() and the --github-output format, because the workflow depends on them. For now they are checked only by hand.
  • Test coverage was unavailable, so I couldn't check it against the bar. The new files are under tools/ rather than pyhealth/, so the usual per-file check doesn't apply to them anyway.

The change doesn't touch the library's base classes or shared code. Once the examples case is fixed, it looks close to ready.

Reviewed commit eff1153

The AI review found that tests importing an example
(`from examples.survival_pipeline import ...`) were never selected, because
the examples/ rule only matched the literal file name. examples/ is now part
of the import graph, so those imports resolve like pyhealth's, including
examples importing each other and pyhealth.

Unresolved `from pkg import name` imports (namespace packages such as
examples/, or a deleted submodule) now also depend on `pkg.name`, so
deleting a submodule still selects its importers.

Adds selector tests for both, and for the --github-output format the
workflow reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 3a005ac

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: human review

Thank you for this PR. Running only the tests a change can affect, while keeping coverage whole-repo, should save a lot of CI time as the suite grows. The import-graph selection, the fail-safes and the baseline merge are well thought through. The PR is close, but one problem blocks it.

To get this merged:

  • Deleted or renamed test modules. In tools/select_tests.py, select() takes the changed files as seeds. classify returns {name} for a changed tests/core/test*.py, whether or not the file still exists. is_suite_test then checks only the name format, so a deleted or renamed test module stays in the selection. pytest then gets a path that doesn't exist and fails the job. Please drop selected test modules that are missing from graph.modules, or whose file is gone. A selector test that deletes a test file and checks it isn't selected would cover this.

Optional suggestions:

  • Docs wording. docs/how_to_contribute.rst says the coverage totals "match what a full run would show". The description names one exception: an unchanged file that loses coverage keeps the baseline's lines. Adding that caveat to the docs would make them match.
  • Source setting in coverage_report.py. Coverage(data_file=...) is loaded without a source. This is fine if the baseline's data already lists every unexecuted pyhealth file, which --cov=pyhealth should do. A short comment, or an explicit source, would make that assumption visible.
  • init narrowing. changed_bindings treats any import in an init.py as a re-export. A side-effect import added there would be narrowed the same way. A note in the docstring would help.
  • Not yet verified. The workflow hasn't been verified on GitHub yet, as you noted. A maintainer will probably want to watch the first runs after merge.

Coverage: CI reported no coverage data. The changed files are under tools/, tests/, docs/ and .github/, not pyhealth/, so the per-file 80% bar doesn't apply. I couldn't check coverage. Both new tools have their own tests.

Reviewed commit 3a005ac

Addresses the AI review on 3a005ac:

- A deleted or renamed test module was still selected (it is a seed), so
  pytest got a missing path and failed. Selection now keeps only test
  modules that exist.
- A bare `import pyhealth.x` added to an __init__ binds no new name, so
  it is no longer narrowed like a re-export; all importers run.
- coverage_report: document why loading without `source` is safe
  (--cov=pyhealth writes unexecuted files into the data), and test that
  the merge keeps such files at 0%.
- docs: state the one case where the merged total differs from a full run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit ddb4f9e

Comment thread tools/coverage_report.py
}


def main() -> int:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] JSON output and merge dispatch in main() have no tests

main() decides between this run's data and the merged baseline (merged_data, git_changed) and prints the JSON block that coverage.yml and ai-review.yml parse, including the new tests object. tests/core/test_coverage_report.py only exercises merge(), so a regression in the mode dispatch or the output shape would not be caught before a PR's own job runs it. Add a test that runs main() in a temp repo with MODE=all and MODE=some and checks the last JSON block's keys and values. Non-blocking, since every PR's test job runs this step.

Comment thread tools/coverage_report.py
# Copy rather than purge: purge_files() empties a file's lines but keeps
# it measured, so a deleted file would linger in the total.
kept = {f: base.lines(f) or [] for f in base.measured_files()
if rel(f, root) not in changed}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Baseline data is matched to changed files by absolute path

Baseline data keys are absolute paths from the master runner's checkout, and rel(f, root) is compared against the changed-file set. If a runner's checkout path differs from the one that saved the baseline, the rel() result becomes ../..., the changed-file filter silently fails, and stale baseline lines stay for changed files, overcounting coverage. GitHub-hosted runners share the path, so this is only a risk on other runners. Normalise the baseline paths relative to the checkout before the filter, or note the assumption in the module docstring.

The updated patients dict.
"""

Which Tests CI Runs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] New section sits under Implementation Requirements, away from test guidance

'Which Tests CI Runs' is inserted between 'Code Style and Documentation' and 'Types of Contributions', under the Implementation Requirements section. Its rule that tests must import what they test belongs with 'Test Case Requirements' (around line 523). Move the section there, or add a short pointer from that section. The content matches the code.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It adds import-graph test selection for PRs (tools/select_tests.py) and a coverage merge with master's last full run (tools/coverage_report.py). It also updates the workflows, docs and makefile to match. It looks ready to merge.

  • Scope: The change touches only CI, tools, docs, the makefile and tests, with no pyhealth/ library files. The description matches the diff.
  • Fail-safes: Full-suite runs on infrastructure changes, the smoke import step, the full-ci label and the baseline fallback are sensible.
  • Coverage: No pyhealth/ files are changed, so there is no per-file coverage to check. The new selector and coverage-merge logic have dedicated tests (22 selector cases and the merge rules). The coverage figures for the whole repository weren't available to me.

Optional suggestions:

  • Add small tests for main(), smoke_imports() and the JSON output of coverage_report.py. They are the glue the workflows depend on.
  • Since the workflow itself is unverified on GitHub, watch the first few PRs after merge. Check that the baseline artifact is saved and found, and that the coverage comment parses.
  • The coverage merge keys files by absolute paths. This works while the master and PR runners share the same checkout path, so a short comment saying so would help.
  • The docs section might sit closer to the testing guidance in how_to_contribute.rst.

Reviewed commit ddb4f9e

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant