diff --git a/.github/workflows/README.md b/.github/workflows/README.md index e8fa1674dd5..e9412dd22e9 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -6,17 +6,19 @@ a check belongs to exactly one tier on purpose. | Tier | Event | Job | |---|---|---| | PR feedback | `pull_request` | Fast, scoped signal for the author. May run slim matrices and path-scoped subsets. | -| **Production gate** | `merge_group` (merge queue) | The authority on what reaches `main`. Runs deterministic checks in the **same shape as push** on the merged state. | -| Post-merge confirm | `push` to `main` | Confirms the queue's verdict, warms shared caches, feeds Codecov/canaries. Should never be the first place a deterministic failure appears. | +| **Production gate** | `merge_group` (merge queue) | The authority on what reaches `main`. Runs affected deterministic checks for the combined candidate and widens to exhaustive deterministic checks for global, topology, or unclassified changes. | +| Post-merge confirm | `push` to `main` | Runs exhaustive coverage, warms shared caches, and feeds Codecov/canaries. A main-only deterministic failure means the affected-area classifier missed an impact and must be widened. | | Deep / scheduled | `schedule` (nightly) | Exhaustive suites too slow for the queue: legacy v1 matrix, full browser E2E, stress scans. | ## The invariant -**No deterministic failure may be main-only.** If a check runs deterministically -on `push` to main, the merge queue must run it in the same shape first -(`merge_group` does not support `paths:` filters — use a `changes` scope job -instead). External/live checks (canaries, deploys, releases, benchmark -thresholds) are exempt: they stay out of the queue by design. +**No attributable deterministic failure may be main-only.** The merge queue +classifies the combined `base_sha...head_sha` diff, runs the union of affected +packages and lanes, and widens to the exhaustive push shape whenever a changed +path is global, changes workspace topology, or cannot be classified. This +fail-loud fallback makes new repository surfaces safe by default. External/live +checks (canaries, deploys, releases, benchmark thresholds) are exempt: they +stay out of the queue by design. The canonical local composition of the deterministic Reborn gates is `scripts/ci/run-hermetic-deterministic-suite.sh all`. CI invokes the same @@ -31,9 +33,10 @@ changes. Root `Cargo.toml` and `Cargo.lock` changes are broader workspace risk: they run the lane in the merge queue, before landing, without adding the full WASM build to ordinary PR feedback. Push and deep-CI runs remain exhaustive. -`reborn-tests.yml` follows the same PR-versus-queue contract. Pull requests use -`reborn_pr_test_plan.py` to run affected crate buckets and exact changed root -and integration suites without LLVM instrumentation. Recorded QA +`reborn-tests.yml` uses one affected-area planner for pull requests and merge +groups. Pull requests classify their own three-dot diff; merge groups classify +the combined candidate diff so interacting PRs contribute one union of +affected crate buckets and exact changed root and integration suites. Recorded QA replay remains a baseline on every pull request because it detects ordering and cross-surface regressions that cannot be inferred from changed paths. The full transitive reverse workspace dependency closure is included in PR crate @@ -43,30 +46,29 @@ package's production behavior. A changed top-level Cargo test, example, or bench target runs directly; nested support changes retain all owning-package targets. Foundational-crate changes that span more than three canonical buckets coalesce every changed and dependent package into at -most three PR jobs instead of omitting consumer tests. The merge queue and -pushes to `main` still run every crate bucket, root partition, group suite, -integration lane, recorded replay, and coverage gate. Shared root or -integration support changes run one -representative PR partition or lane, with the exhaustive fan-out required in -merge queue. CI workflow, CI script, coverage-policy, toolchain, and workspace -topology changes use their owning static/compile gates on the PR and receive -the exhaustive Reborn matrix in merge queue. Unknown paths and empty diffs -fail quickly at planning instead of silently launching or skipping an -unbounded matrix. A planner execution or schema failure also fails the -required check loudly. +most three PR jobs instead of omitting consumer tests. Merge groups retain the +planner's reverse-dependency closure without the PR fan-out caps. Shared root +or integration support changes select their owning lanes. CI workflow, CI +script, coverage-policy, toolchain, workspace topology, and other global inputs +widen the merge group to every crate bucket, root partition, group suite, +integration lane, and recorded replay. Unclassified merge-group paths also +widen to exhaustive deterministic checks; unclassified pull-request paths and +empty diffs fail planning loudly. Push, schedule, and manual runs remain +exhaustive. A planner execution or schema failure fails the required check. `Cargo.lock` is scoped only when a structured base/head comparison proves that the lockfile changed solely in dependency lists for workspace manifests changed by the same PR. Package additions/removals, versions, checksums, unrelated workspace edges, and unreadable base state receive their full dependency -breadth in merge queue; changed workspace manifests still select their -production dependency closure on the PR. The stress tool +breadth; workspace manifests and lockfiles are exhaustive merge-group inputs. +Changed workspace manifests still select their production dependency closure +on the PR. The stress tool is owned by `ironclaw-stress.yml`, and changed-line coverage exemptions are schema-checked in Code Style instead of launching unrelated integration lanes. -The queue therefore preserves exhaustive deterministic evidence while -ordinary PRs avoid consuming 20-plus runners for unrelated lanes. Pull-request -parallelism is capped at three crate buckets, one root partition, and one -integration lane; merge queue and main retain full matrix parallelism so this -feedback optimization does not serialize the production gate. +The queue therefore preserves evidence for every classified impact without +launching unrelated lanes. Diff-based crate work is packed into at most three +buckets without dropping packages. Pull requests additionally cap root and +integration work at one lane; merge groups run every selected root and +integration lane in parallel, while main retains exhaustive fan-out. Full-coverage crate buckets run one multi-package `cargo llvm-cov` invocation per bucket, preserving every package test and the bucket LCOV artifact while sharing dependency compilation across packages in the same job. @@ -77,9 +79,11 @@ code events. Pull-request Clippy covers production libraries and binaries for directly changed workspace packages with all features. Test-only and CI-only PRs do not compile an unchanged workspace solely for linting. Root `Cargo.toml` and `Cargo.lock` changes lint every workspace package because -their dependency and feature impact is workspace-wide. Merge queue and main -lint the full workspace, add test and example targets, and run the -default-feature matrix. Code Style's CLI Rust smoke and Reborn E2E's +their dependency and feature impact is workspace-wide. Merge groups lint +affected packages and their test/example targets in both all-features and +default-feature configurations. Global, topology, and unclassified inputs +widen that scope to the full workspace. Main always runs the full workspace. +Code Style's CLI Rust smoke and Reborn E2E's four Rust groups run on merge queue and main, where they validate the exhaustive merged state, but do not repeat those contracts on PR runners. The release-binary smoke harness self-test remains in Code Style's fast deterministic job on every @@ -96,9 +100,9 @@ without restoring the two runner allocations removed by pairing. The fast Responses API and black-box contracts share the browser worker in separate hermetic pytest processes, capping the E2E fan-out at four workers. -History: the slim-vs-full clippy matrix violated this — the queue linted only -`--all-features` while push linted a broader matrix, so feature-gated dead code -could pass the queue and turn main red post-merge. +History: the slim-vs-full clippy matrix showed why feature configurations and +affected packages are separate dimensions. The queue keeps both required +feature configurations even when its package set is scoped. ## Required checks and where they're enforced diff --git a/.github/workflows/code_style.yml b/.github/workflows/code_style.yml index 6c5540ebcfa..c7eb9da5448 100644 --- a/.github/workflows/code_style.yml +++ b/.github/workflows/code_style.yml @@ -45,6 +45,7 @@ jobs: has_docs: ${{ steps.non_pr.outputs.has_docs || steps.diff.outputs.has_docs }} has_reborn_cli: ${{ steps.non_pr.outputs.has_reborn_cli || steps.diff.outputs.has_reborn_cli }} has_clippy: ${{ steps.non_pr.outputs.has_clippy || steps.diff.outputs.has_clippy }} + clippy_scope: ${{ steps.non_pr.outputs.clippy_scope || steps.diff.outputs.clippy_scope }} clippy_packages: ${{ steps.non_pr.outputs.clippy_packages || steps.diff.outputs.clippy_packages }} clippy_matrix: ${{ steps.non_pr.outputs.clippy_matrix || steps.diff.outputs.clippy_matrix }} steps: @@ -56,37 +57,52 @@ jobs: echo "has_docs=true" >> "$GITHUB_OUTPUT" echo "has_reborn_cli=true" >> "$GITHUB_OUTPUT" echo "has_clippy=true" >> "$GITHUB_OUTPUT" + echo "clippy_scope=full" >> "$GITHUB_OUTPUT" echo 'clippy_packages=[]' >> "$GITHUB_OUTPUT" echo 'clippy_matrix=[{"name":"all-features","flags":"--all-features"},{"name":"default","flags":""}]' >> "$GITHUB_OUTPUT" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 if: github.event_name == 'pull_request' || github.event_name == 'merge_group' with: - fetch-depth: 0 - # The scope calculation needs merge-base ancestry for its three-dot - # diff, but no historical file contents. + # PR scope keeps full ancestry for its three-dot diff. A merge-group + # checkout is the candidate commit only; its base is fetched below. + fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }} filter: blob:none persist-credentials: false + - name: Fetch merge-group base for scope diff + if: github.event_name == 'merge_group' + env: + BASE_SHA: ${{ github.event.merge_group.base_sha }} + run: git fetch --no-tags --filter=blob:none --depth=1 origin "$BASE_SHA" - id: diff if: github.event_name == 'pull_request' || github.event_name == 'merge_group' env: BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.merge_group.base_sha }} HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} run: | - CHANGED_FILES="$(git diff --name-only "$BASE_SHA"..."$HEAD_SHA")" + if [[ "${{ github.event_name }}" == "merge_group" ]]; then + CHANGED_FILES="$(git diff --name-only "$BASE_SHA" "$HEAD_SHA")" + else + CHANGED_FILES="$(git diff --name-only "$BASE_SHA"..."$HEAD_SHA")" + fi printf '%s\n' "$CHANGED_FILES" > "${RUNNER_TEMP}/changed-files.txt" - clippy_packages="$( + clippy_plan="$( python3 scripts/ci/changed_workspace_packages.py \ + --event "${{ github.event_name }}" \ --changed-files "${RUNNER_TEMP}/changed-files.txt" )" + clippy_scope="$(jq -r '.mode' <<< "${clippy_plan}")" + clippy_packages="$(jq -c '.packages' <<< "${clippy_plan}")" + echo "clippy_scope=${clippy_scope}" >> "$GITHUB_OUTPUT" echo "clippy_packages=${clippy_packages}" >> "$GITHUB_OUTPUT" - if jq -e 'length > 0' <<< "${clippy_packages}" > /dev/null; then + if [[ "${clippy_scope}" != "none" ]]; then echo "has_clippy=true" >> "$GITHUB_OUTPUT" else echo "has_clippy=false" >> "$GITHUB_OUTPUT" fi - if printf '%s\n' "$CHANGED_FILES" | grep -Eq '^(crates/|tests/|migrations/|Cargo\.toml$|Cargo\.lock$|deny\.toml$|Dockerfile|\.gitignore$|scripts/ci/|\.githooks/|docker/reborn/(entrypoint|start-sshd)\.sh$|scripts/reborn_webui_v2_live_qa/|scripts/live-canary/|\.github/workflows/(live-canary|reborn-e2e)\.yml$|scripts/check_no_panics\.py$|scripts/no_panics_reborn_baseline\.txt$|scripts/(check|test-check)-type-duplicates\.py$|\.github/scripts/(pr-labeler|test-pr-labeler)\.sh$|\.github/workflows/(code_style|main-ci-slack-alerts)\.yml$|\.github/workflows/ironclaw-release\.yml$|rust-toolchain\.toml$|\.github/actions/setup-rust/)'; then + if [[ "${clippy_scope}" == "full" ]] || \ + printf '%s\n' "$CHANGED_FILES" | grep -Eq '^(crates/|tests/|migrations/|Cargo\.toml$|Cargo\.lock$|deny\.toml$|Dockerfile|\.gitignore$|scripts/ci/|\.githooks/|docker/reborn/(entrypoint|start-sshd)\.sh$|scripts/reborn_webui_v2_live_qa/|scripts/live-canary/|\.github/workflows/(live-canary|reborn-e2e)\.yml$|scripts/check_no_panics\.py$|scripts/no_panics_reborn_baseline\.txt$|scripts/(check|test-check)-type-duplicates\.py$|\.github/scripts/(pr-labeler|test-pr-labeler)\.sh$|\.github/workflows/(code_style|main-ci-slack-alerts)\.yml$|\.github/workflows/ironclaw-release\.yml$|rust-toolchain\.toml$|\.github/actions/setup-rust/)'; then echo "has_code=true" >> "$GITHUB_OUTPUT" else echo "has_code=false" >> "$GITHUB_OUTPUT" @@ -154,7 +170,8 @@ jobs: needs: changes # `has_guidance` OR-s in the guidance surfaces (.claude/, root # AGENTS.md/CLAUDE.md, docs/) so check-guidance.py runs for the files it - # governs; every other lane keys on `has_code` alone. + # governs. Clippy additionally follows `clippy_scope=full` for merge-group + # inputs that are outside the narrow `has_code` path filter. if: needs.changes.outputs.has_code == 'true' || needs.changes.outputs.has_guidance == 'true' runs-on: ubuntu-latest timeout-minutes: 30 @@ -369,8 +386,9 @@ jobs: name: Clippy (${{ matrix.name }}) needs: changes if: >- - needs.changes.outputs.has_code == 'true' && - (github.event_name != 'pull_request' || needs.changes.outputs.has_clippy == 'true') + needs.changes.outputs.has_clippy == 'true' && + (needs.changes.outputs.has_code == 'true' || + needs.changes.outputs.clippy_scope == 'full') runs-on: ubuntu-latest timeout-minutes: 45 strategy: @@ -428,7 +446,7 @@ jobs: cache-ssh-known-hosts: ${{ secrets.SCCACHE_CACHE_SSH_KNOWN_HOSTS }} redis-password: ${{ secrets.SCCACHE_REDIS_PASSWORD }} - name: Check production-target lints - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request' && needs.changes.outputs.clippy_scope == 'selected' env: CLIPPY_PACKAGES: ${{ needs.changes.outputs.clippy_packages }} run: | @@ -447,9 +465,30 @@ jobs: # package shape. scripts/ci/ws12_workflow_contracts.py pins this. cargo clippy "${package_args[@]}" \ ${{ matrix.flags }} -- -D warnings + - name: Check affected all-target lints + if: github.event_name == 'merge_group' && needs.changes.outputs.clippy_scope == 'selected' + env: + CLIPPY_PACKAGES: ${{ needs.changes.outputs.clippy_packages }} + run: | + package_args=() + while IFS= read -r package; do + package_args+=(-p "${package}") + done < <(jq -r '.[]' <<< "${CLIPPY_PACKAGES}") + cargo clippy "${package_args[@]}" --all-targets \ + ${{ matrix.flags }} -- -D warnings + - name: Check affected production-target lints (no dev-dependency features) + if: github.event_name == 'merge_group' && needs.changes.outputs.clippy_scope == 'selected' && matrix.name == 'default' + env: + CLIPPY_PACKAGES: ${{ needs.changes.outputs.clippy_packages }} + run: | + package_args=() + while IFS= read -r package; do + package_args+=(-p "${package}") + done < <(jq -r '.[]' <<< "${CLIPPY_PACKAGES}") + cargo clippy "${package_args[@]}" -- -D warnings - name: Check all-target lints - if: github.event_name != 'pull_request' - run: cargo clippy --all --tests --examples ${{ matrix.flags }} -- -D warnings + if: needs.changes.outputs.clippy_scope == 'full' + run: cargo clippy --all --all-targets ${{ matrix.flags }} -- -D warnings # #7119. The PR lane above lints only the *changed* packages, so a crate # that is merely a dependency of that set compiles with whatever features # the set happens to enable. `--lib --bins` builds no dev-dependencies, and @@ -466,7 +505,7 @@ jobs: # `test-support` on every selected package and masks the exact class this # step exists to catch. - name: Check production-target lints (workspace, no dev-dependency features) - if: github.event_name != 'pull_request' && matrix.name == 'default' + if: needs.changes.outputs.clippy_scope == 'full' && matrix.name == 'default' run: cargo clippy --all --lib --bins -- -D warnings clippy-windows: @@ -630,7 +669,8 @@ jobs: exit 1 fi - if [[ "${{ needs.changes.outputs.has_code }}" == "false" ]]; then + if [[ "${{ needs.changes.outputs.has_code }}" == "false" && + "${{ needs.changes.outputs.clippy_scope }}" != "full" ]]; then if [[ "${{ needs.changes.outputs.has_reborn_cli }}" == "true" && "${{ needs.reborn-cli-smoke.result }}" != "success" ]]; then echo "Reborn CLI smoke failed: ${{ needs.reborn-cli-smoke.result }}" exit 1 @@ -657,8 +697,7 @@ jobs: done clippy_may_skip=false - if [[ "${{ github.event_name }}" == "pull_request" && \ - "${{ needs.changes.outputs.has_clippy }}" != "true" ]]; then + if [[ "${{ needs.changes.outputs.has_clippy }}" != "true" ]]; then clippy_may_skip=true fi if ! job_result_ok \ @@ -678,7 +717,7 @@ jobs: fi done - name: Assert the full clippy matrix ran (merge queue + push) - if: needs.changes.outputs.has_code == 'true' && github.event_name != 'pull_request' + if: needs.changes.outputs.clippy_scope == 'full' && github.event_name != 'pull_request' env: MATRIX_JSON: ${{ needs.changes.outputs.clippy_matrix }} run: | diff --git a/.github/workflows/reborn-tests.yml b/.github/workflows/reborn-tests.yml index 25f9568977a..8da69b51438 100644 --- a/.github/workflows/reborn-tests.yml +++ b/.github/workflows/reborn-tests.yml @@ -98,14 +98,19 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 with: ref: ${{ inputs.ref || github.sha }} - # PR planning uses a three-dot diff and reads the base Cargo.lock, - # so it needs the commit graph. Other events always build the full - # plan and need only the execution commit. + # PR planning keeps full ancestry for its three-dot diff. A + # merge-group checkout is the candidate commit only; its base is + # fetched below. fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }} - # Keep PR ancestry while omitting historical blobs. Checkout still - # materializes the complete execution tree used by the planner. + # Checkout still materializes the complete execution tree used by the + # planner while omitting historical blobs. filter: blob:none persist-credentials: false + - name: Fetch merge-group base for scope diff + if: github.event_name == 'merge_group' + env: + BASE_SHA: ${{ github.event.merge_group.base_sha }} + run: git fetch --no-tags --filter=blob:none --depth=1 origin "$BASE_SHA" - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: "3.12" @@ -113,16 +118,23 @@ jobs: - id: plan name: Build affected-area test plan env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.merge_group.base_sha }} + HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} run: | set -euo pipefail changed_args=() base_args=() - if [[ "${{ github.event_name }}" == "pull_request" ]]; then - git diff --name-only "$BASE_SHA"..."$HEAD_SHA" \ - > "${RUNNER_TEMP}/reborn-changed-files.txt" + if [[ "${{ github.event_name }}" == "pull_request" || "${{ github.event_name }}" == "merge_group" ]]; then + if [[ "${{ github.event_name }}" == "merge_group" ]]; then + git diff --name-only "$BASE_SHA" "$HEAD_SHA" \ + > "${RUNNER_TEMP}/reborn-changed-files.txt" + else + git diff --name-only "$BASE_SHA"..."$HEAD_SHA" \ + > "${RUNNER_TEMP}/reborn-changed-files.txt" + fi changed_args=(--changed-files "${RUNNER_TEMP}/reborn-changed-files.txt") + fi + if [[ "${{ github.event_name }}" == "pull_request" ]]; then base_args=(--base-sha "$BASE_SHA") fi diff --git a/scripts/ci/changed_workspace_packages.py b/scripts/ci/changed_workspace_packages.py index 1e500832162..0c70f8cbed4 100644 --- a/scripts/ci/changed_workspace_packages.py +++ b/scripts/ci/changed_workspace_packages.py @@ -11,12 +11,26 @@ ROOT = Path(__file__).resolve().parents[2] +MERGE_GROUP_FULL_PATHS = { + "Cargo.toml", + "Cargo.lock", + "rust-toolchain", + "rust-toolchain.toml", + ".cargo/config", + ".cargo/config.toml", + "clippy.toml", +} +MERGE_GROUP_FULL_PREFIXES = ( + ".github/actions/", + ".github/workflows/", + "migrations/", + "scripts/ci/", +) -def changed_production_packages( - changed_paths: list[str], metadata: dict[str, Any] -) -> list[str]: + +def _workspace_packages(metadata: dict[str, Any]) -> list[tuple[Path, str]]: members = set(metadata["workspace_members"]) - packages = sorted( + return sorted( ( Path(package["manifest_path"]).resolve().parent.relative_to(ROOT), package["name"], @@ -24,6 +38,52 @@ def changed_production_packages( for package in metadata["packages"] if package["id"] in members ) + + +def _reverse_dependency_closure( + metadata: dict[str, Any], roots: set[str] +) -> set[str]: + workspace_members = set(metadata["workspace_members"]) + workspace_packages = { + package["name"]: package + for package in metadata["packages"] + if package["id"] in workspace_members + } + workspace_package_by_directory = { + Path(package["manifest_path"]).resolve().parent: package["name"] + for package in workspace_packages.values() + } + dependents: dict[str, set[str]] = { + package_name: set() for package_name in workspace_packages + } + for package_name, package in workspace_packages.items(): + for dependency in package.get("dependencies", []): + dependency_name = None + dependency_path = dependency.get("path") + if dependency_path: + dependency_name = workspace_package_by_directory.get( + Path(dependency_path).resolve() + ) + if dependency_name is None: + dependency_name = dependency.get("name") + if dependency_name in dependents: + dependents[dependency_name].add(package_name) + + closure = set(roots) + pending = list(roots) + while pending: + package_name = pending.pop() + for dependent in dependents.get(package_name, set()): + if dependent not in closure: + closure.add(dependent) + pending.append(dependent) + return closure + + +def changed_production_packages( + changed_paths: list[str], metadata: dict[str, Any] +) -> list[str]: + packages = _workspace_packages(metadata) selected: set[str] = set() normalized_paths = { path.strip().replace("\\", "/") for path in changed_paths if path.strip() @@ -51,9 +111,93 @@ def changed_production_packages( return sorted(selected) +def classify_clippy_scope( + changed_paths: list[str], metadata: dict[str, Any], *, event: str +) -> dict[str, Any]: + """Classify the clippy work required by a pull request or merge group.""" + if event not in {"pull_request", "merge_group"}: + raise ValueError(f"unsupported diff event: {event}") + + normalized_paths = { + path.strip().replace("\\", "/") for path in changed_paths if path.strip() + } + if event == "merge_group" and not normalized_paths: + raise ValueError("empty merge-group diff cannot be classified") + if event == "pull_request": + packages = changed_production_packages(list(normalized_paths), metadata) + return {"mode": "selected" if packages else "none", "packages": packages} + + packages = _workspace_packages(metadata) + workspace_manifests = { + "Cargo.toml" + if str(directory) == "." + else f"{directory.as_posix()}/Cargo.toml" + for directory, _package in packages + } + if any( + path in MERGE_GROUP_FULL_PATHS + or path in workspace_manifests + or path.startswith(MERGE_GROUP_FULL_PREFIXES) + for path in normalized_paths + ): + return {"mode": "full", "packages": []} + + selected: set[str] = set() + ignored_prefixes = ("docs/", "openwiki/", ".claude/", ".github/ISSUE_TEMPLATE/") + ignored_paths = { + ".env.example", + ".github/pull_request_template.md", + "AGENTS.md", + "CLAUDE.md", + "README.md", + } + production_packages: set[str] = set() + for path in normalized_paths: + matched_workspace_package = False + for directory, package in sorted( + packages, key=lambda item: len(item[0].parts), reverse=True + ): + prefix = "" if str(directory) == "." else f"{directory.as_posix()}/" + if prefix and not path.startswith(prefix): + continue + relative = path.removeprefix(prefix) + production_input = ( + relative == "Cargo.toml" + or relative == "build.rs" + or relative.startswith("src/") + ) + package_test_surface = relative.startswith( + ("tests/", "benches/", "examples/") + ) + if production_input or package_test_surface: + selected.add(package) + matched_workspace_package = True + if production_input: + production_packages.add(package) + break + if path.startswith("crates/") and not matched_workspace_package: + return {"mode": "full", "packages": []} + if ( + not matched_workspace_package + and path not in ignored_paths + and not path.startswith(ignored_prefixes) + ): + return {"mode": "full", "packages": []} + + selected.update(_reverse_dependency_closure(metadata, production_packages)) + package_names = sorted(selected) + return { + "mode": "selected" if package_names else "none", + "packages": package_names, + } + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--changed-files", type=Path, required=True) + parser.add_argument( + "--event", choices=("pull_request", "merge_group"), required=True + ) args = parser.parse_args() metadata = json.loads( subprocess.run( @@ -65,7 +209,7 @@ def main() -> int: ).stdout ) changed_paths = args.changed_files.read_text(encoding="utf-8").splitlines() - print(json.dumps(changed_production_packages(changed_paths, metadata))) + print(json.dumps(classify_clippy_scope(changed_paths, metadata, event=args.event))) return 0 diff --git a/scripts/ci/reborn_pr_test_plan.py b/scripts/ci/reborn_pr_test_plan.py index aa282bfb241..8a728f112c4 100644 --- a/scripts/ci/reborn_pr_test_plan.py +++ b/scripts/ci/reborn_pr_test_plan.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 -"""Select focused Reborn test lanes for pull requests. +"""Select focused Reborn test lanes for pull requests and merge groups. -Pull requests run direct evidence for changed packages and test surfaces. -Merge-queue, main, and manual runs remain exhaustive. +Diff events run direct evidence for changed packages and test surfaces. +Global or unattributable merge-group changes widen to exhaustive coverage; +main and manual runs remain exhaustive. """ from __future__ import annotations @@ -70,7 +71,10 @@ def _sandbox_docker_prefixes() -> tuple[str, ...]: MAX_PR_CRATE_BUCKETS = 3 -FULL_EVENTS = {"merge_group", "push", "workflow_call", "workflow_dispatch", "schedule"} +DIFF_EVENTS = {"pull_request", "merge_group"} +FULL_EVENTS = {"push", "workflow_call", "workflow_dispatch", "schedule"} +ALL_ROOT_PARTITIONS = (0, 1, 2, 3) +ALL_INTEGRATION_LANES = (0, 1, 2, 3, "groups") # Doc-fact contract tests (#7378) read `docs/` pages from inside owning # crates, so a published-page edit can fail a cargo test. Route those edits # to exactly the doc-fact test binaries (no reverse-dependency widening — @@ -850,8 +854,8 @@ def _full_plan( "changed_packages": [], "affected_packages": canonical_packages, "crate_buckets": _bucket_packages(canonical_packages), - "root_partitions": [0, 1, 2, 3], - "integration_lanes": [0, 1, 2, 3, "groups"], + "root_partitions": list(ALL_ROOT_PARTITIONS), + "integration_lanes": list(ALL_INTEGRATION_LANES), "run_group_tests": True, "run_qa_replay": True, "run_sandbox_docker": True, @@ -859,6 +863,36 @@ def _full_plan( } +def _merge_group_global_risk(paths: set[str]) -> str | None: + """Return the first path whose queue impact cannot be narrowed safely.""" + for path in sorted(paths): + if ( + path in {"Cargo.lock", ".config/nextest.toml"} + or path in PR_STATIC_CONTROL_PATHS + or path in PR_STATIC_CONTROL_FRAGMENTS + or path.startswith(PR_STATIC_CONTROL_PREFIXES) + or path.startswith(SHARED_REBORN_ACTION_PREFIXES) + ): + return path + return None + + +def _unclassified_path_plan( + *, + event: str, + reason: str, + canonical_packages: list[str], +) -> dict[str, Any]: + """Fail PR feedback loudly; widen an otherwise valid queue diff.""" + if event == "merge_group": + return _full_plan( + f"merge-group scope could not classify {reason}; running the " + "exhaustive plan", + canonical_packages, + ) + raise ValueError(reason) + + def build_plan( *, event: str, @@ -867,20 +901,45 @@ def build_plan( canonical_packages: list[str], lockfile_manifest_owned: bool = False, ) -> dict[str, Any]: - """Build a deterministic test plan, rejecting unknown PR inputs.""" + """Build a deterministic test plan, rejecting or widening unknown inputs.""" if event in FULL_EVENTS: return _full_plan(f"{event} requires exhaustive coverage", canonical_packages) - if event != "pull_request": + if event not in DIFF_EVENTS: return _full_plan(f"unknown event {event!r}", canonical_packages) paths = {path.strip().replace("\\", "/") for path in changed_paths if path.strip()} if not paths: raise ValueError( - "empty pull-request diff cannot be classified; refusing to launch " - "an unbounded PR matrix" + f"empty {event.replace('_', '-')} diff cannot be classified; " + "refusing to launch " + "an unbounded test matrix" ) + if event == "merge_group": + global_risk = _merge_group_global_risk(paths) + if global_risk is not None: + return _full_plan( + f"merge-group global or topology input changed: {global_risk}; " + "running the exhaustive plan", + canonical_packages, + ) + package_directories, reverse = _workspace_packages(metadata) + if event == "merge_group": + changed_manifest = next( + ( + f"{directory}/Cargo.toml" + for directory in sorted(package_directories) + if f"{directory}/Cargo.toml" in paths + ), + None, + ) + if changed_manifest is not None: + return _full_plan( + "merge-group workspace topology input changed: " + f"{changed_manifest}; running the exhaustive plan", + canonical_packages, + ) production_packages: set[str] = set() direct_test_packages: set[str] = set() exact_test_targets: dict[str, set[tuple[str, str]]] = defaultdict(set) @@ -1042,22 +1101,36 @@ def build_plan( path.startswith("tests/support/reborn_parity_qa/") or path == "tests/support_unit_tests.rs" ): - root_partitions.add(0) - reasons.append( - "shared root-test support changed; PR runs a representative partition" - ) + if event == "merge_group": + root_partitions.update(ALL_ROOT_PARTITIONS) + reasons.append( + "shared root-test support changed; merge group runs every root partition" + ) + else: + root_partitions.add(0) + reasons.append( + "shared root-test support changed; PR runs a representative partition" + ) continue if path.startswith("tests/support/") and path not in INTEGRATION_SUPPORT_OWNERS: # Direct shared root-test support (tests/support/mod.rs and the # modules it declares). The integration group targets also compile # this tree via `#[path = "../../support/mod.rs"]`, so schedule a # representative lane of each tier. - root_partitions.add(0) - integration_lanes.add(0) - reasons.append( - "shared root-test support changed; PR runs a representative " - "partition and integration lane" - ) + if event == "merge_group": + root_partitions.update(ALL_ROOT_PARTITIONS) + integration_lanes.update(ALL_INTEGRATION_LANES) + reasons.append( + "shared root-test support changed; merge group runs every " + "root and integration consumer lane" + ) + else: + root_partitions.add(0) + integration_lanes.add(0) + reasons.append( + "shared root-test support changed; PR runs a representative " + "partition and integration lane" + ) continue if path in integration_inventory: integration_lanes.add(integration_inventory[path]) @@ -1080,6 +1153,23 @@ def build_plan( integration_lanes.add(integration_inventory[snapshot_owner]) reasons.append(f"integration test snapshot changed: {path}") continue + if path.startswith("tests/integration/support/"): + if event == "merge_group": + # Root parity/QA binaries and every flat/group integration + # target compile this support tree, so the queue must run all + # of those consumers together. + root_partitions.update(ALL_ROOT_PARTITIONS) + integration_lanes.update(ALL_INTEGRATION_LANES) + reasons.append( + "shared integration support changed; merge group runs every " + "root and integration consumer lane" + ) + else: + integration_lanes.add(0) + reasons.append( + "shared integration support changed; PR runs a representative lane" + ) + continue if path.startswith("tests/integration/"): integration_lanes.add(0) reasons.append( @@ -1107,7 +1197,11 @@ def build_plan( reasons.append(f"integration fixture changed: {path}") continue if path.startswith(("tests/reborn_", "tests/e2e/reborn_", "scripts/ci/reborn-")): - raise ValueError(f"unmapped Reborn test path: {path}") + return _unclassified_path_plan( + event=event, + reason=f"unmapped Reborn test path: {path}", + canonical_packages=canonical_packages, + ) if path.startswith("tests/e2e/"): # E2E scenarios and support live in the dedicated # `reborn-e2e.yml` workflow, which runs its own changed-path @@ -1236,7 +1330,11 @@ def build_plan( reasons.append(f"production package changed: {package}") continue if path.startswith(("tests/reborn_", "tests/e2e/reborn_", "scripts/ci/reborn-")): - raise ValueError(f"unmapped Reborn test path: {path}") + return _unclassified_path_plan( + event=event, + reason=f"unmapped Reborn test path: {path}", + canonical_packages=canonical_packages, + ) if path.startswith("tests/e2e/"): # The browser/E2E suite has its own workflow (`reborn-e2e.yml`, # `paths: tests/e2e/**`) with its own scope detection, so this @@ -1246,8 +1344,16 @@ def build_plan( reasons.append(f"dedicated Reborn E2E workflow owns: {path}") continue if path.startswith(("scripts/", "tests/", ".github/actions/")): - raise ValueError(f"unmapped test or CI path: {path}") - raise ValueError(f"unclassified pull-request path: {path}") + return _unclassified_path_plan( + event=event, + reason=f"unmapped test or CI path: {path}", + canonical_packages=canonical_packages, + ) + return _unclassified_path_plan( + event=event, + reason=f"unclassified pull-request path: {path}", + canonical_packages=canonical_packages, + ) if nextest_config_changed: return _full_plan( @@ -1287,7 +1393,9 @@ def build_plan( for package in sorted(bucket_packages) for kind, name in sorted(exact_test_targets[package]) ] - if len(buckets) > MAX_PR_CRATE_BUCKETS: + # PR feedback is latency-bounded; merge-group coverage stays exhaustive + # and preserves every canonical bucket boundary. + if event == "pull_request" and len(buckets) > MAX_PR_CRATE_BUCKETS: original_bucket_count = len(buckets) buckets = _bound_pr_buckets(buckets) reasons.append( @@ -1311,7 +1419,7 @@ def build_plan( "integration_lanes": sorted( integration_lanes, key=lambda value: (isinstance(value, str), str(value)) ), - "run_group_tests": False, + "run_group_tests": event == "merge_group" and "groups" in integration_lanes, "run_qa_replay": run_qa_replay, "run_sandbox_docker": run_sandbox_docker, "coverage_mode": "none", @@ -1324,7 +1432,7 @@ def main() -> int: parser.add_argument( "--changed-files", type=Path, - help="newline-delimited changed paths; required for pull_request", + help="newline-delimited changed paths; required for diff events", ) parser.add_argument( "--canonical-packages", diff --git a/scripts/ci/test_changed_workspace_packages.py b/scripts/ci/test_changed_workspace_packages.py index 61029ce5936..1e8e649ed65 100644 --- a/scripts/ci/test_changed_workspace_packages.py +++ b/scripts/ci/test_changed_workspace_packages.py @@ -4,7 +4,10 @@ from __future__ import annotations import importlib.util +import json +import subprocess import sys +import tempfile import unittest from pathlib import Path @@ -25,22 +28,90 @@ def metadata() -> dict: "id": "root", "name": "root", "manifest_path": str(ROOT / "Cargo.toml"), + "dependencies": [{"name": "nested"}], }, { "id": "alpha", "name": "alpha", "manifest_path": str(ROOT / "crates/alpha/Cargo.toml"), + "dependencies": [], }, { "id": "nested", "name": "nested", "manifest_path": str(ROOT / "crates/family/nested/Cargo.toml"), + "dependencies": [{"name": "alpha"}], }, ], } +def metadata_with_renamed_workspace_dependency() -> dict: + data = metadata() + data["packages"][0]["dependencies"] = [ + { + "name": "nested", + "rename": "renamed-nested", + "path": str(ROOT / "crates/family/nested"), + } + ] + return data + + class ChangedWorkspacePackagesTests(unittest.TestCase): + def run_cli( + self, changed_paths: list[str], event: str + ) -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as temp_dir: + changed_files = Path(temp_dir) / "changed-files.txt" + changed_files.write_text("\n".join(changed_paths), encoding="utf-8") + return subprocess.run( + [ + sys.executable, + str(MODULE), + "--event", + event, + "--changed-files", + str(changed_files), + ], + cwd=ROOT, + capture_output=True, + text=True, + check=False, + ) + + def test_cli_prints_exact_scope_schema(self) -> None: + scenarios = ( + ( + "selected", + "pull_request", + ["crates/contracts/ironclaw_common/src/lib.rs"], + {"mode": "selected", "packages": ["ironclaw_common"]}, + ), + ( + "full", + "merge_group", + ["Cargo.lock"], + {"mode": "full", "packages": []}, + ), + ( + "none", + "pull_request", + ["docs/using/cli.mdx"], + {"mode": "none", "packages": []}, + ), + ) + for name, event, changed_paths, expected in scenarios: + with self.subTest(name=name): + result = self.run_cli(changed_paths, event) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout), expected) + + def test_cli_fails_fast_for_empty_merge_group_diff(self) -> None: + result = self.run_cli([], "merge_group") + self.assertNotEqual(result.returncode, 0) + self.assertIn("empty merge-group diff", result.stderr) + def test_selects_direct_production_packages(self) -> None: self.assertEqual( selector.changed_production_packages( @@ -79,6 +150,119 @@ def test_workspace_manifest_or_lockfile_selects_the_full_workspace(self) -> None ["alpha", "nested", "root"], ) + def test_pull_request_scope_preserves_production_only_selection(self) -> None: + self.assertEqual( + selector.classify_clippy_scope( + ["crates/alpha/src/lib.rs", "crates/alpha/tests/contract.rs"], + metadata(), + event="pull_request", + ), + {"mode": "selected", "packages": ["alpha"]}, + ) + + def test_merge_group_selects_changed_package_test_surfaces(self) -> None: + self.assertEqual( + selector.classify_clippy_scope( + [ + "crates/alpha/tests/contract.rs", + "crates/alpha/benches/throughput.rs", + "crates/family/nested/examples/demo.rs", + ], + metadata(), + event="merge_group", + ), + {"mode": "selected", "packages": ["alpha", "nested"]}, + ) + + def test_merge_group_production_changes_select_reverse_dependency_closure( + self, + ) -> None: + self.assertEqual( + selector.classify_clippy_scope( + ["crates/alpha/src/lib.rs"], + metadata(), + event="merge_group", + ), + {"mode": "selected", "packages": ["alpha", "nested", "root"]}, + ) + + def test_reverse_closure_uses_resolved_identity_for_renamed_dependency( + self, + ) -> None: + self.assertEqual( + selector.classify_clippy_scope( + ["crates/alpha/src/lib.rs"], + metadata_with_renamed_workspace_dependency(), + event="merge_group", + ), + {"mode": "selected", "packages": ["alpha", "nested", "root"]}, + ) + + def test_merge_group_test_surface_selects_only_owning_package(self) -> None: + self.assertEqual( + selector.classify_clippy_scope( + ["crates/alpha/tests/contract.rs"], + metadata(), + event="merge_group", + ), + {"mode": "selected", "packages": ["alpha"]}, + ) + + def test_merge_group_global_inputs_escalate_to_full(self) -> None: + for path in ( + "Cargo.toml", + "Cargo.lock", + "rust-toolchain.toml", + ".cargo/config.toml", + ".github/workflows/code_style.yml", + ".github/actions/setup-rust/action.yml", + "scripts/ci/changed_workspace_packages.py", + ): + with self.subTest(path=path): + self.assertEqual( + selector.classify_clippy_scope( + [path], metadata(), event="merge_group" + ), + {"mode": "full", "packages": []}, + ) + + def test_merge_group_workspace_member_manifests_escalate_to_full(self) -> None: + for path in ( + "crates/alpha/Cargo.toml", + "crates/family/nested/Cargo.toml", + ): + with self.subTest(path=path): + self.assertEqual( + selector.classify_clippy_scope( + [path], metadata(), event="merge_group" + ), + {"mode": "full", "packages": []}, + ) + + def test_merge_group_unknown_crate_path_escalates_to_full(self) -> None: + for path in ("crates/deleted/src/lib.rs", "Makefile"): + with self.subTest(path=path): + self.assertEqual( + selector.classify_clippy_scope( + [path], metadata(), event="merge_group" + ), + {"mode": "full", "packages": []}, + ) + + def test_empty_merge_group_diff_fails_fast(self) -> None: + with self.assertRaisesRegex(ValueError, "empty merge-group diff"): + selector.classify_clippy_scope([], metadata(), event="merge_group") + + def test_non_code_diff_selects_no_clippy_scope(self) -> None: + for event in ("pull_request", "merge_group"): + with self.subTest(event=event): + self.assertEqual( + selector.classify_clippy_scope( + ["docs/using/cli.mdx"], metadata(), event=event + ), + {"mode": "none", "packages": []}, + ) + if __name__ == "__main__": unittest.main() diff --git a/scripts/ci/test_reborn_pr_test_plan.py b/scripts/ci/test_reborn_pr_test_plan.py index b7136e8209e..b01733bdc41 100644 --- a/scripts/ci/test_reborn_pr_test_plan.py +++ b/scripts/ci/test_reborn_pr_test_plan.py @@ -4,8 +4,11 @@ from __future__ import annotations import importlib.util +import os import re +import subprocess import sys +import tempfile import tomllib import unittest from pathlib import Path @@ -273,12 +276,50 @@ def plan_real_owners(self, paths: list[str]) -> dict: ], ) - def test_merge_queue_is_always_exhaustive(self) -> None: + def test_merge_queue_uses_the_combined_diff_and_reverse_dependency_closure( + self, + ) -> None: plan = self.plan("merge_group", ["crates/alpha/src/lib.rs"]) + self.assertEqual(plan["mode"], "selected") + self.assertEqual(plan["changed_packages"], ["alpha"]) + self.assertEqual(plan["affected_packages"], ["alpha", "beta", "gamma"]) + self.assertEqual( + plan["crate_buckets"], + [{"name": "selected", "packages": ["alpha", "beta", "gamma"]}], + ) + self.assertEqual(plan["coverage_mode"], "none") + + def test_merge_queue_global_inputs_escalate_to_the_exhaustive_plan(self) -> None: + for path in ( + "Cargo.toml", + "Cargo.lock", + "crates/alpha/Cargo.toml", + "rust-toolchain.toml", + ".config/nextest.toml", + ".github/workflows/reborn-tests.yml", + ".github/actions/setup-rust/action.yml", + "scripts/ci/reborn_pr_test_plan.py", + ): + with self.subTest(path=path): + plan = self.plan("merge_group", [path]) + self.assertEqual(plan["mode"], "full") + self.assertEqual(plan["root_partitions"], [0, 1, 2, 3]) + self.assertEqual( + plan["integration_lanes"], [0, 1, 2, 3, "groups"] + ) + + def test_merge_queue_unclassified_path_escalates_but_pr_still_fails(self) -> None: + path = "Makefile" + plan = self.plan("merge_group", [path]) self.assertEqual(plan["mode"], "full") - self.assertEqual(plan["coverage_mode"], "full") - self.assertEqual(plan["root_partitions"], [0, 1, 2, 3]) - self.assertEqual(plan["integration_lanes"], [0, 1, 2, 3, "groups"]) + self.assertIn("could not classify", plan["reasons"][0]) + + with self.assertRaisesRegex(ValueError, "unclassified pull-request path"): + self.plan("pull_request", [path]) + + def test_empty_merge_queue_diff_fails_fast(self) -> None: + with self.assertRaisesRegex(ValueError, "empty merge-group diff"): + self.plan("merge_group", []) def test_changed_package_includes_transitive_reverse_dependents(self) -> None: plan = self.plan("pull_request", ["crates/alpha/src/lib.rs"]) @@ -357,6 +398,25 @@ def test_high_fanout_package_keeps_consumers_in_bounded_jobs(self) -> None: ) self.assertIn("without omitting packages", plan["reasons"][-1]) + merge_group_plan = planner.build_plan( + event="merge_group", + changed_paths=["crates/alpha/src/lib.rs"], + metadata=wide, + canonical_packages=canonical, + ) + self.assertEqual(len(merge_group_plan["crate_buckets"]), len(canonical)) + self.assertEqual( + sorted( + package + for bucket in merge_group_plan["crate_buckets"] + for package in bucket["packages"] + ), + canonical, + ) + self.assertFalse( + any("coalesced" in reason for reason in merge_group_plan["reasons"]) + ) + def test_bounded_jobs_do_not_split_canonical_buckets(self) -> None: source = [ {"name": "reborn-core", "packages": ["ironclaw", "runner"]}, @@ -2119,6 +2179,26 @@ def test_direct_root_support_runs_both_representative_tiers(self) -> None: self.assertEqual(plan["root_partitions"], [0]) self.assertEqual(plan["integration_lanes"], [0]) + def test_merge_group_shared_root_support_runs_every_root_partition(self) -> None: + for path in ( + "tests/support/reborn_parity_qa/assertions.rs", + "tests/support/mod.rs", + ): + with self.subTest(path=path): + plan = self.plan("merge_group", [path]) + self.assertEqual(plan["root_partitions"], [0, 1, 2, 3]) + + def test_merge_group_shared_integration_support_runs_every_integration_lane( + self, + ) -> None: + for path in ("tests/integration/support/database.rs", "tests/support/mod.rs"): + with self.subTest(path=path): + plan = self.plan("merge_group", [path]) + self.assertEqual( + plan["integration_lanes"], [0, 1, 2, 3, "groups"] + ) + self.assertTrue(plan["run_group_tests"]) + def test_owned_integration_support_selects_its_exact_lane(self) -> None: for path, owner in planner.INTEGRATION_SUPPORT_OWNERS.items(): @@ -2336,10 +2416,37 @@ def test_workflow_consumes_plan_and_bounds_each_rust_matrix(self) -> None: "python3 scripts/ci/changed_workspace_packages.py", code_style, ) + self.assertIn('--event "${{ github.event_name }}"', code_style) + self.assertIn("clippy_scope:", code_style) + self.assertIn("needs.changes.outputs.clippy_scope == 'selected'", code_style) self.assertIn('package_args+=(-p "${package}")', code_style) self.assertIn("needs.changes.outputs.has_clippy == 'true'", code_style) self.assertIn( - "cargo clippy --all --tests --examples ${{ matrix.flags }} -- -D warnings", + "needs.changes.outputs.has_clippy == 'true' &&\n" + " (needs.changes.outputs.has_code == 'true' ||\n" + " needs.changes.outputs.clippy_scope == 'full')", + code_style, + ) + self.assertIn( + 'if [[ "${{ needs.changes.outputs.has_code }}" == "false" &&\n' + ' "${{ needs.changes.outputs.clippy_scope }}" != "full" ]]; then', + code_style, + ) + self.assertIn('if [[ "${clippy_scope}" == "full" ]] ||', code_style) + self.assertIn( + "if: needs.changes.outputs.clippy_scope == 'full' && " + "github.event_name != 'pull_request'", + code_style, + ) + self.assertIn( + 'cargo clippy "${package_args[@]}" --all-targets', code_style + ) + self.assertIn( + 'cargo clippy "${package_args[@]}" -- -D warnings', + code_style, + ) + self.assertIn( + "cargo clippy --all --all-targets ${{ matrix.flags }} -- -D warnings", code_style, ) self.assertIn( @@ -2352,10 +2459,10 @@ def test_workflow_consumes_plan_and_bounds_each_rust_matrix(self) -> None: workflow, ) - def test_scope_checkouts_minimize_transfer_without_losing_pr_ancestry( + def test_scope_checkouts_keep_pr_ancestry_and_bound_merge_group_fetches( self, ) -> None: - """Scope jobs keep merge-base semantics without downloading history blobs.""" + """PRs keep three-dot ancestry; merge groups fetch only their base.""" reborn_tests = (ROOT / ".github/workflows/reborn-tests.yml").read_text( encoding="utf-8" ) @@ -2363,12 +2470,32 @@ def test_scope_checkouts_minimize_transfer_without_losing_pr_ancestry( "\n crate-tests:\n", 1 )[0] self.assertIn( - "fetch-depth: " - "${{ github.event_name == 'pull_request' && '0' || '1' }}", + "fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }}", reborn_scope, ) self.assertIn("filter: blob:none", reborn_scope) + self.assertIn("github.event.merge_group.base_sha", reborn_scope) + self.assertIn( + 'git fetch --no-tags --filter=blob:none --depth=1 origin "$BASE_SHA"', + reborn_scope, + ) + self.assertIn( + 'if [[ "${{ github.event_name }}" == "pull_request" || ' + '"${{ github.event_name }}" == "merge_group" ]]; then', + reborn_scope, + ) + self.assertIn('if [[ "${{ github.event_name }}" == "merge_group" ]]; then', reborn_scope) + self.assertIn('git diff --name-only "$BASE_SHA" "$HEAD_SHA"', reborn_scope) self.assertIn('git diff --name-only "$BASE_SHA"..."$HEAD_SHA"', reborn_scope) + self.assertEqual( + reborn_scope.count('git diff --name-only "$BASE_SHA" "$HEAD_SHA"'), + 1, + ) + self.assertEqual( + reborn_scope.count('git diff --name-only "$BASE_SHA"..."$HEAD_SHA"'), + 1, + ) + self.assertIn("ref: ${{ inputs.ref || github.sha }}", reborn_scope) code_style = (ROOT / ".github/workflows/code_style.yml").read_text( encoding="utf-8" @@ -2376,9 +2503,116 @@ def test_scope_checkouts_minimize_transfer_without_losing_pr_ancestry( style_scope = code_style.split("\n changes:\n", 1)[1].split( "\n fast-checks:\n", 1 )[0] - self.assertIn("fetch-depth: 0", style_scope) + self.assertIn( + "fetch-depth: ${{ github.event_name == 'pull_request' && '0' || '1' }}", + style_scope, + ) self.assertIn("filter: blob:none", style_scope) + self.assertIn("github.event.merge_group.base_sha", style_scope) + self.assertIn( + 'git fetch --no-tags --filter=blob:none --depth=1 origin "$BASE_SHA"', + style_scope, + ) + self.assertIn('if [[ "${{ github.event_name }}" == "merge_group" ]]; then', style_scope) + self.assertIn('git diff --name-only "$BASE_SHA" "$HEAD_SHA"', style_scope) self.assertIn('git diff --name-only "$BASE_SHA"..."$HEAD_SHA"', style_scope) + self.assertEqual( + style_scope.count('git diff --name-only "$BASE_SHA" "$HEAD_SHA"'), + 1, + ) + self.assertEqual( + style_scope.count('git diff --name-only "$BASE_SHA"..."$HEAD_SHA"'), + 1, + ) + + def test_scope_diff_branches_execute_the_event_specific_revision_range(self) -> None: + """Execute each workflow's branch and inspect the git arguments it uses.""" + + workflows = ( + ( + ROOT / ".github/workflows/reborn-tests.yml", + ' if [[ "${{ github.event_name }}" == "merge_group" ]]; then', + " changed_args=(--changed-files", + 12, + ), + ( + ROOT / ".github/workflows/code_style.yml", + ' if [[ "${{ github.event_name }}" == "merge_group" ]]; then', + ' printf \'%s\\n\' "$CHANGED_FILES" >', + 10, + ), + ) + expected_ranges = { + "merge_group": ["base-sha", "head-sha"], + "pull_request": ["base-sha...head-sha"], + } + + for workflow_path, start, end, indentation in workflows: + workflow = workflow_path.read_text(encoding="utf-8") + block_start = workflow.index(start) + block_end = workflow.index(end, block_start) + block = workflow[block_start:block_end] + shell = "\n".join( + line[indentation:] if line else "" + for line in block.splitlines() + ) + for event, expected_range in expected_ranges.items(): + with self.subTest(workflow=workflow_path.name, event=event): + rendered = shell.replace("${{ github.event_name }}", event) + with tempfile.TemporaryDirectory() as temp: + temp_path = Path(temp) + bin_path = temp_path / "bin" + bin_path.mkdir() + git_log = temp_path / "git-args.txt" + git_stub = bin_path / "git" + git_stub.write_text( + "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$GIT_LOG\"\n", + encoding="utf-8", + ) + git_stub.chmod(0o755) + environment = os.environ.copy() + environment.update( + { + "BASE_SHA": "base-sha", + "HEAD_SHA": "head-sha", + "GIT_LOG": str(git_log), + "PATH": f"{bin_path}{os.pathsep}{environment['PATH']}", + "RUNNER_TEMP": str(temp_path), + } + ) + result = subprocess.run( + ["bash", "-c", rendered], + cwd=ROOT, + env=environment, + capture_output=True, + text=True, + ) + self.assertEqual( + result.returncode, + 0, + result.stderr, + ) + self.assertEqual( + git_log.read_text(encoding="utf-8").splitlines(), + ["diff", "--name-only", *expected_range], + ) + + def test_windows_push_clippy_keeps_tests_and_examples_scope(self) -> None: + code_style = (ROOT / ".github/workflows/code_style.yml").read_text( + encoding="utf-8" + ) + windows_scope = code_style.split("\n clippy-windows:\n", 1)[1].split( + "\n reborn-cli-smoke:\n", 1 + )[0] + self.assertIn( + "if: needs.changes.outputs.has_code == 'true' && github.event_name == 'push'", + windows_scope, + ) + self.assertIn( + "run: cargo clippy --all --tests --examples ${{ matrix.flags }} -- -D warnings", + windows_scope, + ) + self.assertNotIn("--all-targets", windows_scope) def test_pr_workflows_do_not_repeat_reborn_rust_contracts(self) -> None: code_style = (ROOT / ".github/workflows/code_style.yml").read_text(