diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index 800322e2..753d06a8 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -17,11 +17,39 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads + # them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The + # jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so + # the required context still reports. This workflow has no gate job, so the scan runs whenever the + # class is not "docs" or "inert": a classifier that fails or prints nothing means a full scan. The clone has every commit but no file contents (blob:none): the + # script only compares file names between the base and the head. + changes: + name: change class + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + class: ${{ steps.classify.outputs.class }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + - name: Classify the changed files + id: classify + env: + EVENT_NAME: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }} + run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT" + security: name: bandit (high severity) + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest # ceil(1.5 x slowest of three green main runs) + 3, never under 5 (test.yml): runs 40257217665, - # 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. + # 40254137380, 40240706583 took 23s / 16s / 23s -> 5 min. change class (#639): 5 min, the floor. timeout-minutes: 5 steps: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d276cd0d..7c2f5157 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,26 +35,60 @@ env: # perf budget 30s / 29s / 27s, black and flake8 39s / 37s / 39s, # frontend modules 23s / 19s / 29s -> 5 min (the floor) # all tests: a result check without setup, 5 min (the floor) +# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor) # # Pull requests run a fast subset (#420): Python 3.12 on ubuntu-latest, coverage, lint and frontend # modules. The merge queue (merge_group), pushes to main and manual runs add Python 3.13 and 3.14 on # Linux and the real ComfyUI job. "all tests" is the required gate that holds the queue to that set. # Windows runs in portability.yml (push to main, nightly, on demand) and never gate a merge. jobs: + # Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads + # them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The + # jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so + # the required contexts still report; "all tests" fails unless this job succeeded and each + # job did what the class asks. The clone has every commit but no file contents (blob:none): the + # script only compares file names between the base and the head. + changes: + name: change class + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + class: ${{ steps.classify.outputs.class }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + - name: Classify the changed files + id: classify + env: + EVENT_NAME: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }} + run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT" + test: name: py${{ matrix.python-version }} on ${{ matrix.os }} + # A skipped matrix job reports under its unexpanded name, which would leave the required context + # "py3.12 on ubuntu-latest" waiting for ever. So this job always runs: a docs change gets the 3.12 + # leg only, and for an inert change the leg starts and its steps are skipped (#639). + needs: changes + if: ${{ !cancelled() }} runs-on: ${{ matrix.os }} timeout-minutes: 27 strategy: fail-fast: false matrix: os: [ubuntu-latest] - python-version: ${{ github.event_name == 'pull_request' && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }} + python-version: ${{ (github.event_name == 'pull_request' || needs.changes.outputs.class == 'docs' || needs.changes.outputs.class == 'inert') && fromJSON('["3.12"]') || fromJSON('["3.12", "3.13", "3.14"]') }} steps: - uses: actions/checkout@v7 + if: needs.changes.outputs.class != 'inert' - name: Set up Python ${{ matrix.python-version }} + if: needs.changes.outputs.class != 'inert' uses: actions/setup-python@v7 with: python-version: ${{ matrix.python-version }} @@ -62,18 +96,26 @@ jobs: cache-dependency-path: requirements-dev.txt - name: Install dependencies + if: needs.changes.outputs.class != 'inert' run: | python -m pip install --upgrade pip pip install -r requirements-dev.txt - name: Run tests + if: needs.changes.outputs.class != 'inert' run: python -m tests.run_suite -v + - name: Nothing to test + if: needs.changes.outputs.class == 'inert' + run: echo "Only inert files changed (tools/ci/change_class.py); no test can be affected." + comfyui: name: real ComfyUI compatibility # Merge queue, main and manual runs only. A job skipped by its condition reports Success, so this - # required context never blocks a pull request; "all tests" fails if it is skipped anywhere else. - if: github.event_name != 'pull_request' + # required context never blocks a pull request; "all tests" fails if it is skipped anywhere else + # for a code change. Docs and inert changes skip it everywhere (#639). + needs: changes + if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest # Chromium and its system libraries come from the pinned Playwright image (tag = @playwright/test in # tools/vendor/package-lock.json; tests/vendor/browser-image.test.mjs checks it). The runner install @@ -174,6 +216,8 @@ jobs: coverage: name: coverage gate (85%) + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -201,7 +245,8 @@ jobs: # Shared-runner timing varies, so it never gates a pull request: it runs on # each push to main and on demand. A red run on main means fix the code. name: perf budget - if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' + needs: changes + if: ${{ !cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -225,6 +270,8 @@ jobs: lint: name: black and flake8 + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -241,6 +288,8 @@ jobs: js-test: name: frontend modules + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -268,9 +317,11 @@ jobs: # The required context "all tests". A dropped matrix leg never reports a check at all, so the eight # legs that pull requests skip cannot be required by name; this gate requires them instead. Every # job must succeed; real ComfyUI must be skipped on a pull request and succeed on every other event. + # For a docs or inert change (#639) the test matrix must still succeed and every other job must be + # skipped. The classifier itself must succeed, and a class it does not print fails the gate. all-tests: name: all tests - needs: [test, comfyui, coverage, lint, js-test] + needs: [changes, test, comfyui, coverage, lint, js-test] if: always() runs-on: ubuntu-latest timeout-minutes: 5 @@ -278,18 +329,26 @@ jobs: - name: Require every test job for this event env: EVENT_NAME: ${{ github.event_name }} + CHANGES_RESULT: ${{ needs.changes.result }} + CHANGE_CLASS: ${{ needs.changes.outputs.class }} TEST_RESULT: ${{ needs.test.result }} COMFYUI_RESULT: ${{ needs.comfyui.result }} COVERAGE_RESULT: ${{ needs.coverage.result }} LINT_RESULT: ${{ needs.lint.result }} JS_RESULT: ${{ needs.js-test.result }} run: | - queue_only=success + echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)" + test "$CHANGES_RESULT" = success + case "$CHANGE_CLASS" in + code) code_only=success; queue_only=success ;; + docs|inert) code_only=skipped; queue_only=skipped ;; + *) echo "::error::unknown change class"; exit 1 ;; + esac if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi - echo "event: $EVENT_NAME (real ComfyUI must be $queue_only)" + echo "event: $EVENT_NAME (real ComfyUI must be $queue_only; coverage, lint and js-test must be $code_only)" echo "test matrix: $TEST_RESULT" echo "comfyui: $COMFYUI_RESULT" echo "coverage: $COVERAGE_RESULT" echo "lint: $LINT_RESULT" echo "js-test: $JS_RESULT" - test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = success && test "$LINT_RESULT" = success && test "$JS_RESULT" = success && test "$COMFYUI_RESULT" = "$queue_only" + test "$TEST_RESULT" = success && test "$COVERAGE_RESULT" = "$code_only" && test "$LINT_RESULT" = "$code_only" && test "$JS_RESULT" = "$code_only" && test "$COMFYUI_RESULT" = "$queue_only" diff --git a/.github/workflows/viewerjs-check.yml b/.github/workflows/viewerjs-check.yml index 6aca9e43..b032d7e2 100644 --- a/.github/workflows/viewerjs-check.yml +++ b/.github/workflows/viewerjs-check.yml @@ -45,9 +45,39 @@ concurrency: # test (PR #560 shard 2/3: 814 passed in 17.9m; queue run 41206495451 shard 1/3: 827 passed; PR #564 # shard 2/3 twice), against recent green shards of 11m-17m. Coverage now runs in four shards with the # limits unchanged; the per-shard times are re-measured after three green main runs. +# change class (#639): a file-less checkout and one stdlib script, 5 min (the floor of test.yml). jobs: + # Sorts the change by the files it touches (tools/ci/change_class.py, #639): "inert" (nothing reads + # them), "docs" (a Python test reads them) or "code" (anything else, and every case of doubt). The + # jobs below skip what the class cannot affect. A job skipped by its condition reports Success, so + # the required contexts still report; "viewerjs" fails unless this job succeeded and each + # job did what the class asks. The clone has every commit but no file contents (blob:none): the + # script only compares file names between the base and the head. + changes: + name: change class + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + class: ${{ steps.classify.outputs.class }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + - name: Classify the changed files + id: classify + env: + EVENT_NAME: ${{ github.event_name }} + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }} + run: python3 tools/ci/change_class.py | tee -a "$GITHUB_OUTPUT" + frontend-coverage: name: frontend coverage (shard ${{ matrix.shard }}/4) + # Code changes only (#639): no browser test reads a docs or inert file. + needs: changes + if: ${{ !cancelled() && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest # Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the # same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json; @@ -117,7 +147,8 @@ jobs: frontend-coverage-merge: name: frontend coverage (merge) - needs: frontend-coverage + needs: [changes, frontend-coverage] + if: ${{ !cancelled() && needs.frontend-coverage.result == 'success' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest # Same image as the shards: the raw files name sources by the container's workspace path. container: @@ -186,7 +217,9 @@ jobs: browser-workflows: name: page workflows (${{ matrix.browser }}, shard ${{ matrix.shard }}/3) # Merge queue, main and manual runs only (#420); pull requests run the Chromium/touch coverage shards. - if: github.event_name != 'pull_request' + # Code changes only (#639). + needs: changes + if: ${{ !cancelled() && github.event_name != 'pull_request' && needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert' }} runs-on: ubuntu-latest # Layout comparisons depend on the fonts each browser falls back to, so browser jobs run in the # same pinned Playwright image as local runs (tag = @playwright/test in tools/vendor/package-lock.json; @@ -245,9 +278,10 @@ jobs: # Branch protection requires the exact context "viewerjs". This job keeps that # name and fails unless every coverage shard and the coverage merge succeeded and # the browser shards succeeded, or, on a pull request only, were skipped (#420). - # Any failure, cancellation or other skip fails it. + # Any failure, cancellation or other skip fails it. For a docs or inert change (#639) all three + # must be skipped. The classifier itself must succeed, and a class it does not print fails the gate. viewerjs: - needs: [frontend-coverage, frontend-coverage-merge, browser-workflows] + needs: [changes, frontend-coverage, frontend-coverage-merge, browser-workflows] if: always() runs-on: ubuntu-latest timeout-minutes: 5 @@ -255,14 +289,22 @@ jobs: - name: Require every frontend job to succeed env: EVENT_NAME: ${{ github.event_name }} + CHANGES_RESULT: ${{ needs.changes.result }} + CHANGE_CLASS: ${{ needs.changes.outputs.class }} COVERAGE_RESULT: ${{ needs.frontend-coverage.result }} MERGE_RESULT: ${{ needs.frontend-coverage-merge.result }} WORKFLOWS_RESULT: ${{ needs.browser-workflows.result }} run: | - queue_only=success + echo "change class: $CHANGE_CLASS (classifier: $CHANGES_RESULT)" + test "$CHANGES_RESULT" = success + case "$CHANGE_CLASS" in + code) code_only=success; queue_only=success ;; + docs|inert) code_only=skipped; queue_only=skipped ;; + *) echo "::error::unknown change class"; exit 1 ;; + esac if [ "$EVENT_NAME" = pull_request ]; then queue_only=skipped; fi - echo "event: $EVENT_NAME (browser-workflows must be $queue_only)" + echo "event: $EVENT_NAME (browser-workflows must be $queue_only; coverage and its merge must be $code_only)" echo "frontend-coverage: $COVERAGE_RESULT" echo "frontend-coverage-merge: $MERGE_RESULT" echo "browser-workflows: $WORKFLOWS_RESULT" - test "$COVERAGE_RESULT" = success && test "$MERGE_RESULT" = success && test "$WORKFLOWS_RESULT" = "$queue_only" + test "$COVERAGE_RESULT" = "$code_only" && test "$MERGE_RESULT" = "$code_only" && test "$WORKFLOWS_RESULT" = "$queue_only" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9106e4fc..68583394 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,9 +22,10 @@ repos: types: [python] exclude: ^(tests/|reference/) + # Skipped when the pushed commits only change inert files (tools/ci/change_class.py, #639). - id: tests name: tests - entry: python -m tests.run_suite -q + entry: python tools/ci/change_class.py --unless-inert python -m tests.run_suite -q language: system pass_filenames: false stages: [pre-push] diff --git a/TESTING.md b/TESTING.md index 1b127eda..757b79d6 100644 --- a/TESTING.md +++ b/TESTING.md @@ -742,6 +742,33 @@ is still a failure: fix it at its cause, not by rerunning, and have every one green before the workspace cutover (#334). `tests/vendor/ci-workflow.test.mjs` pins the event split and runs both gate scripts for each event. +### Only changes that can affect code are tested (#639) + +The table above is for a code change. Each of the three workflows starts with a +`change class` job that runs `tools/ci/change_class.py` over the files the pull +request, merge group or push touches, and the other jobs follow its answer: + +| Class | Files (allowlists in the script) | What runs | +| --- | --- | --- | +| `inert` | `.github/FUNDING.yml`, `SECURITY.md`, `images/`, `.github/ISSUE_TEMPLATE/` | `change class` and the two gates. `py3.12 on ubuntu-latest` starts and skips its steps, because a skipped matrix job would never report that required context. | +| `docs` | `README.md`, `README-legacy.md`, `assets/readme/`, `assets/brand/` (may include inert files) | The above plus the real `py3.12 on ubuntu-latest` suite, which holds the tests that read them (`tests/test_brand_assets.py`, `tests/test_package_contents.py`). | +| `code` | Anything else | Everything in the table above. | + +A file on no list is code, and so is every case of doubt: no changed files, a +manual run, a range git cannot read. `docs/` is code, because the browser suite +compares production against `docs/concepts/workspace/`; `TESTING.md` is code, +because the tooling tests read its tables. Before adding a file to a list, +check that no test and no shipped code opens it. + +The gates enforce the class: for `docs` and `inert` they require the classifier +to have succeeded, the Python matrix to have succeeded and every other job to +have been skipped; a class the script does not print fails them. `bandit` has no +gate, so it runs unless the class is `docs` or `inert`, which means a failed +classifier gets a full scan. The required contexts do not change. + +The pre-push hook uses the same script: it skips the Python suite when the +pushed commits are `inert` and runs it otherwise. + ## Required merge checks `.github/branch-protection.json` records the required checks: diff --git a/tests/test_ci_change_class.py b/tests/test_ci_change_class.py new file mode 100644 index 00000000..712e72c7 --- /dev/null +++ b/tests/test_ci_change_class.py @@ -0,0 +1,206 @@ +"""CI runs tests only for changes that can affect code (#639). + +``tools/ci/change_class.py`` sorts a change by the files it touches: ``inert`` +(nothing reads the file at run or test time), ``docs`` (a Python test reads +it) or ``code`` (everything else, and every case of doubt). +""" + +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools" / "ci")) +import change_class # noqa: E402 + +SCRIPT = ROOT / "tools" / "ci" / "change_class.py" + + +class TestClassify(unittest.TestCase): + def test_files_nothing_reads_are_inert(self): + for paths in ( + [".github/FUNDING.yml"], + ["SECURITY.md"], + ["images/pm-01.png", ".github/ISSUE_TEMPLATE/bug_report.md"], + ): + self.assertEqual(change_class.classify(paths), "inert", paths) + + def test_documents_a_test_reads_are_docs(self): + for paths in ( + ["README.md"], + ["README-legacy.md", "assets/readme/hero.webp"], + ["assets/brand/banner.webp", ".github/FUNDING.yml"], + ): + self.assertEqual(change_class.classify(paths), "docs", paths) + + def test_anything_else_is_code(self): + for paths in ( + ["py/api/images.py"], + ["README.md", "web/js/workspace/index.mjs"], + [".github/FUNDING.yml", "pyproject.toml"], + # The browser suite compares production against the concept. + ["docs/concepts/workspace/app.js"], + # The tooling tests read the tables in it. + ["TESTING.md"], + [".github/workflows/test.yml"], + ["LICENSE"], + # Look-alikes of listed names are not listed. + ["docs/README.md"], + ["web/images/x.png"], + ["SECURITY.md.py"], + [".github/funding.yml"], + ): + self.assertEqual(change_class.classify(paths), "code", paths) + + def test_no_files_is_code(self): + self.assertEqual(change_class.classify([]), "code") + + def test_every_document_a_test_reads_exists(self): + for name in change_class.DOCS_FILES: + self.assertTrue((ROOT / name).is_file(), name) + for folder in change_class.DOCS_FOLDERS: + self.assertTrue((ROOT / folder).is_dir(), folder) + + +class TestCommandLine(unittest.TestCase): + """The script against a real repository with one commit per kind of change.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.repo = Path(self.tmp.name) + self.git("init", "-q", "-b", "main") + self.commit({"py/a.py": "a\n", "README.md": "r\n"}) + self.base = self.head() + + def git(self, *args): + return subprocess.run( + ["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], + cwd=self.repo, + check=True, + capture_output=True, + text=True, + ).stdout.strip() + + def commit(self, files): + for name, text in files.items(): + path = self.repo / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + self.git("add", "-A") + self.git("commit", "-q", "-m", "change") + + def head(self): + return self.git("rev-parse", "HEAD") + + def run_script(self, *args, **env): + clean = { + key: value + for key, value in os.environ.items() + if key not in change_class.ENVIRONMENT + } + return subprocess.run( + [sys.executable, str(SCRIPT), *args], + cwd=self.repo, + env={**clean, **env}, + capture_output=True, + text=True, + ) + + def class_of(self, **env): + result = self.run_script(**env) + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.strip() + + def test_a_pull_request_is_classed_by_its_own_files(self): + self.git("checkout", "-q", "-b", "topic") + self.commit({".github/FUNDING.yml": "x\n"}) + topic = self.head() + # main moved on with code meanwhile: that is not this pull request's change. + self.git("checkout", "-q", "main") + self.commit({"py/a.py": "b\n"}) + self.assertEqual( + self.class_of( + EVENT_NAME="pull_request", BASE_SHA=self.head(), HEAD_SHA=topic + ), + "class=inert", + ) + + def test_a_merge_group_and_a_push_are_classed_by_their_range(self): + self.commit({"README.md": "r2\n"}) + for event in ("merge_group", "push"): + self.assertEqual( + self.class_of( + EVENT_NAME=event, BASE_SHA=self.base, HEAD_SHA=self.head() + ), + "class=docs", + event, + ) + self.commit({"py/a.py": "c\n"}) + self.assertEqual( + self.class_of( + EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head() + ), + "class=code", + ) + + def test_a_deleted_or_renamed_file_counts_under_both_names(self): + self.git("mv", "py/a.py", "SECURITY.md") + self.git("commit", "-q", "-m", "rename") + self.assertEqual( + self.class_of( + EVENT_NAME="merge_group", BASE_SHA=self.base, HEAD_SHA=self.head() + ), + "class=code", + ) + + def test_doubt_is_code(self): + self.commit({".github/FUNDING.yml": "x\n"}) + head = self.head() + zero = "0" * 40 + for env in ( + {"EVENT_NAME": "workflow_dispatch", "BASE_SHA": self.base}, + {"EVENT_NAME": "schedule", "BASE_SHA": self.base, "HEAD_SHA": head}, + {"EVENT_NAME": "push", "BASE_SHA": zero, "HEAD_SHA": head}, + {"EVENT_NAME": "push", "BASE_SHA": "", "HEAD_SHA": head}, + {"EVENT_NAME": "push", "BASE_SHA": "f" * 40, "HEAD_SHA": head}, + {"EVENT_NAME": "push", "BASE_SHA": head, "HEAD_SHA": head}, + {}, + ): + self.assertEqual(self.class_of(**env), "class=code", env) + + def test_the_pre_push_command_is_skipped_only_for_an_inert_push(self): + marker = self.repo / "ran" + command = ( + "--unless-inert", + sys.executable, + "-c", + "open('ran', 'w').close()", + ) + self.commit({".github/FUNDING.yml": "x\n"}) + refs = {"PRE_COMMIT_FROM_REF": self.base, "PRE_COMMIT_TO_REF": self.head()} + result = self.run_script(*command, **refs) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(marker.exists()) + self.assertIn("inert", result.stdout) + # No range from pre-commit (a manual run) and a docs push both run it. + self.assertEqual(self.run_script(*command).returncode, 0) + self.assertTrue(marker.exists()) + marker.unlink() + self.commit({"README.md": "r3\n"}) + refs["PRE_COMMIT_TO_REF"] = self.head() + self.assertEqual(self.run_script(*command, **refs).returncode, 0) + self.assertTrue(marker.exists()) + + def test_the_pre_push_command_keeps_its_exit_code(self): + result = self.run_script( + "--unless-inert", sys.executable, "-c", "raise SystemExit(7)" + ) + self.assertEqual(result.returncode, 7) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/vendor/ci-workflow.test.mjs b/tests/vendor/ci-workflow.test.mjs index 3bd96145..00f5b821 100644 --- a/tests/vendor/ci-workflow.test.mjs +++ b/tests/vendor/ci-workflow.test.mjs @@ -67,9 +67,16 @@ const browserJobIds = [...allJobs].filter(([, body]) => /npm run --prefix tools\ const mergeJob = () => allJobs.get('frontend-coverage-merge'); const verifyStep = () => steps(mergeJob()).find(step => /name: Verify every shard's raw coverage arrived/.test(step)); +// #639: each workflow classifies the change first (tools/ci/change_class.py). Jobs that only a code +// change can affect skip for the classes "docs" and "inert", and run when the classifier failed. +const escapeRegExp = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const jobIf = condition => new RegExp(`^ {4}if: ${escapeRegExp(`\${{ ${condition} }}`)}$`, 'm'); +const CODE_CLASS = "needs.changes.outputs.class != 'docs' && needs.changes.outputs.class != 'inert'"; +const CODE_ONLY_IF = jobIf(`!cancelled() && ${CODE_CLASS}`); // Jobs that run only in the merge queue, on main and on demand (#420): skipped on pull_request. -const QUEUE_ONLY_IF = /^ {4}if: github\.event_name != 'pull_request'$/m; +const QUEUE_ONLY_IF = jobIf(`!cancelled() && github.event_name != 'pull_request' && ${CODE_CLASS}`); const EVENTS = ['pull_request', 'merge_group', 'push', 'workflow_dispatch']; +const CLASSES = ['code', 'docs', 'inert']; function gateVariables(jobText) { return new Map([...jobText.matchAll(/^ {10}([A-Z_]+): \$\{\{ needs\.([\w-]+)\.result \}\}$/gm)] @@ -86,21 +93,36 @@ function runGate(jobText, env) { } } -// A gate passes only when every always-on job succeeded and every queue-only job is skipped on a -// pull request and succeeded on every other event. Anything else fails it. -function assertGateBehaviour(jobText, queueOnly) { +// A gate passes only when the classifier succeeded and every job did what the change class and the +// event ask (#639). For a code change: every always-on and code-only job succeeded, and every +// queue-only job is skipped on a pull request and succeeded on every other event. For a docs or +// inert change: every always-on job succeeded and every other job is skipped. Anything else fails +// it, and so does a class the classifier does not print. +function assertGateBehaviour(jobText, { queueOnly, codeOnly, always = [] }) { assert.match(jobText, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m, 'the gate knows the event'); + assert.match(jobText, /^ {10}CHANGE_CLASS: \$\{\{ needs\.changes\.outputs\.class \}\}$/m, 'the gate knows the change class'); const variables = gateVariables(jobText); - for (const id of queueOnly) assert.ok(variables.has(id), `${id} reaches the gate`); - for (const event of EVENTS) { - const expected = id => (queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success'); - const green = Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])); - assert.equal(runGate(jobText, { ...green, EVENT_NAME: event }), true, `${event}: the expected results pass`); - for (const [id, name] of variables) { - for (const result of ['success', 'failure', 'cancelled', 'skipped']) { - if (result === expected(id)) continue; - assert.equal(runGate(jobText, { ...green, EVENT_NAME: event, [name]: result }), false, - `${event}: ${id}=${result} must fail the gate`); + assert.deepEqual([...variables.keys()].sort(), ['changes', ...queueOnly, ...codeOnly, ...always].sort(), + 'every job the gate reads has an expected result'); + for (const changeClass of CLASSES) { + for (const event of EVENTS) { + const expected = id => { + if (id === 'changes' || always.includes(id)) return 'success'; + if (changeClass !== 'code') return 'skipped'; + return queueOnly.includes(id) && event === 'pull_request' ? 'skipped' : 'success'; + }; + const where = `${changeClass} change on ${event}`; + const green = { EVENT_NAME: event, CHANGE_CLASS: changeClass, + ...Object.fromEntries([...variables].map(([id, name]) => [name, expected(id)])) }; + assert.equal(runGate(jobText, green), true, `${where}: the expected results pass`); + for (const [id, name] of variables) { + for (const result of ['success', 'failure', 'cancelled', 'skipped']) { + if (result === expected(id)) continue; + assert.equal(runGate(jobText, { ...green, [name]: result }), false, `${where}: ${id}=${result} must fail the gate`); + } + } + for (const unknown of ['', 'other', 'code ']) { + assert.equal(runGate(jobText, { ...green, CHANGE_CLASS: unknown }), false, `${where}: class "${unknown}" must fail the gate`); } } } @@ -113,20 +135,20 @@ test('viewerjs keeps its name and needs every frontend job', () => { const needs = needsOf(viewerjs); const others = [...allJobs.keys()].filter(id => id !== 'viewerjs'); assert.deepEqual([...needs].sort(), [...others].sort(), 'viewerjs needs every other job in the workflow'); - assert.deepEqual([...needs].sort(), ['browser-workflows', 'frontend-coverage', 'frontend-coverage-merge']); + assert.deepEqual([...needs].sort(), ['browser-workflows', 'changes', 'frontend-coverage', 'frontend-coverage-merge']); assert.match(viewerjs, /^ {4}if: always\(\)$/m, 'viewerjs runs (and fails) when a needed job failed or was skipped'); assert.deepEqual([...gateVariables(viewerjs).keys()].sort(), [...needs].sort(), 'every needed result reaches the check'); }); -test('viewerjs requires the browser shards everywhere but on a pull request', () => { - assertGateBehaviour(allJobs.get('viewerjs'), ['browser-workflows']); +test('viewerjs requires the browser shards everywhere but on a pull request, and nothing for a docs or inert change', () => { + assertGateBehaviour(allJobs.get('viewerjs'), { queueOnly: ['browser-workflows'], codeOnly: ['frontend-coverage', 'frontend-coverage-merge'] }); }); -test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event', () => { +test('Firefox/WebKit page workflows run only outside pull requests; coverage runs on every event; both for code changes only', () => { assert.match(allJobs.get('browser-workflows'), QUEUE_ONLY_IF); - for (const id of ['frontend-coverage', 'frontend-coverage-merge']) { - assert.doesNotMatch(allJobs.get(id), /^ {4}if:/m, `${id} runs on every event`); - } + assert.match(allJobs.get('frontend-coverage'), CODE_ONLY_IF); + // !cancelled() replaces the implicit success() check, so the merge names the shards' success itself. + assert.match(allJobs.get('frontend-coverage-merge'), jobIf(`!cancelled() && needs.frontend-coverage.result == 'success' && ${CODE_CLASS}`)); }); test('coverage runs as four shards that each upload their raw coverage', () => { @@ -144,7 +166,7 @@ test('coverage runs as four shards that each upload their raw coverage', () => { test('merge job downloads every shard and runs the merge-only report and check', () => { const merge = mergeJob(); assert.ok(merge, 'frontend-coverage-merge exists'); - assert.deepEqual(needsOf(merge), ['frontend-coverage']); + assert.deepEqual(needsOf(merge), ['changes', 'frontend-coverage']); assert.match(merge, /^ {4}name: frontend coverage \(merge\)$/m); const download = steps(merge).find(step => /uses: actions\/download-artifact@/.test(step)); assert.ok(download, 'merge downloads the shard artifacts'); @@ -329,16 +351,33 @@ test('the bandit pre-commit hook fails at the severity CI enforces and passes ev // Event split (#420): pull requests run a fast subset, the merge queue and main run everything. const testJobs = () => jobs(readWorkflow('test.yml')); -test('the Python matrix is Linux 3.12 on a pull request and Linux 3.12-3.14 on every other event', () => { +test('the Python matrix is Linux 3.12 on a pull request or a docs or inert change and Linux 3.12-3.14 otherwise', () => { const body = testJobs().get('test'); assert.deepEqual(matrixList(body, 'os'), ['ubuntu-latest'], 'Windows never gates a merge'); - const match = /^ {8}python-version: \$\{\{ github\.event_name == 'pull_request' && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body); - assert.ok(match, 'python-version is chosen by event'); - assert.deepEqual({ pr: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { pr: ['3.12'], other: ['3.12', '3.13', '3.14'] }); + const match = /^ {8}python-version: \$\{\{ \(github\.event_name == 'pull_request' \|\| needs\.changes\.outputs\.class == 'docs' \|\| needs\.changes\.outputs\.class == 'inert'\) && fromJSON\('(\[[^\]]*\])'\) \|\| fromJSON\('(\[[^\]]*\])'\) \}\}$/m.exec(body); + assert.ok(match, 'python-version is chosen by event and change class'); + assert.deepEqual({ small: JSON.parse(match[1]), other: JSON.parse(match[2]) }, { small: ['3.12'], other: ['3.12', '3.13', '3.14'] }); assert.match(body, /^ {6}fail-fast: false$/m); assert.match(body, /^ {4}name: py\$\{\{ matrix\.python-version \}\} on \$\{\{ matrix\.os \}\}$/m); }); +// #639: a skipped matrix job reports under its unexpanded name, so the required context +// "py3.12 on ubuntu-latest" would never report. The job therefore always starts, and an inert change +// skips its steps instead. +test('the Python matrix always starts and skips its steps for an inert change', () => { + const body = testJobs().get('test'); + assert.deepEqual(needsOf(body), ['changes']); + assert.match(body, jobIf('!cancelled()'), 'it also runs, in full, when the classifier failed'); + const jobSteps = steps(body); + const nothing = jobSteps.filter(step => /^ {8}if: needs\.changes\.outputs\.class == 'inert'$/m.test(step)); + assert.equal(nothing.length, 1, 'one step says nothing needs testing'); + assert.match(nothing[0], /^ {8}run: echo /m, 'and it only prints that'); + for (const step of jobSteps.filter(step => step !== nothing[0])) { + assert.match(step, /^ {8}if: needs\.changes\.outputs\.class != 'inert'$/m, `every real step is skipped for an inert change: ${step.trim().split('\n')[0]}`); + } + assert.equal(jobSteps.length, 5); +}); + test('Windows runs 3.12-3.14 on main, nightly and on demand, never on a PR or in the queue', () => { const text = readWorkflow('portability.yml'); const triggers = text.slice(text.indexOf('\non:'), text.indexOf('\nconcurrency:')); @@ -374,12 +413,14 @@ test('the portability limit is computed from three measured green main runs', () assert.equal(limit, expected, 'the job uses the written limit'); }); -test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event', () => { +test('real ComfyUI runs only outside pull requests; the other test.yml checks run on every event; all for code changes only', () => { const found = testJobs(); assert.match(found.get('comfyui'), QUEUE_ONLY_IF); - for (const id of ['test', 'coverage', 'lint', 'js-test']) { - assert.doesNotMatch(found.get(id), /^ {4}if:/m, `${id} runs on every event`); + for (const id of ['coverage', 'lint', 'js-test']) { + assert.match(found.get(id), CODE_ONLY_IF, `${id} runs on every event for a code change`); } + assert.match(found.get('perf-budget'), + jobIf(`!cancelled() && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && ${CODE_CLASS}`)); }); test('all tests needs every gating test.yml job and requires the full set outside pull requests', () => { @@ -391,7 +432,7 @@ test('all tests needs every gating test.yml job and requires the full set outsid const gating = [...found.keys()].filter(id => !['all-tests', 'perf-budget'].includes(id)); assert.deepEqual([...needsOf(gate)].sort(), gating.sort(), 'the gate needs every job but the non-gating perf budget'); assert.deepEqual([...gateVariables(gate).keys()].sort(), gating.sort(), 'every needed result reaches the gate'); - assertGateBehaviour(gate, ['comfyui']); + assertGateBehaviour(gate, { queueOnly: ['comfyui'], codeOnly: ['coverage', 'lint', 'js-test'], always: ['test'] }); }); test('the CI workflows run on pull_request, merge_group and push without path filters', () => { @@ -403,7 +444,39 @@ test('the CI workflows run on pull_request, merge_group and push without path fi } assert.doesNotMatch(text, /^ {4}paths(-ignore)?:/m, `${name} has no path filter that would leave a required check pending`); } - assert.doesNotMatch(jobs(readWorkflow('code-quality.yml')).get('security'), /^ {4}if:/m, 'bandit runs on every event'); + assert.match(jobs(readWorkflow('code-quality.yml')).get('security'), CODE_ONLY_IF, 'bandit runs on every event for a code change'); +}); + +// #639: the change is classified once per workflow, before anything else, from file names alone. +test('each gating workflow classifies the change first and every other job waits for it', () => { + for (const name of GATING_WORKFLOWS) { + const found = jobs(readWorkflow(name)); + assert.equal([...found.keys()][0], 'changes', `${name} starts with the classifier`); + const changes = found.get('changes'); + assert.match(changes, /^ {4}name: change class$/m); + assert.doesNotMatch(changes, /^ {4}(needs|if):/m, `${name}: the classifier waits for nothing and always runs`); + assert.match(changes, /^ {6}class: \$\{\{ steps\.classify\.outputs\.class \}\}$/m); + const [checkout, classify] = steps(changes); + assert.match(checkout, /uses: actions\/checkout@v\d+/); + assert.match(checkout, /^ {10}fetch-depth: 0$/m, 'the base commit must be in the clone'); + assert.match(checkout, /^ {10}filter: blob:none$/m, 'file names need no file contents'); + assert.match(checkout, /^ {10}persist-credentials: false$/m); + assert.match(classify, /^ {8}id: classify$/m); + assert.match(classify, /^ {10}EVENT_NAME: \$\{\{ github\.event_name \}\}$/m); + assert.match(classify, /^ {10}BASE_SHA: \$\{\{ github\.event\.pull_request\.base\.sha \|\| github\.event\.merge_group\.base_sha \|\| github\.event\.before \}\}$/m); + assert.match(classify, /^ {10}HEAD_SHA: \$\{\{ github\.event\.pull_request\.head\.sha \|\| github\.event\.merge_group\.head_sha \|\| github\.sha \}\}$/m); + assert.match(classify, /^ {8}run: python3 tools\/ci\/change_class\.py \| tee -a "\$GITHUB_OUTPUT"$/m); + for (const [id, body] of found) { + if (id !== 'changes') assert.ok(needsOf(body).includes('changes'), `${name} job ${id} waits for the classifier`); + } + } +}); + +test('the pre-push hook runs the suite through the classifier', () => { + const hook = /- id: tests\n([\s\S]*?)(?=\n {6}(?:- id:|#)|\n*$)/.exec(readRepoFile('.pre-commit-config.yaml'))?.[1]; + assert.ok(hook, 'the tests hook exists'); + assert.match(hook, /^ {8}entry: python tools\/ci\/change_class\.py --unless-inert python -m tests\.run_suite -q$/m); + assert.match(hook, /^ {8}stages: \[pre-push\]$/m); }); test('every required check reports on a pull request and the gates carry the full matrix', () => { diff --git a/tools/ci/change_class.py b/tools/ci/change_class.py new file mode 100644 index 00000000..ae8e2abc --- /dev/null +++ b/tools/ci/change_class.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Sort a change by the files it touches, so CI tests only what can break (#639). + +Three classes, decided from allowlists: + +- ``inert``: every file is one nothing reads at run or test time (the funding + file, the security policy, the old README's screenshots, issue templates). + No test job runs. +- ``docs``: every file is inert or a document a Python test reads (the + READMEs and their images, checked by ``tests/test_brand_assets.py`` and + ``tests/test_package_contents.py``). Only the Python 3.12 suite runs. +- ``code``: anything else. A file on no list is code, and so is every case of + doubt: no files, an unknown event, a range git cannot read. + +``docs/`` is code (the browser suite compares production against +``docs/concepts/workspace/``) and so is ``TESTING.md`` (the tooling tests read +its tables). To add a file to a list, first check that no test and no shipped +code opens it. + +Usage: + +``change_class.py`` + Prints ``class=`` for the workflow's ``$GITHUB_OUTPUT``, + from ``EVENT_NAME``, ``BASE_SHA`` and ``HEAD_SHA``. A pull request is + compared with its merge base, so commits that landed on main meanwhile + do not count; a merge group and a push are compared end to end. + +``change_class.py --unless-inert `` + The pre-push hook: runs the command unless pre-commit's pushed range + (``PRE_COMMIT_FROM_REF``..``PRE_COMMIT_TO_REF``) is inert, and exits + with the command's code. +""" + +import os +import subprocess +import sys +from typing import Iterable, Optional + +INERT_FILES = frozenset({".github/FUNDING.yml", "SECURITY.md"}) +INERT_FOLDERS = ("images/", ".github/ISSUE_TEMPLATE/") +DOCS_FILES = frozenset({"README.md", "README-legacy.md"}) +DOCS_FOLDERS = ("assets/readme/", "assets/brand/") + +RANGE_EVENTS = frozenset({"pull_request", "merge_group", "push"}) +ENVIRONMENT = frozenset( + { + "EVENT_NAME", + "BASE_SHA", + "HEAD_SHA", + "PRE_COMMIT_FROM_REF", + "PRE_COMMIT_TO_REF", + } +) + + +def classify(paths: Iterable[str]) -> str: + """``inert``, ``docs`` or ``code`` for the repository paths of one change.""" + found = "code" + for path in paths: + if path in INERT_FILES or path.startswith(INERT_FOLDERS): + if found == "code": + found = "inert" + elif path in DOCS_FILES or path.startswith(DOCS_FOLDERS): + found = "docs" + else: + return "code" + return found + + +def changed_paths(base: str, head: str, three_dot: bool) -> Optional[list[str]]: + """Paths that differ between two commits, or None when git cannot say. + + Renames are listed under both names, so a file moved onto a listed name + still counts as the code file it was. + """ + if not base or not head or not base.strip("0") or not head.strip("0"): + return None + span = f"{base}...{head}" if three_dot else f"{base}..{head}" + try: + result = subprocess.run( + ["git", "diff", "--name-only", "--no-renames", "-z", span, "--"], + capture_output=True, + text=True, + check=False, + ) + except OSError: + return None + if result.returncode != 0: + return None + return [path for path in result.stdout.split("\0") if path] + + +def class_of_range(base: str, head: str, three_dot: bool = False) -> str: + paths = changed_paths(base, head, three_dot) + if paths is None: + return "code" + for path in paths: + print(f"changed: {path}", file=sys.stderr) + return classify(paths) + + +def main(argv: list[str]) -> int: + if argv[:1] == ["--unless-inert"]: + found = class_of_range( + os.environ.get("PRE_COMMIT_FROM_REF", ""), + os.environ.get("PRE_COMMIT_TO_REF", ""), + ) + if found == "inert": + print("Skipped: this push only changes inert files (tools/ci).") + return 0 + return subprocess.run(argv[1:], check=False).returncode + event = os.environ.get("EVENT_NAME", "") + found = "code" + if event in RANGE_EVENTS: + found = class_of_range( + os.environ.get("BASE_SHA", ""), + os.environ.get("HEAD_SHA", ""), + three_dot=event == "pull_request", + ) + print(f"class={found}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))