diff --git a/.github/actions/policyengine-us-main/action.yaml b/.github/actions/policyengine-us-main/action.yaml new file mode 100644 index 000000000..69bed5a30 --- /dev/null +++ b/.github/actions/policyengine-us-main/action.yaml @@ -0,0 +1,49 @@ +name: Set up policyengine-us with this Core +description: >- + Check out a policyengine-us commit into ./policyengine-us, install it from + its lock as its CI does, and replace the locked Core with the Core checkout + in ./core. +inputs: + ref: + description: The policyengine-us commit to check out. + required: true +runs: + using: composite + steps: + - name: Checkout policyengine-us + uses: actions/checkout@v6 + with: + repository: PolicyEngine/policyengine-us + ref: ${{ inputs.ref }} + path: policyengine-us + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.14" + - name: Install uv + uses: astral-sh/setup-uv@v8.1.0 + # As policyengine-us's setup-system-ca action does before its tests. + - name: Update system certificate authorities + shell: bash + run: | + sudo apt-get update + sudo apt-get install --only-upgrade --yes ca-certificates + # update_itemization.sh turns off default branching, as policyengine-us's + # CI does before its tests. + - name: Install policyengine-us + shell: bash + working-directory: policyengine-us + run: | + uv sync --frozen --extra dev + bash ./update_itemization.sh + # The checkout replaces the locked Core even at the same version number, + # the step checks that it was installed from the checkout, and the + # dependency set must still resolve. + - name: Install this Core + shell: bash + working-directory: policyengine-us + run: | + uv pip install --python .venv/bin/python --reinstall-package policyengine-core ../core + uv run --no-sync python -c "import json; from importlib.metadata import distribution; url = json.loads(distribution('policyengine-core').read_text('direct_url.json'))['url']; print(url); assert url.startswith('file://'), url" + uv pip check --python .venv/bin/python diff --git a/.github/country_main_tests.py b/.github/country_main_tests.py index b8afe986d..337b8db33 100644 --- a/.github/country_main_tests.py +++ b/.github/country_main_tests.py @@ -1,30 +1,30 @@ #!/usr/bin/env python -"""Run policyengine-us main's Core-facing tests against the Core under test. +"""Compare policyengine-us main's Python tests under this Core with its release run. The country smoke job installs a pinned policyengine-us release and checks that its system loads, so it cannot see a policyengine-us test that a Core -change breaks. On 2026-10-27, 3.33.13 broke policyengine-us main's -test_social_security_input_state_machine.py within minutes of its release. - -The PolicyEngineUSMain job checks out policyengine-us main and runs the files -in .github/requirements/policyengine-us-main-tests.txt twice, each with a -JUnit report: first with the Core release on PyPI, then with this checkout. - -- `select LIST REPO` prints the pytest arguments for the listed files that - exist in REPO, one per line, and warns about the rest, which - policyengine-us renamed or removed. -- `run SELECTED REPORT` runs them with a JUnit report. It fails unless pytest - ran them to the end, passing or failing. +change breaks. From 2026-10-01 to 12-03, four Core releases broke +policyengine-us main's Python tests within minutes of release: 3.32.15-16, +3.33.13, 3.39.0 and 3.41.0. + +On PRs marked ready, the policyengine-us jobs in pr.yaml check out the commit +of policyengine-us's latest successful release run, install this Core, and run +its Python tests as that run did: the Rest shards, Microsimulation, SPM and +the contrib Python tests. A successful release run passed every test it ran, +and kept a JUnit report of each group except the contrib tests. + +- `run SELECTED REPORT` runs the test files listed in SELECTED with a JUnit + report. It fails unless pytest ran them to the end, passing or failing. - `compare RELEASED CANDIDATE` lists the tests this Core breaks: those that - fail with it but did not fail with the release, and those that passed with - the release in a file this Core cannot collect. A break does not fail the - job, since a Core change can need a policyengine-us fix after its release. - The job fails only when the comparison cannot be trusted: a run wrote no - report, the release's run collected no tests, this Core's run recorded - none, or a test that passed with the release did not run for another - reason. A test that fails with both Cores is a warning: policyengine-us - main or an earlier Core release broke it. So is a test that passed with - the release and is skipped with this Core, since its coverage is lost. + fail with it but did not fail in the release run, and those that passed + in the release run in a file this Core cannot collect. RELEASED and + CANDIDATE are JUnit reports or directories of them. A break does not fail + the job, since a Core change can need a policyengine-us fix after its + release. The job fails only when the comparison cannot be trusted: no + report from the release run or this Core, a release run with no tests, + or a test that passed in the release run and did not run with this Core + for another reason. A test that passed in the release run and is skipped + with this Core is a warning, since its coverage is lost. - `report RESULT` puts compare's result on the PR: a neutral check that lists the breaks, or a successful one when there are none, and one comment that lists them, updated on each run. @@ -40,8 +40,9 @@ from pathlib import Path from xml.etree import ElementTree -# Hypothesis draws the same examples in both runs, so a difference between -# them comes from Core. A file that fails to import must not stop the others. +# `run`'s command, for the contrib Python tests. A file that fails to import +# must not stop the others, and a fixed Hypothesis seed makes a rerun draw the +# same examples. PYTEST = [ "uv", "run", @@ -61,34 +62,14 @@ 4: "usage error", 5: "no tests collected", } -DESELECT = "deselect " - - -def listed_entries(list_path): - """The list's test files, and the tests to deselect from them.""" - files, deselected = [], [] - for line in Path(list_path).read_text().splitlines(): - line = line.split("#", 1)[0].strip() - if line.startswith(DESELECT): - deselected.append(line.removeprefix(DESELECT).strip()) - elif line: - files.append(line) - return files, deselected - - -def select(list_path, repo): - """pytest arguments for the files the checkout has, and the files it lacks.""" - files, deselected = listed_entries(list_path) - present = [path for path in files if (Path(repo) / path).is_file()] - missing = [path for path in files if path not in present] - deselect = [ - f"--deselect={test}" for test in deselected if test.split("::")[0] in present - ] - return present + deselect, missing +MARKER = "" +HEADING = "### policyengine-us main against this Core" +# compare's --baseline when the workflow names no run. +RELEASE_RUN = "policyengine-us's latest successful release run" def run_tests(selected_path, report, pytest=PYTEST): - """Run the selected tests with a JUnit report; fail unless they all ran. + """Run the listed test files with a JUnit report; fail unless they all ran. pytest exits 1 when a test fails or a file cannot be collected, and compare sorts those out. Any other failing status means the run stopped @@ -103,14 +84,28 @@ def run_tests(selected_path, report, pytest=PYTEST): return status -def outcomes(report): - """Each test's outcome in a JUnit report: passed, failed or skipped. +def reports(path): + """The JUnit reports at a path: the file itself, or a directory's.""" + path = Path(path) + if path.is_dir(): + return sorted(path.rglob("*.xml")) + return [path] if path.exists() else [] + + +def cases(paths): + """Every testcase entry in one JUnit report or a list of them.""" + for report in [paths] if isinstance(paths, (str, Path)) else paths: + yield from ElementTree.parse(report).getroot().iter("testcase") + + +def outcomes(paths): + """Each test's outcome in JUnit reports: passed, failed or skipped. A test can appear twice, as when its teardown errors after it passed; a failure in either entry counts. """ results = {} - for case in ElementTree.parse(report).getroot().iter("testcase"): + for case in cases(paths): test = f"{case.get('classname', '')}::{case.get('name', '')}" tags = {child.tag for child in case} if tags & {"failure", "error"}: @@ -136,18 +131,18 @@ def records(case, kind): return any(child.tag == tag and child.get("message") == message for child in case) -def collected_any(report): - """Whether a JUnit report records a test, not only collection entries.""" +def collected_any(paths): + """Whether JUnit reports record a test, not only collection entries.""" return any( not records(case, COLLECTION_FAILURE) and not records(case, COLLECTION_SKIP) - for case in ElementTree.parse(report).getroot().iter("testcase") + for case in cases(paths) ) -def collection_entries(report, kind): - """The modules a JUnit report records as a collection failure or skip.""" +def collection_entries(paths, kind): + """The modules JUnit reports record as a collection failure or skip.""" modules = set() - for case in ElementTree.parse(report).getroot().iter("testcase"): + for case in cases(paths): if records(case, kind): parts = (case.get("classname", ""), case.get("name", "")) modules.add(".".join(part for part in parts if part)) @@ -162,19 +157,22 @@ def in_modules(test, modules): def compare(released, candidate, uncollected=(), lost=(), skipped_modules=()): - """Sort this Core's failures and absences against the release's results. + """Sort this Core's failures and absences against the release run's results. - `uncollected` and `lost` are the modules the release and this Core could - not collect; `skipped_modules`, those this Core skipped while collecting. + `uncollected` and `lost` are the modules the release run and this Core + could not collect; `skipped_modules`, those this Core skipped while + collecting. - - broken: fails with this Core but did not fail with the release. - - uncollected: passed with the release; this Core cannot collect its file. - - missing: passed with the release but did not run with this Core, for + - broken: fails with this Core but did not fail in the release run, + including a test the release run has no result for. + - uncollected: passed in the release run; this Core cannot collect its + file. + - missing: passed in the release run but did not run with this Core, for no reason the reports show. - - skipped: passed with the release and is skipped with this Core. - - unsure: fails with this Core in a module the release could not - collect, so the release has no result to compare. - - both: fails with both Cores. + - skipped: passed in the release run and is skipped with this Core. + - unsure: fails with this Core in a module the release run could not + collect, so it has no result to compare. + - both: fails in both runs. """ result = { "broken": [], @@ -208,6 +206,11 @@ def compare(released, candidate, uncollected=(), lost=(), skipped_modules=()): return result +# Tests listed per kind in the summary, which GitHub caps at 1 MiB a step: a +# lost shard can leave thousands missing. The log lists them all. +SUMMARY_LISTED = 200 + + def tally(results): counts = [ f"{sum(outcome == kind for outcome in results.values())} {kind}" @@ -216,87 +219,97 @@ def tally(results): return ", ".join(counts) -def summary(released, candidate, result): +def summary(released, candidate, result, baseline=RELEASE_RUN): lines = [ - "### policyengine-us main against this Core", + HEADING, + "", + f"Compared with {baseline}.", "", - f"- With the Core release: {tally(released)}", + f"- In the release run: {tally(released)}", f"- With this Core: {tally(candidate)}", "", ] titles = { "broken": "**This Core breaks {}:**", - "uncollected": "**Passed with the Core release; this Core cannot collect their file: {}**", - "missing": "**Passed with the Core release but did not run with this Core: {}**", - "skipped": "Passed with the Core release; skipped with this Core: {}", - "unsure": "Failing with this Core in files the Core release could not collect: {}", - "both": "Failing with both Cores: {}", + "uncollected": "**Passed in the release run; this Core cannot collect their file: {}**", + "missing": "**Passed in the release run but did not run with this Core: {}**", + "skipped": "Passed in the release run; skipped with this Core: {}", + "unsure": "Failing with this Core in files the release run could not collect: {}", + "both": "Failing in both runs: {}", } for key, title in titles.items(): if result[key]: lines.append(title.format(len(result[key]))) - lines += [f"- `{test}`" for test in result[key]] + lines += [f"- `{test}`" for test in result[key][:SUMMARY_LISTED]] + if len(result[key]) > SUMMARY_LISTED: + more = len(result[key]) - SUMMARY_LISTED + lines.append(f"- ...and {more} more in the compare step's log.") lines.append("") if not any(result.values()): lines.append( - "No test fails with this Core, and every test that ran before ran." + "No test fails with this Core, and every test from the release run ran." ) return "\n".join(lines) + "\n" -def run_compare(released_report, candidate_report, summary_path=None, json_path=None): - for name, report in ( - ("This Core", candidate_report), - ("The Core release", released_report), - ): - if not Path(report).exists(): - print(f"::error::{name}'s run wrote no JUnit report.") - return 1 - if not collected_any(released_report): +def run_compare( + released_path, + candidate_path, + summary_path=None, + json_path=None, + baseline=RELEASE_RUN, +): + released_reports = reports(released_path) + candidate_reports = reports(candidate_path) + if not released_reports: + print("::error::There is no JUnit report from the release run.") + return 1 + if not candidate_reports: + print("::error::This Core's runs wrote no JUnit report.") + return 1 + if not collected_any(released_reports): print( - "::error::The Core release's run collected no tests, so there is " + "::error::The release run's reports record no tests, so there is " "nothing to compare this Core with." ) return 1 - released = outcomes(released_report) - candidate = outcomes(candidate_report) + released = outcomes(released_reports) + candidate = outcomes(candidate_reports) if not candidate: - print("::error::This Core's run recorded no tests.") + print("::error::This Core's runs recorded no tests.") return 1 result = compare( released, candidate, - collection_entries(released_report, COLLECTION_FAILURE), - collection_entries(candidate_report, COLLECTION_FAILURE), - collection_entries(candidate_report, COLLECTION_SKIP), + collection_entries(released_reports, COLLECTION_FAILURE), + collection_entries(candidate_reports, COLLECTION_FAILURE), + collection_entries(candidate_reports, COLLECTION_SKIP), ) for test in result["both"]: - print(f"::warning::Fails with both Cores: {test}") + print(f"::warning::Fails in both runs: {test}") for test in result["unsure"]: print( - "::warning::Fails with this Core; the Core release could not collect " + "::warning::Fails with this Core; the release run could not collect " f"its file: {test}" ) for test in result["broken"] + result["uncollected"]: print(f"::warning::This Core breaks {test}") for test in result["skipped"]: - print( - f"::warning::Passed with the Core release; skipped with this Core: {test}" - ) + print(f"::warning::Passed in the release run; skipped with this Core: {test}") for test in result["missing"]: - print(f"::error::Passed with the Core release but did not run: {test}") - text = summary(released, candidate, result) + print(f"::error::Passed in the release run but did not run: {test}") + text = summary(released, candidate, result, baseline) print(text) if summary_path: with open(summary_path, "a") as output: output.write(text) if json_path: - Path(json_path).write_text(json.dumps({**result, "summary": text}, indent=2)) + Path(json_path).write_text( + json.dumps({**result, "summary": text, "baseline": baseline}, indent=2) + ) return 1 if result["missing"] else 0 -MARKER = "" -HEADING = "### policyengine-us main against this Core" CHECK = "policyengine-us compatibility" BOT = "github-actions[bot]" LISTED = 50 @@ -334,14 +347,14 @@ def find_comment(api, repo, number): page = page + 1 -def break_comment(breaks, where): - noun, verb = ("test", "passes") if len(breaks) == 1 else ("tests", "pass") +def break_comment(breaks, where, baseline=RELEASE_RUN): + noun = "test" if len(breaks) == 1 else "tests" lines = [ MARKER, HEADING, "", - f"This Core breaks {len(breaks)} policyengine-us {noun} that {verb} with " - "the Core release:", + f"This Core breaks {len(breaks)} policyengine-us {noun} that passed in " + f"{baseline}:", "", *(f"- `{test}`" for test in breaks[:LISTED]), ] @@ -359,9 +372,11 @@ def break_comment(breaks, where): def report(result_path, env=os.environ, api=None): - """Put compare's result on the PR as a check and, for breaks, a comment. + """Put compare's result on the PR as a check and one comment. - A break is a neutral check, not a failure: the change may be intended. + The comment is posted with or without breaks, and edited on each push, so + whoever waits for it learns whether the PR affects policyengine-us. A + break is a neutral check, not a failure: the change may be intended. Without write access, as on a PR from a fork, it warns and leaves the result in the job summary. """ @@ -393,15 +408,15 @@ def api(method, path, payload=None): }, ) comment = find_comment(api, repo, number) + baseline = result.get("baseline", RELEASE_RUN) if breaks: - body = break_comment(breaks, where) - elif comment: + body = break_comment(breaks, where, baseline) + else: body = ( - f"{MARKER}\n{HEADING}\n\nNo policyengine-us test breaks with this " - f"Core any more, as of {where}.\n" + f"{MARKER}\n{HEADING}\n\nNo policyengine-us test breaks: every " + f"policyengine-us Python test that passed in {baseline} still " + f"passes with this Core.\n\nChecked at {where}.\n" ) - else: - return 0 if comment: api( "PATCH", @@ -421,15 +436,19 @@ def api(method, path, payload=None): def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) commands = parser.add_subparsers(dest="command", required=True) - chooser = commands.add_parser("select", help="list the pytest arguments") - chooser.add_argument("list") - chooser.add_argument("repo") - runner = commands.add_parser("run", help="run the selected tests") + runner = commands.add_parser("run", help="run the listed test files") runner.add_argument("selected") runner.add_argument("report") - checker = commands.add_parser("compare", help="compare the two runs") - checker.add_argument("released") - checker.add_argument("candidate") + checker = commands.add_parser( + "compare", help="compare this Core's runs with the release run" + ) + checker.add_argument("released", help="a JUnit report or a directory of them") + checker.add_argument("candidate", help="a JUnit report or a directory of them") + checker.add_argument( + "--baseline", + default=RELEASE_RUN, + help="the release run, in Markdown, for the summary and the comment", + ) checker.add_argument( "--summary", default=os.environ.get("GITHUB_STEP_SUMMARY"), @@ -439,24 +458,13 @@ def main(argv=None): reporter = commands.add_parser("report", help="put the result on the PR") reporter.add_argument("result") args = parser.parse_args(argv) - if args.command == "select": - arguments, missing = select(args.list, args.repo) - for path in missing: - print( - f"::warning::policyengine-us main has no {path}; update " - ".github/requirements/policyengine-us-main-tests.txt.", - file=sys.stderr, - ) - if not any(not argument.startswith("--") for argument in arguments): - print("::error::None of the listed files exist.", file=sys.stderr) - return 1 - print("\n".join(arguments)) - return 0 if args.command == "run": return run_tests(args.selected, args.report) if args.command == "report": return report(args.result) - return run_compare(args.released, args.candidate, args.summary, args.json) + return run_compare( + args.released, args.candidate, args.summary, args.json, args.baseline + ) if __name__ == "__main__": diff --git a/.github/requirements/policyengine-us-main-tests.txt b/.github/requirements/policyengine-us-main-tests.txt deleted file mode 100644 index c30296a88..000000000 --- a/.github/requirements/policyengine-us-main-tests.txt +++ /dev/null @@ -1,30 +0,0 @@ -# policyengine-us test files the PolicyEngineUSMain job runs from a checkout of -# policyengine-us main, first with the Core release on PyPI and then with the -# Core under test (.github/country_main_tests.py). Paths are relative to the -# policyengine-us repository root. -# -# Each file drives Core internals (simulations, holders, data storage, tools, -# populations, parameters or reforms) and is fast: together they took about -# 95 seconds in policyengine-us release run 40544965026. The state machine test -# runs Core's installed source bodies in namespaces it builds; Core 3.33.13 -# broke it on 2026-10-27, which this job would have shown on the PR. -# -# A file policyengine-us renames or removes is skipped with a warning, so keep -# the list in step when that happens. A `deselect ::` line leaves -# one test of a listed file out. -policyengine_us/tests/core/test_social_security_input_state_machine.py -policyengine_us/tests/core/test_social_security_real_core.py -policyengine_us/tests/core/test_loss_ald_extraction_parity.py -policyengine_us/tests/core/test_capital_gains_rate_worksheet_properties.py -policyengine_us/tests/core/test_ald_determinism.py -policyengine_us/tests/core/test_pandas3_compatibility.py -policyengine_us/tests/core/test_social_security_lever_properties.py -policyengine_us/tests/test_locality_sales_tax_rates.py -policyengine_us/tests/test_parameter_scale_thresholds.py -policyengine_us/tests/code_health/test_no_group_variables_in_person_adds.py -policyengine_us/tests/microsimulation/data/test_extend_single_year_dataset.py -policyengine_us/tests/policy/baseline/parameters/test_uprating_extensions.py -# Builds the default Microsimulation, which downloads about 830 MB of microdata, -# only to read parameters. -deselect policyengine_us/tests/policy/baseline/parameters/test_uprating_extensions.py::test_retirement_contribution_limits_include_latest_explicit_irs_values -policyengine_us/tests/policy/baseline/gov/states/or/tax/income/credits/test_or_ctc_sunset.py diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 8e6634811..0e8f00544 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -2,12 +2,16 @@ name: Pull request on: pull_request: branches: [master] + # The default types, and ready_for_review to start the policyengine-us + # jobs, which skip drafts, when a draft is marked ready. + types: [opened, synchronize, reopened, ready_for_review] # A new push to a pull request supersedes the run on its previous head. Cancel -# that run instead of letting its 20 jobs (8 Test, 8 smoke, 1 policyengine-us -# main, 3 checks) keep holding org-wide shared runners. From 2026-10-06 to -# 10-08, 21 of 55 PR runs were superseded while still running, and finishing -# them used 850 runner-minutes (26% of this workflow). +# that run instead of letting its jobs (8 Test, 8 smoke, 3 checks, and about 12 +# policyengine-us main jobs on a PR marked ready) keep holding org-wide shared +# runners. From 2026-10-06 to 10-08, 21 of 55 PR runs were superseded while +# still running, and finishing them used 850 runner-minutes (26% of this +# workflow). concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number }} cancel-in-progress: true @@ -121,16 +125,28 @@ jobs: env: RUN_SMOKE_TESTS: "0" POLICYENGINE_GITHUB_MICRODATA_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PolicyEngineUSMain: - name: Test policyengine-us main against this Core + # policyengine-us main's Python tests with this Core, on PRs marked ready. + # From 2026-10-01 to 12-03, Core releases broke policyengine-us main's + # Python tests four times (3.32.15-16, 3.33.13, 3.39.0, 3.41.0) and none of + # its YAML tests, so the YAML tests are left out. The jobs check out the + # commit of policyengine-us's latest successful release run and run its + # Python tests as that run did (its python-tests.yaml): the Rest shards from + # its own planner, Microsimulation, SPM and the contrib Python tests. Compare + # sets the results against that run's JUnit reports + # (.github/country_main_tests.py). + PolicyEngineUSPlan: + name: "policyengine-us main: plan" + if: ${{ !github.event.pull_request.draft }} runs-on: ubuntu-latest needs: Lint - timeout-minutes: 30 + timeout-minutes: 15 permissions: + actions: read contents: read - # The result goes on the PR as a check and a comment. - checks: write - pull-requests: write + outputs: + sha: ${{ steps.release.outputs.sha }} + baseline: ${{ steps.release.outputs.baseline }} + matrix: ${{ steps.plan.outputs.matrix }} env: PYTHONUNBUFFERED: 1 steps: @@ -139,55 +155,277 @@ jobs: with: path: core persist-credentials: false - - name: Checkout policyengine-us main + # Successful first attempts only: a failed run can lack a lost runner's + # reports, and a re-run keeps an earlier attempt's. The Core version + # comes from the run's SPM log, for the summary. + - name: Download the latest successful release run's reports + id: release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + repo=PolicyEngine/policyengine-us + runs=$(gh run list --repo "$repo" --workflow push.yaml --branch main \ + --status success --limit 40 --json databaseId,displayTitle,attempt,headSha \ + --jq '[.[] | select(.displayTitle == "Update PolicyEngine US" and .attempt == 1)][:3][] | "\(.databaseId) \(.headSha)"') + while read -r run sha; do + [ -n "$run" ] || continue + rm -rf released + if gh run download "$run" --repo "$repo" --dir released \ + --pattern 'rest-python-test-timings-*' \ + --pattern simulation-test-timings \ + --pattern spm-test-timings && + compgen -G 'released/rest-python-test-timings-*/rest-python-*.xml' > /dev/null && + [ -f released/simulation-test-timings/simulation-microsimulation.xml ] && + [ -f released/spm-test-timings/simulation-spm.xml ]; then + job=$(gh api "repos/$repo/actions/runs/$run/jobs?per_page=100" --jq '.jobs[] | select(.name == "Full Suite - SPM") | .id') || job="" + gh api "repos/$repo/actions/jobs/$job/logs" > spm.log || true + core=$(grep -m 1 -oE 'policyengine-core==[0-9][0-9a-z.]*' spm.log | cut -d= -f3) || core="" + { + echo "run=$run" + echo "sha=$sha" + echo "baseline=policyengine-us release run [$run](https://github.com/$repo/actions/runs/$run) at \`${sha:0:7}\`${core:+, with Core $core}" + } >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "::warning::Release run $run lacks a Python test report; trying an earlier one." + done <<< "$runs" + echo "::error::No recent successful policyengine-us release run has every Python test report." + exit 1 + - name: Set up policyengine-us with this Core + uses: ./core/.github/actions/policyengine-us-main + with: + ref: ${{ steps.release.outputs.sha }} + # policyengine-us's planner, with the release run's reports as timings. + - name: Plan the Rest Python shards + id: plan + working-directory: policyengine-us + env: + RUN: ${{ steps.release.outputs.run }} + run: uv run --no-sync python policyengine_us/tests/rest_python_shards.py plan --timings ../released --source "release run $RUN" --github-output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY" + - name: Keep the release run's reports for the comparison + uses: actions/upload-artifact@v4 + with: + name: policyengine-us-released + path: released + PolicyEngineUSRest: + name: "policyengine-us main: Rest Python (shard ${{ matrix.shard }})" + runs-on: ubuntu-latest + needs: PolicyEngineUSPlan + # The planner aims at 25 minutes a shard, as in policyengine-us. + timeout-minutes: 90 + permissions: + contents: read + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.PolicyEngineUSPlan.outputs.matrix) }} + env: + PYTHONUNBUFFERED: 1 + OMP_NUM_THREADS: 4 + OPENBLAS_NUM_THREADS: 4 + MKL_NUM_THREADS: 4 + VECLIB_MAXIMUM_THREADS: 4 + NUMEXPR_NUM_THREADS: 4 + OMP_WAIT_POLICY: PASSIVE + steps: + - name: Checkout repo uses: actions/checkout@v6 with: - repository: PolicyEngine/policyengine-us - ref: main - path: policyengine-us + path: core persist-credentials: false - - name: Set up Python - uses: actions/setup-python@v6 + - name: Set up policyengine-us with this Core + uses: ./core/.github/actions/policyengine-us-main with: - python-version: "3.14" - - name: Install uv - uses: astral-sh/setup-uv@v8.1.0 - # As policyengine-us's own CI does: its lock with the newest Core release. - - name: Install policyengine-us main with the Core release + ref: ${{ needs.PolicyEngineUSPlan.outputs.sha }} + # In this and the other test jobs, a failing test fails the step but not + # the job: compare sorts the failures out, and reports any test that a + # stopped run left out. A file that fails to import must not stop the + # others, as a Core change can cause that. + - name: Run the shard's Rest Python tests + continue-on-error: true working-directory: policyengine-us + env: + PYTEST_ADDOPTS: "--continue-on-collection-errors -p no:unraisableexception -p no:threadexception" + REST_PYTHON_PROCESSES: ${{ matrix.processes }} run: | - uv lock --upgrade-package policyengine-core - uv sync --locked --extra dev - bash ./update_itemization.sh - - name: Select the policyengine-us tests - run: python core/.github/country_main_tests.py select core/.github/requirements/policyengine-us-main-tests.txt policyengine-us > selected.txt - # Both runs use the same pytest command (country_main_tests.PYTEST). A - # run whose tests fail goes on to the comparison; one that stops early - # or runs nothing fails here. - - name: Run them with the Core release + mkdir -p ../candidate + uv run --no-sync python policyengine_us/tests/rest_python_shards.py run --report-dir ../candidate + - name: Keep the reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: policyengine-us-candidate-rest-${{ matrix.shard }} + path: candidate/*.xml + PolicyEngineUSMicrosimulation: + name: "policyengine-us main: Microsimulation" + runs-on: ubuntu-latest + needs: PolicyEngineUSPlan + timeout-minutes: 60 + permissions: + contents: read + env: + PYTHONUNBUFFERED: 1 + steps: + - name: Checkout repo + uses: actions/checkout@v6 + with: + path: core + persist-credentials: false + - name: Set up policyengine-us with this Core + uses: ./core/.github/actions/policyengine-us-main + with: + ref: ${{ needs.PolicyEngineUSPlan.outputs.sha }} + # Some tests compare with a reference commit, which policyengine-us's + # Microsimulation job fetches first. + - name: Fetch the commits policyengine-us's Python tests read working-directory: policyengine-us run: | - uv pip list | grep -i '^policyengine-core ' - python ../core/.github/country_main_tests.py run ../selected.txt ../released.xml - - name: Install this Core + shas=$(grep -oE 'git fetch --no-tags --depth=1 origin [0-9a-f]{40}' .github/workflows/python-tests.yaml | awk '{print $NF}' | sort -u) || shas="" + for sha in $shas; do + git fetch --no-tags --depth=1 origin "$sha" + done + - name: Run the microsimulation tests + continue-on-error: true working-directory: policyengine-us - run: | - uv pip install --python .venv/bin/python --reinstall-package policyengine-core ../core - uv run --no-sync python -c "import json; from importlib.metadata import distribution; url = json.loads(distribution('policyengine-core').read_text('direct_url.json'))['url']; print(url); assert url.startswith('file://'), url" - uv pip check --python .venv/bin/python - - name: Run them with this Core + env: + PYTEST_ADDOPTS: "--junitxml=simulation-microsimulation.xml --continue-on-collection-errors -p no:unraisableexception -p no:threadexception" + run: uv run --no-sync make test-microsimulation + - name: Keep the reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: policyengine-us-candidate-microsimulation + path: policyengine-us/simulation-*.xml + PolicyEngineUSSPM: + name: "policyengine-us main: SPM" + runs-on: ubuntu-latest + needs: PolicyEngineUSPlan + timeout-minutes: 45 + permissions: + contents: read + env: + PYTHONUNBUFFERED: 1 + steps: + - name: Checkout repo + uses: actions/checkout@v6 + with: + path: core + persist-credentials: false + - name: Set up policyengine-us with this Core + uses: ./core/.github/actions/policyengine-us-main + with: + ref: ${{ needs.PolicyEngineUSPlan.outputs.sha }} + - name: Run the SPM tests + continue-on-error: true + working-directory: policyengine-us + env: + PYTEST_ADDOPTS: "--junitxml=simulation-spm.xml --continue-on-collection-errors -p no:unraisableexception -p no:threadexception" + run: uv run --no-sync make test-other-python-spm + - name: Keep the report + if: always() + uses: actions/upload-artifact@v4 + with: + name: policyengine-us-candidate-spm + path: policyengine-us/simulation-spm.xml + PolicyEngineUSContrib: + name: "policyengine-us main: Contrib Python" + runs-on: ubuntu-latest + needs: PolicyEngineUSPlan + timeout-minutes: 45 + permissions: + contents: read + env: + PYTHONUNBUFFERED: 1 + steps: + - name: Checkout repo + uses: actions/checkout@v6 + with: + path: core + persist-credentials: false + - name: Set up policyengine-us with this Core + uses: ./core/.github/actions/policyengine-us-main + with: + ref: ${{ needs.PolicyEngineUSPlan.outputs.sha }} + # The files `make test-policy-contrib-python` runs. The release run + # keeps no report of them but passed them all, so compare counts any + # failure as a break. With no list of what ran to check against, the + # script's run fails here if pytest stops early. + - name: Run the contrib Python tests working-directory: policyengine-us - run: python ../core/.github/country_main_tests.py run ../selected.txt ../candidate.xml + env: + PYTEST_ADDOPTS: "-p no:unraisableexception -p no:threadexception" + run: | + find policyengine_us/tests/policy/contrib -name 'test*.py' -print | sort > ../contrib.txt + python ../core/.github/country_main_tests.py run ../contrib.txt ../candidate/contrib-python.xml + - name: Keep the report + if: always() + uses: actions/upload-artifact@v4 + with: + name: policyengine-us-candidate-contrib + path: candidate/contrib-python.xml + PolicyEngineUSCompare: + name: "policyengine-us main: compare" + runs-on: ubuntu-latest + needs: + - PolicyEngineUSPlan + - PolicyEngineUSRest + - PolicyEngineUSMicrosimulation + - PolicyEngineUSSPM + - PolicyEngineUSContrib + # Compares whatever the test jobs reported, but stops when the run is + # cancelled. + if: ${{ !cancelled() && needs.PolicyEngineUSPlan.result == 'success' }} + timeout-minutes: 10 + permissions: + contents: read + # The result goes on the PR as a check and a comment. + checks: write + pull-requests: write + steps: + - name: Checkout repo + uses: actions/checkout@v6 + with: + path: core + persist-credentials: false + - name: Download the release run's reports + uses: actions/download-artifact@v4 + with: + name: policyengine-us-released + path: released + - name: Download this Core's reports + uses: actions/download-artifact@v4 + with: + pattern: policyengine-us-candidate-* + path: candidate # A test this Core breaks is a warning here and a neutral check on the # PR, since the change may be intended; a comparison that cannot be # trusted fails the job. The job summary keeps the full result, which # PRs from forks cannot post. - - name: Compare the two runs - run: python core/.github/country_main_tests.py compare released.xml candidate.xml --summary "$GITHUB_STEP_SUMMARY" --json result.json + - name: Compare this Core's runs with the release run + env: + BASELINE: ${{ needs.PolicyEngineUSPlan.outputs.baseline }} + run: python3 core/.github/country_main_tests.py compare released candidate --baseline "$BASELINE" --summary "$GITHUB_STEP_SUMMARY" --json result.json + # A test job that failed set up, lost its runner or, for the contrib + # tests, stopped early, ran less than compare can see. + - name: Check every test job finished + env: + REST: ${{ needs.PolicyEngineUSRest.result }} + MICROSIMULATION: ${{ needs.PolicyEngineUSMicrosimulation.result }} + SPM: ${{ needs.PolicyEngineUSSPM.result }} + CONTRIB: ${{ needs.PolicyEngineUSContrib.result }} + run: | + status=0 + for job in "Rest Python:$REST" "Microsimulation:$MICROSIMULATION" "SPM:$SPM" "Contrib Python:$CONTRIB"; do + if [ "${job##*:}" != success ]; then + echo "::error::The ${job%:*} job did not finish: ${job##*:}." + status=1 + fi + done + exit "$status" - name: Report the result on the PR env: GITHUB_TOKEN: ${{ github.token }} PR_NUMBER: ${{ github.event.pull_request.number }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: python core/.github/country_main_tests.py report result.json + run: python3 core/.github/country_main_tests.py report result.json diff --git a/AGENTS.md b/AGENTS.md index f8efd06ba..729aaf981 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,3 +31,8 @@ Before creating or sharing any PR, all developers and agents must: If you cannot push to the canonical repository, stop and ask for access. Do not open a fork PR as a fallback unless the user explicitly asks for one. + +After opening a PR, wait for the bot comment that says whether the PR breaks +any policyengine-us tests, and include its result when you report the PR. See +the policyengine-us compatibility section of +`docs/engineering/skills/github-prs.md`. diff --git a/changelog.d/policyengine-us-all-python-tests.changed.md b/changelog.d/policyengine-us-all-python-tests.changed.md new file mode 100644 index 000000000..63a865f18 --- /dev/null +++ b/changelog.d/policyengine-us-all-python-tests.changed.md @@ -0,0 +1 @@ +Run all of policyengine-us main's Python tests, not a list of 13 files, against the Core under test on PRs marked ready, compare them with policyengine-us's latest successful release run, post the result as one bot comment whether or not anything breaks, and tell agents to wait for that comment. diff --git a/docs/engineering/skills/README.md b/docs/engineering/skills/README.md index 5f68e80c7..664dd40ce 100644 --- a/docs/engineering/skills/README.md +++ b/docs/engineering/skills/README.md @@ -12,6 +12,7 @@ Current skills: - `documentation_review.md`: model-neutral review checklist for public API, architecture, documentation, and generated artifact changes. - `github-prs.md`: canonical PR workflow, required changelog fragments, PR head - verification, and title conventions. + verification, title conventions, and the policyengine-us compatibility + comment to wait for. - `testing.md`: test placement, fixture scope, command, and environment expectations. diff --git a/docs/engineering/skills/github-prs.md b/docs/engineering/skills/github-prs.md index 88673c828..2d10c3b55 100644 --- a/docs/engineering/skills/github-prs.md +++ b/docs/engineering/skills/github-prs.md @@ -69,3 +69,25 @@ Keep the description concrete: - Summarize the user-visible behavior change. - List the tests or checks run. - Call out any commands that were not run and why. + +## policyengine-us compatibility + +policyengine-us CI installs each new Core release, so a Core change can break +policyengine-us right after it is released. On every push to a PR marked ready +(not a draft), CI runs policyengine-us main's Python tests (not its YAML tests) +against the PR's Core and compares them with policyengine-us's latest +successful release run. It takes about 30 minutes. Mark a draft ready to start +it. + +Before reporting a PR as ready for review or merge, wait for the bot comment +headed **policyengine-us main against this Core**. The bot keeps one comment +and edits it on each push, so check that its commit is the PR's head commit. + +- **No policyengine-us test breaks**: the PR does not affect policyengine-us's + Python tests. +- **This Core breaks N policyengine-us tests**: list those tests in your + report. The check is neutral, not a failure, because the change may be + intended. If it is, policyengine-us needs a fix right after this Core is + released. +- **No comment for the head commit**: a policyengine-us job failed before + the comparison. Report the failed job; do not treat it as no effect. diff --git a/tests/core/test_country_main_tests.py b/tests/core/test_country_main_tests.py index c47febfe0..98a9cd2b2 100644 --- a/tests/core/test_country_main_tests.py +++ b/tests/core/test_country_main_tests.py @@ -1,12 +1,14 @@ -"""The PolicyEngineUSMain job blames Core only for the tests Core breaks. +"""The policyengine-us jobs blame Core only for the tests Core breaks. -It runs policyengine-us main's listed tests with the Core release and then -with the Core under test (.github/country_main_tests.py). These tests check -the run's exit handling on real pytest runs, the comparison on synthetic -JUnit reports, the file selection, the list, and the job's steps. +They run policyengine-us main's Python tests with the Core under test and +compare them with the JUnit reports of policyengine-us's latest successful +release run (.github/country_main_tests.py). These tests check the run's exit +handling on real pytest runs, the comparison on synthetic JUnit reports, the +report on the PR, and the jobs' steps. """ import importlib.util +import json import sys import urllib.error from pathlib import Path @@ -16,8 +18,8 @@ ROOT = Path(__file__).resolve().parents[2] SCRIPT = ROOT / ".github" / "country_main_tests.py" -LIST = ROOT / ".github" / "requirements" / "policyengine-us-main-tests.txt" WORKFLOW = ROOT / ".github" / "workflows" / "pr.yaml" +SETUP = ROOT / ".github" / "actions" / "policyengine-us-main" / "action.yaml" SPEC = importlib.util.spec_from_file_location("country_main_tests", SCRIPT) country = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(country) @@ -109,14 +111,14 @@ def test_compare_sorts_this_cores_failures_and_absences(): [("t", "a", "failed")], [("t", "a", "failed")], 0, - "::warning::Fails with both Cores: t::a", + "::warning::Fails in both runs: t::a", ), ([("t", "a", "passed")], [("t", "a", "passed")], 0, "No test fails"), ( [("t", "a", "passed"), ("t", "b", "passed")], [("t", "a", "passed"), ("t", "b", "skipped")], 0, - "Passed with the Core release; skipped with this Core: 1\n- `t::b`", + "Passed in the release run; skipped with this Core: 1\n- `t::b`", ), ( [("t.test_b", "test_y", "passed"), ("t.test_a", "test_x", "passed")], @@ -128,43 +130,43 @@ def test_compare_sorts_this_cores_failures_and_absences(): [("t", "a", "passed"), ("t", "b", "passed")], [("t", "a", "passed")], 1, - "::error::Passed with the Core release but did not run: t::b", + "::error::Passed in the release run but did not run: t::b", ), ( [("t", "a", "passed")], [], 1, - "::error::This Core's run recorded no tests.", + "::error::This Core's runs recorded no tests.", ), ( None, [("t", "a", "passed")], 1, - "::error::The Core release's run wrote no JUnit report.", + "::error::There is no JUnit report from the release run.", ), ( [("t", "a", "passed")], None, 1, - "::error::This Core's run wrote no JUnit report.", + "::error::This Core's runs wrote no JUnit report.", ), ( [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], [("t.test_a", "test_x", "passed"), ("t.test_b", "test_y", "failed")], 0, - "the Core release could not collect its file: t.test_b::test_y", + "the release run could not collect its file: t.test_b::test_y", ), ( [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], [("", "t.test_b", "uncollected"), ("t.test_a", "test_x", "passed")], 0, - "::warning::Fails with both Cores: ::t.test_b", + "::warning::Fails in both runs: ::t.test_b", ), ( [("", "t.test_b", "uncollected"), ("", "t.test_c", "module-skipped")], [("", "t.test_b", "uncollected"), ("", "t.test_c", "module-skipped")], 1, - "::error::The Core release's run collected no tests", + "::error::The release run's reports record no tests", ), ], ids=[ @@ -202,6 +204,42 @@ def test_compare_fails_only_when_the_comparison_cannot_be_trusted( assert message in capsys.readouterr().out +def test_compare_reads_every_report_under_each_directory(tmp_path, capsys): + released, candidate = tmp_path / "released", tmp_path / "candidate" + (released / "shard-1").mkdir(parents=True) + (candidate / "spm").mkdir(parents=True) + (candidate / "rest-1").mkdir(parents=True) + junit(released / "shard-1" / "rest.xml", [("t", "a", "passed")]) + junit(released / "spm.xml", [("s", "b", "passed")]) + junit(candidate / "rest-1" / "rest.xml", [("t", "a", "passed")]) + junit(candidate / "spm" / "spm.xml", [("s", "b", "failed")]) + # A contrib test the release run kept no report of. + junit(candidate / "contrib.xml", [("c", "d", "failed"), ("c", "e", "passed")]) + result = tmp_path / "result.json" + baseline = "policyengine-us release run [1](https://example.com/1)" + arguments = ["compare", str(released), str(candidate), "--baseline", baseline] + arguments += ["--summary", str(tmp_path / "summary.md"), "--json", str(result)] + assert country.main(arguments) == 0 + output = capsys.readouterr().out + assert "::warning::This Core breaks s::b" in output + assert "::warning::This Core breaks c::d" in output + assert f"Compared with {baseline}." in output + assert "- In the release run: 2 passed, 0 failed, 0 skipped" in output + assert "- With this Core: 2 passed, 2 failed, 0 skipped" in output + saved = json.loads(result.read_text()) + assert (saved["broken"], saved["baseline"]) == (["c::d", "s::b"], baseline) + + +def test_the_summary_lists_at_most_a_set_number_of_tests_per_kind(): + tests = [f"t::{index:04}" for index in range(country.SUMMARY_LISTED + 5)] + result = {key: [] for key in ("broken", "uncollected", "skipped", "unsure")} + result.update(missing=tests, both=[]) + text = country.summary({test: "passed" for test in tests}, {}, result) + assert f"- `{tests[country.SUMMARY_LISTED - 1]}`" in text + assert f"- `{tests[country.SUMMARY_LISTED]}`" not in text + assert "- ...and 5 more in the compare step's log." in text + + class FakeGitHub: """Records API calls; GET returns the PR's comments.""" @@ -230,6 +268,7 @@ def writes(self): "PR_NUMBER": "635", "RUN_URL": "https://github.com/PolicyEngine/policyengine-core/actions/runs/1", } +BASELINE = "policyengine-us release run [9](https://example.com/9)" BOT_COMMENT = { "id": 7, "user": {"login": "github-actions[bot]"}, @@ -247,6 +286,7 @@ def compared(tmp_path, candidate_outcome): str(tmp_path / "candidate.xml"), ] arguments += ["--summary", str(tmp_path / "summary.md"), "--json", str(result)] + arguments += ["--baseline", BASELINE] assert country.main(arguments) == 0 return result @@ -256,7 +296,7 @@ def compared(tmp_path, candidate_outcome): [ ("failed", [], "neutral", "POST"), ("failed", [BOT_COMMENT], "neutral", "PATCH"), - ("passed", [], "success", None), + ("passed", [], "success", "POST"), ("passed", [BOT_COMMENT], "success", "PATCH"), ( "failed", @@ -268,7 +308,7 @@ def compared(tmp_path, candidate_outcome): ids=[ "break-new-comment", "break-updates-comment", - "no-break-no-comment", + "no-break-new-comment", "fixed-updates-comment", "ignores-other-authors", ], @@ -284,9 +324,7 @@ def test_report_shows_breaks_as_a_neutral_check_and_one_comment( assert check[2]["name"] == "policyengine-us compatibility" assert check[2]["head_sha"] == ENV["HEAD_SHA"] assert check[2]["conclusion"] == conclusion - if comment_call is None: - assert comment == [] - return + # One comment either way, so whoever waits for it gets an answer. ((method, path, payload),) = comment assert method == comment_call assert path == ( @@ -296,11 +334,15 @@ def test_report_shows_breaks_as_a_neutral_check_and_one_comment( ) assert payload["body"].startswith(country.MARKER) if conclusion == "neutral": - assert "This Core breaks 1 policyengine-us test that" in payload["body"] + assert ( + f"This Core breaks 1 policyengine-us test that passed in {BASELINE}:" + in payload["body"] + ) assert "- `t::a`" in payload["body"] else: assert ( - "No policyengine-us test breaks with this Core any more" in payload["body"] + "No policyengine-us test breaks: every policyengine-us Python test that " + f"passed in {BASELINE} still passes with this Core." in payload["body"] ) assert "`abcdef1`" in payload["body"] @@ -360,88 +402,181 @@ def test_run_fails_unless_pytest_ran_every_test( assert country.outcomes("report.xml")["test_ok::test_ok"] == "passed" -def test_select_skips_files_the_checkout_lacks(tmp_path, capsys): - repo = tmp_path / "policyengine-us" - (repo / "tests").mkdir(parents=True) - (repo / "tests" / "test_kept.py").write_text("") - listing = tmp_path / "list.txt" - listing.write_text( - "# comment\n\ntests/test_kept.py # trailing comment\ntests/test_gone.py\n" - "deselect tests/test_kept.py::test_slow # downloads data\n" - "deselect tests/test_gone.py::test_other\n" - ) - assert country.select(listing, repo) == ( - ["tests/test_kept.py", "--deselect=tests/test_kept.py::test_slow"], - ["tests/test_gone.py"], +POLICYENGINE_US_JOBS = [ + "PolicyEngineUSPlan", + "PolicyEngineUSRest", + "PolicyEngineUSMicrosimulation", + "PolicyEngineUSSPM", + "PolicyEngineUSContrib", + "PolicyEngineUSCompare", +] +TEST_JOBS = POLICYENGINE_US_JOBS[1:-1] + + +def workflow(): + return yaml.safe_load(WORKFLOW.read_text()) + + +def steps_of(job): + return {step["name"]: step for step in workflow()["jobs"][job]["steps"]} + + +def test_the_policyengine_us_jobs_run_on_prs_marked_ready(): + triggers = workflow()[True]["pull_request"] + assert "ready_for_review" in triggers["types"] + assert {"opened", "synchronize", "reopened"} <= set(triggers["types"]) + jobs = workflow()["jobs"] + assert jobs["PolicyEngineUSPlan"]["if"] == ( + "${{ !github.event.pull_request.draft }}" ) - assert country.main(["select", str(listing), str(repo)]) == 0 - captured = capsys.readouterr() - assert captured.out == ( - "tests/test_kept.py\n--deselect=tests/test_kept.py::test_slow\n" + # Every other job waits for the plan, so a draft skips them all. + for name in POLICYENGINE_US_JOBS[1:]: + needs = jobs[name]["needs"] + assert "PolicyEngineUSPlan" in ([needs] if isinstance(needs, str) else needs) + assert jobs["PolicyEngineUSCompare"]["needs"] == POLICYENGINE_US_JOBS[:-1] + + +def test_every_job_installs_this_core_at_the_release_runs_commit(): + for name in POLICYENGINE_US_JOBS[:-1]: + setup = steps_of(name)["Set up policyengine-us with this Core"] + assert setup["uses"] == "./core/.github/actions/policyengine-us-main" + expected = ( + "${{ steps.release.outputs.sha }}" + if name == "PolicyEngineUSPlan" + else "${{ needs.PolicyEngineUSPlan.outputs.sha }}" + ) + assert setup["with"]["ref"] == expected + action = { + step["name"]: step + for step in yaml.safe_load(SETUP.read_text())["runs"]["steps"] + } + checkout = action["Checkout policyengine-us"]["with"] + assert (checkout["repository"], checkout["ref"]) == ( + "PolicyEngine/policyengine-us", + "${{ inputs.ref }}", ) - assert "::warning::policyengine-us main has no tests/test_gone.py" in captured.err - listing.write_text("tests/test_gone.py\ndeselect tests/test_gone.py::test_x\n") - assert country.main(["select", str(listing), str(repo)]) == 1 - - -def test_the_list_names_distinct_policyengine_us_test_files(): - files, deselected = country.listed_entries(LIST) - assert files, "the list is empty" - assert len(files) == len(set(files)), "a file is listed twice" - for path in files: - assert path.startswith("policyengine_us/tests/"), path - assert Path(path).name.startswith("test_") and path.endswith(".py"), path - for test in deselected: - assert test.split("::")[0] in files, test - - -def test_the_job_runs_the_release_then_this_core_and_compares_them(): - job = yaml.safe_load(WORKFLOW.read_text())["jobs"]["PolicyEngineUSMain"] - names = [step["name"] for step in job["steps"]] - assert names == [ - "Checkout repo", - "Checkout policyengine-us main", - "Set up Python", - "Install uv", - "Install policyengine-us main with the Core release", - "Select the policyengine-us tests", - "Run them with the Core release", - "Install this Core", - "Run them with this Core", - "Compare the two runs", - "Report the result on the PR", - ] - steps = {step["name"]: step for step in job["steps"]} - us = steps["Checkout policyengine-us main"]["with"] - assert (us["repository"], us["ref"]) == ("PolicyEngine/policyengine-us", "main") - # Both runs go through the script's pytest command and its exit handling. - run = "python ../core/.github/country_main_tests.py run ../selected.txt" - released = steps["Run them with the Core release"]["run"] - assert released.splitlines()[-1] == f"{run} ../released.xml" - assert steps["Run them with this Core"]["run"] == f"{run} ../candidate.xml" - assert all("|| true" not in step.get("run", "") for step in job["steps"]) - # The candidate replaces the release even at the same version number, the - # job checks that it was installed from this checkout, and the dependency - # set must still resolve. - install = steps["Install this Core"]["run"] + # The candidate replaces the locked Core even at the same version number, + # the step checks that it was installed from the checkout, and the + # dependency set must still resolve. + install = action["Install this Core"]["run"] assert "--reinstall-package policyengine-core ../core" in install assert "assert url.startswith('file://')" in install assert "uv pip check --python .venv/bin/python" in install + + +def test_the_plan_uses_the_release_runs_reports_and_policyengine_uss_planner(): + steps = steps_of("PolicyEngineUSPlan") + release = steps["Download the latest successful release run's reports"]["run"] + assert "--status success" in release + assert '.displayTitle == "Update PolicyEngine US" and .attempt == 1' in release + for pattern in ( + "'rest-python-test-timings-*'", + "simulation-test-timings", + "spm-test-timings", + ): + assert f"--pattern {pattern}" in release + plan = steps["Plan the Rest Python shards"]["run"] + assert plan.startswith( + "uv run --no-sync python policyengine_us/tests/rest_python_shards.py plan " + "--timings ../released" + ) + kept = steps["Keep the release run's reports for the comparison"]["with"] + assert kept == {"name": "policyengine-us-released", "path": "released"} + + +def test_test_jobs_report_every_test_for_compare_to_judge(): + tests = { + "PolicyEngineUSRest": "Run the shard's Rest Python tests", + "PolicyEngineUSMicrosimulation": "Run the microsimulation tests", + "PolicyEngineUSSPM": "Run the SPM tests", + } + for job, name in tests.items(): + step = steps_of(job)[name] + # compare decides what a failure means and finds the tests a stopped + # run left out. + assert step["continue-on-error"] is True + assert "--continue-on-collection-errors" in step["env"]["PYTEST_ADDOPTS"] + # The step's block scalar ends with a newline. + rest = steps_of("PolicyEngineUSRest")[tests["PolicyEngineUSRest"]]["run"] + assert rest.rstrip().endswith("rest_python_shards.py run --report-dir ../candidate") + assert ( + steps_of("PolicyEngineUSMicrosimulation")["Run the microsimulation tests"][ + "run" + ] + == "uv run --no-sync make test-microsimulation" + ) + assert ( + steps_of("PolicyEngineUSSPM")["Run the SPM tests"]["run"] + == "uv run --no-sync make test-other-python-spm" + ) + # No report lists the contrib tests that ran, so the script's run fails + # the job if pytest stops early. + contrib = steps_of("PolicyEngineUSContrib")["Run the contrib Python tests"] + assert "continue-on-error" not in contrib + assert contrib["run"].splitlines()[-1] == ( + "python ../core/.github/country_main_tests.py run ../contrib.txt " + "../candidate/contrib-python.xml" + ) + # Each job keeps its reports where compare downloads them from. + for job in TEST_JOBS: + kept = [ + step + for step in workflow()["jobs"][job]["steps"] + if step["name"].startswith("Keep the report") + ] + assert len(kept) == 1 + assert kept[0]["if"] == "always()" + assert kept[0]["with"]["name"].startswith("policyengine-us-candidate-") + compare = steps_of("PolicyEngineUSCompare") + assert compare["Download this Core's reports"]["with"] == { + "pattern": "policyengine-us-candidate-*", + "path": "candidate", + } + assert compare["Download the release run's reports"]["with"] == { + "name": "policyengine-us-released", + "path": "released", + } + + +def test_compare_puts_the_result_on_the_pr(): + job = workflow()["jobs"]["PolicyEngineUSCompare"] + assert job["if"] == ( + "${{ !cancelled() && needs.PolicyEngineUSPlan.result == 'success' }}" + ) + steps = steps_of("PolicyEngineUSCompare") + names = list(steps) + # A job that ran less than compare can see fails the job before the + # result goes on the PR. + assert names.index("Check every test job finished") < names.index( + "Report the result on the PR" + ) + finished = steps["Check every test job finished"]["env"] + assert sorted(finished.values()) == sorted( + f"${{{{ needs.{job}.result }}}}" for job in TEST_JOBS + ) # The job summary has the full result, as the PR comment and the warning # without write access say. - assert steps["Compare the two runs"]["run"].endswith( - 'compare released.xml candidate.xml --summary "$GITHUB_STEP_SUMMARY" ' - "--json result.json" + compare = steps["Compare this Core's runs with the release run"] + assert compare["run"] == ( + "python3 core/.github/country_main_tests.py compare released candidate " + '--baseline "$BASELINE" --summary "$GITHUB_STEP_SUMMARY" --json result.json' + ) + assert compare["env"]["BASELINE"] == ( + "${{ needs.PolicyEngineUSPlan.outputs.baseline }}" ) # The result goes on the PR's head commit as a check, and as a comment. report = steps["Report the result on the PR"] assert ( - report["run"] == "python core/.github/country_main_tests.py report result.json" + report["run"] == "python3 core/.github/country_main_tests.py report result.json" ) assert report["env"]["HEAD_SHA"] == "${{ github.event.pull_request.head.sha }}" assert report["env"]["PR_NUMBER"] == "${{ github.event.pull_request.number }}" - assert job["permissions"] == { + # Only compare can write to the PR. + jobs = workflow()["jobs"] + assert jobs["PolicyEngineUSCompare"]["permissions"] == { "contents": "read", "checks": "write", "pull-requests": "write", } + for name in POLICYENGINE_US_JOBS[:-1]: + assert "write" not in jobs[name]["permissions"].values()