diff --git a/.github/actions/prepare-parity/action.yml b/.github/actions/prepare-parity/action.yml new file mode 100644 index 0000000000..39229038a7 --- /dev/null +++ b/.github/actions/prepare-parity/action.yml @@ -0,0 +1,44 @@ +name: Prepare the parity inputs +description: >- + Put this run's rescript executable (from the build job) and OCaml reference + executables (from the ocaml job) where the parity scripts and the compiler + tests look for them. Then build the runtime, Belt and tests/tests with the + OCaml compiler, whose compiled files the OCaml side and the compiler test + fixtures read. + +runs: + using: composite + steps: + - uses: actions/download-artifact@v8 + with: + name: rescript + + - uses: actions/download-artifact@v8 + with: + name: ocaml + path: ${{ runner.temp }}/ocaml + + - name: Install the executables + shell: bash + run: | + tar -xmf rescript.tar + rm rescript.tar + ./scripts/rust_compiler_shims.sh release + # Where the parity scripts look for them: the dune install directory + # and the platform npm package, as `make lib` leaves them. + ocaml="$RUNNER_TEMP/ocaml" + platform_bin="packages/@rescript/$(./scripts/platform.sh)/bin" + mkdir -p _build/install/default/bin "$platform_bin" + install -m 755 "$ocaml/bsc" "$ocaml/res_parser" _build/install/default/bin/ + install -m 755 "$ocaml/bsc" "$platform_bin/bsc.exe" + install -m 755 rewatch/target/release/rescript "$platform_bin/rescript.exe" + + - name: Build the runtime, Belt and tests/tests + shell: bash + run: | + export RESCRIPT_RUNTIME="$PWD/packages/@rescript/runtime" + rescript=rewatch/target/release/rescript + "$rescript" build packages/@rescript/runtime > /dev/null + "$rescript" build packages/@rescript/belt > /dev/null + PROJECT_ROOT="$PWD" RUST_TARGET=release bash -c \ + 'source scripts/parity_lib.sh && parity_build_ocaml_reference "$PROJECT_ROOT/tests/tests"' diff --git a/.github/workflows/instruction-count.yml b/.github/workflows/instruction-count.yml new file mode 100644 index 0000000000..aa6f3302b6 --- /dev/null +++ b/.github/workflows/instruction-count.yml @@ -0,0 +1,216 @@ +name: Instruction count + +# Counts the instructions a clean build of tests/tests executes with the +# pull request's compiler and with its base's (scripts/compare_build_instructions.py), +# and fails when the pull request's executes more than 0.1% more: a change +# that adds instructions makes every build slower. +# +# Cachegrind counts instructions in software, because GitHub's runners have +# no hardware counters. With one worker thread the count of one executable +# varies by about 0.1% between runs, hence the threshold. +# +# An increase can be accepted by a commit in the pull request whose message +# has an `Instruction-count-increase:` trailer saying why. +# +# Trunk runs build and cache the executable of each trunk commit, so a pull +# request normally builds only its own. When the base's is not cached, the +# base job builds it at the same time. + +on: + pull_request: + push: + branches: [ocaml-to-rust-rewrite] + +permissions: + contents: read + +concurrency: + group: instruction-count-${{ github.ref }} + # A trunk run is left to finish, so that it caches its executable. + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # The shipped configuration without profile-guided optimization: fat LTO + # and one codegen unit. With more units, how the code happens to be + # partitioned moves the count by up to 1%. + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "1" + CACHE_PREFIX: instruction-count-rescript-v1 + +jobs: + # The executable of the commit under test: the pull request merged into + # its base, or a trunk commit. + head: + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v6 + + - name: Install the pinned Rust toolchain + run: rustup toolchain install + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: rewatch -> target + shared-key: instruction-count + save-if: ${{ github.event_name == 'push' }} + + - name: Build + run: | + cargo build --release --locked --manifest-path rewatch/Cargo.toml + mkdir -p executable + cp rewatch/target/release/rescript executable/ + + - uses: actions/upload-artifact@v7 + with: + name: rescript-head + path: executable/rescript + retention-days: 3 + + - name: Cache the executable for pull requests based on this commit + if: ${{ github.event_name == 'push' }} + uses: actions/cache/save@v5 + with: + path: executable/rescript + key: ${{ env.CACHE_PREFIX }}-${{ github.sha }} + + # The executable of the parent commit: the base of a pull request, or the + # previous trunk commit. A trunk run only reuses a cached one, for the + # report; it does not build it. + base: + runs-on: ubuntu-24.04 + timeout-minutes: 40 + outputs: + available: ${{ steps.result.outputs.available }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 2 + + - name: Find the parent commit + id: parent + run: echo "sha=$(git rev-parse HEAD^1)" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v5 + id: cached + with: + path: executable/rescript + key: ${{ env.CACHE_PREFIX }}-${{ steps.parent.outputs.sha }} + + - name: Check out the parent commit + if: ${{ steps.cached.outputs.cache-hit != 'true' && github.event_name == 'pull_request' }} + run: git checkout --detach "${{ steps.parent.outputs.sha }}" + + - name: Install the pinned Rust toolchain + if: ${{ steps.cached.outputs.cache-hit != 'true' && github.event_name == 'pull_request' }} + run: rustup toolchain install + + - uses: Swatinem/rust-cache@v2 + if: ${{ steps.cached.outputs.cache-hit != 'true' && github.event_name == 'pull_request' }} + with: + workspaces: rewatch -> target + shared-key: instruction-count + save-if: false + + - name: Build + if: ${{ steps.cached.outputs.cache-hit != 'true' && github.event_name == 'pull_request' }} + run: | + cargo build --release --locked --manifest-path rewatch/Cargo.toml + mkdir -p executable + cp rewatch/target/release/rescript executable/ + + - name: Record whether there is an executable + id: result + run: | + if [[ -x executable/rescript ]]; then + echo "available=true" >> "$GITHUB_OUTPUT" + else + echo "No cached executable of the parent commit; nothing to compare against." + echo "available=false" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/upload-artifact@v7 + if: ${{ steps.result.outputs.available == 'true' }} + with: + name: rescript-base + path: executable/rescript + retention-days: 3 + + compare: + needs: [head, base] + if: ${{ needs.base.outputs.available == 'true' }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 2 + + - uses: ./.github/actions/setup-node + + - name: Install Valgrind + run: | + sudo apt-get update -q + sudo apt-get install -y -q --no-install-recommends valgrind + + - uses: actions/download-artifact@v8 + with: + pattern: rescript-* + path: executables + + # Both executables build the parent's tests/tests, so a pull request + # that adds or edits tests does not change what is measured. Each + # builds its own commit's runtime, which its executable embeds. + # + # The two checkouts are at paths of the same depth and length: the + # compiler walks and compares source paths, and a deeper checkout + # alone costs about 0.08% more instructions. + - name: Prepare the two checkouts + run: | + chmod +x executables/*/rescript + parent=$(git rev-parse HEAD^1) + git worktree add --detach "$RUNNER_TEMP/base" "$parent" + git worktree add --detach "$RUNNER_TEMP/head" HEAD + git -C "$RUNNER_TEMP/head" restore --source="$parent" --worktree -- tests/tests tests/dependencies + for side in base head; do + (cd "$RUNNER_TEMP/$side" && yarn install --immutable) + done + + # Only a real trailer counts: the line has to be in the message's last + # paragraph of `Key: value` lines, as git interpret-trailers reads it. + - name: Find an accepted increase + id: accepted + if: ${{ github.event_name == 'pull_request' }} + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + reasons="" + while read -r message; do + reason=$(printf '%s' "$message" | base64 -d | + git interpret-trailers --parse | sed -n 's/^Instruction-count-increase: *//Ip') + reasons+=${reason:+$reason$'\n'} + done < <(gh api --paginate "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/commits?per_page=100" \ + --jq '.[].commit.message | @base64') + if [[ -n "$reasons" ]]; then + printf 'Accepted increase: %s' "$reasons" + echo "flag=--allow-increase" >> "$GITHUB_OUTPUT" + fi + + - name: Compare + run: | + python3 scripts/compare_build_instructions.py \ + --base executables/rescript-base/rescript "$RUNNER_TEMP/base" \ + --head executables/rescript-head/rescript "$RUNNER_TEMP/head" \ + --runs 5 \ + --work-dir "$RUNNER_TEMP/cachegrind" \ + --summary "$GITHUB_STEP_SUMMARY" \ + ${{ steps.accepted.outputs.flag }} \ + ${{ github.event_name == 'push' && '--allow-increase' || '' }} + + - uses: actions/upload-artifact@v7 + if: ${{ always() }} + with: + name: cachegrind + path: ${{ runner.temp }}/cachegrind + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/rust-rewrite-validation.yml b/.github/workflows/rust-rewrite-validation.yml index 85c8d1eec0..287f3f696e 100644 --- a/.github/workflows/rust-rewrite-validation.yml +++ b/.github/workflows/rust-rewrite-validation.yml @@ -4,7 +4,7 @@ on: # Every pull request, including ones stacked on another PR's branch. pull_request: # The trunk as well. A cache saved by a pull request run is visible to that - # pull request alone, so the trunk runs are what save the OPAM, package and + # pull request alone, so the trunk runs are what save the OPAM, OCaml and # Rust caches that pull requests start from. push: branches: [ocaml-to-rust-rewrite] @@ -17,14 +17,54 @@ concurrency: # A trunk run is left to finish, so that it saves its caches. cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + RUST_BACKTRACE: "1" + # Everything here checks behaviour, which link-time optimization does not + # change, and fat LTO is most of a release build's time. The Instruction + # count workflow builds the shipped configuration. + CARGO_PROFILE_RELEASE_LTO: "off" + # Keep rustc's incremental state in the cached target directories, so a + # pull request recompiles what it changed rather than whole crates. + CARGO_PROFILE_RELEASE_INCREMENTAL: "true" + # Decide whether a file changed by its contents, not its mtime: a fresh + # checkout dates every file now, which would make every restored crate + # stale. A nightly Cargo flag; rust-toolchain.toml pins a nightly. + CARGO_UNSTABLE_CHECKSUM_FRESHNESS: "true" + +# How the jobs overlap, on 4-CPU Arm runners: +# +# build ──────────────┬─> parity (4 suites), ir-parity (3 suites) +# ocaml ──────────────┘ +# compiler-tests: compiles its tests, then waits for build and ocaml +# build-system-tests, script-tests, compiler-warnings: on their own +# +# Rust target directories are cached by trunk runs and restored by pull +# requests (build-system-tests saves the release one, compiler-tests the dev +# one), so a pull request compiles what changed against the trunk. jobs: + # Warning-free Clippy and rustdoc for the compiler crate. Its check + # artifacts are cached by trunk runs like the other Rust targets. compiler-warnings: - runs-on: ubuntu-24.04 + runs-on: ubuntu-24.04-arm timeout-minutes: 15 steps: - uses: actions/checkout@v6 - name: Install the pinned Rust toolchain run: rustup toolchain install --component clippy + + - uses: actions/cache/restore@v5 + id: cache + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + compiler-rust/target + key: validation-compiler-warnings-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock') }}-${{ github.sha }} + restore-keys: | + validation-compiler-warnings-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock') }}- + validation-compiler-warnings-v1-${{ runner.os }}-${{ runner.arch }}- + - name: Check all compiler targets and feature configurations run: | cargo clippy --locked --manifest-path compiler-rust/Cargo.toml --all-targets --all-features -- -D warnings @@ -34,135 +74,321 @@ jobs: RUSTDOCFLAGS: "-D warnings" run: cargo doc --locked --manifest-path compiler-rust/Cargo.toml --all-features --no-deps - release-parity: - runs-on: ubuntu-24.04 - timeout-minutes: 90 - env: - RUST_BACKTRACE: "1" + - uses: actions/cache/save@v5 + if: ${{ !cancelled() && github.event_name == 'push' && steps.cache.outputs.cache-hit != 'true' }} + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + compiler-rust/target + key: ${{ steps.cache.outputs.cache-primary-key }} + + build: + runs-on: ubuntu-24.04-arm + timeout-minutes: 40 steps: - uses: actions/checkout@v6 - - name: Test parity failure reporting - run: | - python3 scripts/test_js_output_fixture_reporting.py - python3 scripts/test_typedtree_parity_exit.py - python3 scripts/test_parser_ast0_parity_exit.py - python3 scripts/test_parser_ast_parity_exit.py - python3 scripts/test_error_output_parity_exit.py - # rust-toolchain.toml pins the toolchain of every Rust build here. - name: Install the pinned Rust toolchain run: rustup toolchain install - # Saved by trunk runs only (see the end of the job). Cargo rebuilds this - # repository's crates after a fresh checkout whatever is restored, so - # what a run gets from it is the compiled dependencies. - uses: actions/cache/restore@v5 - id: rust-cache with: path: | - ~/.cargo/registry - ~/.cargo/git - compiler-rust/target + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db rewatch/target - key: rewrite-release-v2-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock', 'rewatch/Cargo.lock') }}-${{ github.sha }} + key: validation-release-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'rewatch/Cargo.lock') }}-${{ github.sha }} restore-keys: | - rewrite-release-v2-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock', 'rewatch/Cargo.lock') }}- - - - uses: ./.github/actions/setup-node - - uses: ./.github/actions/setup-linux-dependencies + validation-release-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'rewatch/Cargo.lock') }}- + validation-release-v1-${{ runner.os }}-${{ runner.arch }}- - # The compiler crate is not built on its own here: the build system - # links it, and the compiler test step below compiles it standalone. - name: Build release Rust compiler and build system - id: rust-build run: | cargo build --release --locked --manifest-path rewatch/Cargo.toml - ./scripts/rust_compiler_shims.sh release + tar -cf rescript.tar rewatch/target/release/rescript - # The same OCaml as ci.yml: diagnostics are laid out by OCaml's Format, - # whose break sizing changed in 5.5, and the Rust formatter follows it. - - uses: ./.github/actions/setup-ocaml + - uses: actions/upload-artifact@v7 with: - compiler: "5.5.2" - os: ubuntu-24.04 - cache-prefix: opam-rewrite-validation-v1 + name: rescript + path: rescript.tar + retention-days: 3 - - name: Build native reference compiler and libraries - # Finds the rescript executable built above up to date. - run: opam exec -- make lib + # The OCaml reference compiler and parser. They change rarely, so they are + # cached by the sources dune builds them from, and OPAM is only set up when + # that cache misses. + ocaml: + runs-on: ubuntu-24.04-arm + timeout-minutes: 40 + env: + OCAML_VERSION: "5.5.2" + steps: + - uses: actions/checkout@v6 - - name: Compare exact CLI output filenames and marshal debug output + - name: Hash the OCaml sources + id: sources run: | - python3 scripts/test_bsc_output_filenames.py - python3 scripts/test_marshal_debug_flags.py + # The files the Makefile's dune build depends on. + hash=$({ + echo "$OCAML_VERSION" + git ls-files -s -- compiler analysis tools rewatch-ocaml tests | + awk '$4 ~ /(\.(ml|mli|c|h|dune)|\/dune|\/dune-project)$/' + git ls-files -s -- dune-project dune '*.opam' + } | sha256sum | cut -c1-32) + echo "hash=$hash" >> "$GITHUB_OUTPUT" - - name: Build native test corpus for compiler unit fixtures - id: fixtures - # The fixtures compile tests/tests sources file by file against .cmi - # files, which only the OCaml reference build writes. + - uses: actions/cache/restore@v5 + id: cached + with: + path: ocaml-bin + key: ocaml-reference-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.sources.outputs.hash }} + + - uses: ./.github/actions/setup-ocaml + if: ${{ steps.cached.outputs.cache-hit != 'true' }} + with: + compiler: ${{ env.OCAML_VERSION }} + os: ubuntu-24.04-arm + cache-prefix: opam-rewrite-validation-v1 + + - name: Build the OCaml compiler and parser + if: ${{ steps.cached.outputs.cache-hit != 'true' }} run: | - PROJECT_ROOT="$PWD" RUST_TARGET=release bash -c \ - 'source scripts/parity_lib.sh && parity_build_ocaml_reference "$PROJECT_ROOT/tests/tests"' + opam exec -- dune build compiler/bsc/rescript_compiler_main.exe compiler/syntax/cli/res_cli.exe + mkdir -p ocaml-bin + cp _build/default/compiler/bsc/rescript_compiler_main.exe ocaml-bin/bsc + cp _build/default/compiler/syntax/cli/res_cli.exe ocaml-bin/res_parser - # The suite includes subprocess timing assertions. Run tests serially so - # those benchmarks do not compete with one another for CPU time. - # This step builds only the test binary, which nothing ships from, so it - # skips link-time optimization: that is most of the build's time. - - name: Test release Rust compiler - env: - CARGO_PROFILE_RELEASE_LTO: "off" - run: cargo test --release --locked --manifest-path compiler-rust/Cargo.toml -- --test-threads=1 + # Saved by pull requests too: the cache is small, and keyed by content. + - uses: actions/cache/save@v5 + if: ${{ steps.cached.outputs.cache-hit != 'true' }} + with: + path: ocaml-bin + key: ${{ steps.cached.outputs.cache-primary-key }} + - uses: actions/upload-artifact@v7 + with: + name: ocaml + path: ocaml-bin + retention-days: 3 + + build-system-tests: + runs-on: ubuntu-24.04-arm + timeout-minutes: 40 + steps: + - uses: actions/checkout@v6 + + - name: Install the pinned Rust toolchain + run: rustup toolchain install + + - uses: actions/cache/restore@v5 + id: cache + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + rewatch/target + key: validation-release-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'rewatch/Cargo.lock') }}-${{ github.sha }} + restore-keys: | + validation-release-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'rewatch/Cargo.lock') }}- + validation-release-v1-${{ runner.os }}-${{ runner.arch }}- + + - uses: ./.github/actions/setup-node + + # Builds what the build job builds, and the tests on top. - name: Test release build system - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - run: cargo test --release --locked --manifest-path rewatch/Cargo.toml + run: | + cargo build --release --locked --manifest-path rewatch/Cargo.toml + cargo test --release --locked --manifest-path rewatch/Cargo.toml - - name: Typedtree parity - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - # Diagnostic only; see "The Correctness Contract" in AGENTS.md. - continue-on-error: true - run: ./scripts/test_typedtree_parity.sh --release --parallel 2 + # This job saves the release cache rather than the build job, which + # the parity jobs wait for: saving a gigabyte takes a while. + - uses: actions/cache/save@v5 + if: ${{ !cancelled() && github.event_name == 'push' && steps.cache.outputs.cache-hit != 'true' }} + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + rewatch/target + key: ${{ steps.cache.outputs.cache-primary-key }} - - name: Raw Lambda parity - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - # Diagnostic only; see "The Correctness Contract" in AGENTS.md. - continue-on-error: true - run: ./scripts/test_lambda_parity.sh --release --raw --parallel 2 + # The parity scripts' own tests. They need nothing built. + script-tests: + runs-on: ubuntu-24.04-arm + timeout-minutes: 15 + steps: + - uses: actions/checkout@v6 - - name: Optimized Lambda parity - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - # Diagnostic only; see "The Correctness Contract" in AGENTS.md. - continue-on-error: true - run: ./scripts/test_lambda_parity.sh --release --parallel 2 + - name: Test parity failure reporting + run: | + status=0 + pids=() + for test in test_js_output_fixture_reporting test_typedtree_parity_exit \ + test_parser_ast0_parity_exit test_parser_ast_parity_exit test_error_output_parity_exit; do + python3 "scripts/$test.py" > "$RUNNER_TEMP/$test.log" 2>&1 & + pids+=("$!:$test") + done + for entry in "${pids[@]}"; do + test=${entry#*:} + if wait "${entry%%:*}"; then + echo "::group::$test passed" + else + status=1 + echo "::group::$test FAILED" + fi + cat "$RUNNER_TEMP/$test.log" + echo "::endgroup::" + done + exit $status - - name: JavaScript output parity - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - run: ./scripts/test_js_output_parity.sh --release + compiler-tests: + runs-on: ubuntu-24.04-arm + timeout-minutes: 40 + permissions: + contents: read + # To see when the build and ocaml jobs have uploaded their artifacts. + actions: read + steps: + - uses: actions/checkout@v6 - - name: Diagnostic parity - if: ${{ !cancelled() && steps.fixtures.outcome == 'success' }} - # Compare normal user-facing errors, not runtime-specific backtraces. - run: env -u OCAMLRUNPARAM -u RUST_BACKTRACE ./scripts/test_error_output_parity.sh --release + - name: Install the pinned Rust toolchain + run: rustup toolchain install + + - uses: actions/cache/restore@v5 + id: cache + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + compiler-rust/target + key: validation-compiler-tests-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock') }}-${{ github.sha }} + restore-keys: | + validation-compiler-tests-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('rust-toolchain.toml', 'compiler-rust/Cargo.lock') }}- + validation-compiler-tests-v1-${{ runner.os }}-${{ runner.arch }}- + + # The tests run in half a second; building them is the cost, and a + # dev build is the faster one. + - name: Build the Rust compiler tests + run: cargo test --locked --no-run --manifest-path compiler-rust/Cargo.toml - # Keep successful build artifacts even when a later assertion fails. - # The job still fails; this only avoids rebuilding unchanged code. - uses: actions/cache/save@v5 - if: ${{ !cancelled() && github.event_name == 'push' && steps.rust-build.outcome == 'success' && steps.rust-cache.outputs.cache-hit != 'true' }} + if: ${{ github.event_name == 'push' && steps.cache.outputs.cache-hit != 'true' }} with: path: | - ~/.cargo/registry - ~/.cargo/git + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db compiler-rust/target - rewatch/target - key: ${{ steps.rust-cache.outputs.cache-primary-key }} + key: ${{ steps.cache.outputs.cache-primary-key }} + + - uses: ./.github/actions/setup-node + + # The tests read .cmi files of tests/tests that only the OCaml compiler + # writes, so they need the other jobs' executables. Rather than + # waiting for those jobs before starting, this job builds the tests + # meanwhile and waits here. + - name: Wait for the build and ocaml jobs + env: + GH_TOKEN: ${{ github.token }} + run: | + api="repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + deadline=$((SECONDS + 1800)) + until names=$(gh api "$api/artifacts" --jq '.artifacts[].name') && + grep -qx rescript <<< "$names" && grep -qx ocaml <<< "$names"; do + failed=$(gh api "$api/attempts/$GITHUB_RUN_ATTEMPT/jobs" --jq \ + '.jobs[] | select((.name == "build" or .name == "ocaml") and .status == "completed" and .conclusion != "success") | .name' || true) + if [[ -n "$failed" ]]; then + echo "::error::No executables to test with: job $failed failed" + exit 1 + fi + if (( SECONDS > deadline )); then + echo "::error::Timed out waiting for the build and ocaml jobs" + exit 1 + fi + sleep 10 + done + + - uses: ./.github/actions/prepare-parity + + # The suite includes subprocess timing assertions. Run tests serially so + # those benchmarks do not compete with one another for CPU time. + - name: Test Rust compiler + run: cargo test --locked --manifest-path compiler-rust/Cargo.toml -- --test-threads=1 + + # The parity suites that gate a change (see "The Correctness Contract" in + # AGENTS.md), each its own check so that a pull request shows which one + # failed. + parity: + name: parity (${{ matrix.suite }}) + needs: [build, ocaml] + runs-on: ubuntu-24.04-arm + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - suite: javascript + run: | + python3 scripts/test_bsc_output_filenames.py + python3 scripts/test_marshal_debug_flags.py + ./scripts/test_js_output_parity.sh --release + - suite: diagnostics + # Compare normal user-facing errors, not runtime-specific backtraces. + run: env -u OCAMLRUNPARAM -u RUST_BACKTRACE ./scripts/test_error_output_parity.sh --release + - suite: stdlib + run: RUST_TARGET=release ./scripts/test_stdlib_output_parity.sh + - suite: gentype + # The in-repo suites; the Tella suite needs a private checkout. + run: | + GENTYPE_PARITY_WITHOUT_TELLA=1 \ + REWATCH_BIN="$PWD/rewatch/target/release/rescript" \ + RUST_BSC="$PWD/rewatch/target/release/bsc" \ + ./scripts/test_gentype_output_parity.sh + steps: + - uses: actions/checkout@v6 + - uses: ./.github/actions/setup-node + - uses: ./.github/actions/prepare-parity + + - name: ${{ matrix.suite }} parity + run: ${{ matrix.run }} - name: Preserve failed parity diagnostics if: ${{ failure() }} uses: actions/upload-artifact@v7 with: - name: parity-diagnostics-${{ github.event.pull_request.number }} + name: parity-${{ matrix.suite }}-${{ github.event.pull_request.number || github.sha }} path: .parity-cache include-hidden-files: true if-no-files-found: ignore retention-days: 7 + + # Diagnostic only; see "The Correctness Contract" in AGENTS.md. These help + # find the layer a JavaScript or diagnostic difference starts in. + ir-parity: + name: ir-parity (${{ matrix.suite }}) + needs: [build, ocaml] + runs-on: ubuntu-24.04-arm + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - suite: typedtree + run: ./scripts/test_typedtree_parity.sh --release --parallel 4 + - suite: raw-lambda + run: ./scripts/test_lambda_parity.sh --release --raw --parallel 4 + - suite: lambda + run: ./scripts/test_lambda_parity.sh --release --parallel 4 + steps: + - uses: actions/checkout@v6 + - uses: ./.github/actions/setup-node + - uses: ./.github/actions/prepare-parity + + - name: ${{ matrix.suite }} parity + continue-on-error: true + run: ${{ matrix.run }} diff --git a/AGENTS.md b/AGENTS.md index 0b9ab0880f..9cefdbf1d6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -433,6 +433,8 @@ These principles apply to all performance-sensitive Rust code in the compiler, e - **Always benchmark with `hyperfine`** — Every performance change must have before/after numbers. "Should be faster" is not evidence. Use `hyperfine` with multiple runs and a representative `--prepare` step for clean-build measurements, then report the mean, standard deviation, and min/max range. +- **CI blocks instruction increases** — The `Instruction count` workflow counts the instructions of a clean `tests/tests` build (cachegrind, one worker thread) with the pull request's `rescript` and its base's, both built like a release, and fails when the pull request's executes more than 0.1% more. When a change has to cost more, give one of its commits an `Instruction-count-increase: ` trailer. On Linux, `scripts/compare_build_instructions.py` runs the same comparison locally. + - **Profile before optimizing** — Use flamegraphs (`cargo flamegraph`), `perf stat` (cache misses, branch misses), or DHAT (heap profiling) to find actual bottlenecks. Don't guess. - **Measure struct sizes** — Add `assert_eq!(std::mem::size_of::(), N)` tests for critical types. Enum size regressions (someone adds a large variant) silently degrade cache performance across the entire codebase. diff --git a/scripts/compare_build_instructions.py b/scripts/compare_build_instructions.py new file mode 100644 index 0000000000..e76fc74d88 --- /dev/null +++ b/scripts/compare_build_instructions.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Compare the instructions two `rescript` executables execute in a clean build. + +Each side is an executable and a checkout: the executable builds the +checkout's runtime package, then cleans and builds the project +(`tests/tests` by default) under Valgrind's cachegrind, which counts the +instructions the process executes. The build runs on one worker thread, so +the count barely moves between runs of the same executable (about 0.1% from +run to run); the smallest of `--runs` builds (five by default) is the side's count. + +Both sides run at the same time, each in its own checkout, so the two +projects must be separate directories. + + scripts/compare_build_instructions.py \\ + --base BASE_RESCRIPT BASE_CHECKOUT --head HEAD_RESCRIPT HEAD_CHECKOUT + +Prints a Markdown report (also appended to --summary) and exits with 1 when +the head executes more than --threshold percent more instructions than the +base, unless --allow-increase is given. +""" + +import argparse +import concurrent.futures +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +SUMMARY_LINE = re.compile(r"^summary:\s+(\d+)", re.MULTILINE) +COMPILED_LINE = re.compile(r"Compiled (\d+) modules") + + +def run(cmd, env, cwd=None): + result = subprocess.run(cmd, env=env, cwd=cwd, capture_output=True, text=True) + if result.returncode != 0: + sys.stderr.write(f"$ {' '.join(map(str, cmd))}\n{result.stdout}{result.stderr}") + raise SystemExit(f"command failed with exit code {result.returncode}") + return result.stdout + result.stderr + + +class Side: + def __init__(self, name, exe, checkout, project, work_dir): + self.name = name + self.exe = str(Path(exe).resolve()) + self.checkout = Path(checkout).resolve() + self.project = self.checkout / project + self.runtime = self.checkout / "packages" / "@rescript" / "runtime" + self.work_dir = work_dir + self.counts = [] + self.modules = None + self.env = dict(os.environ, RESCRIPT_RUNTIME=str(self.runtime), RAYON_NUM_THREADS="1") + + def prepare(self): + # Builds read the runtime's lib/ocaml folder, which only a build of + # the runtime writes. Not measured. + run([self.exe, "build", str(self.runtime)], self.env) + + def measure(self, index): + run([self.exe, "clean", str(self.project)], self.env) + out_file = self.work_dir / f"{self.name}-{index}.cachegrind" + output = run( + [ + "valgrind", + "--tool=cachegrind", + "--cache-sim=no", + f"--cachegrind-out-file={out_file}", + self.exe, + "build", + str(self.project), + ], + self.env, + ) + modules = COMPILED_LINE.findall(output) + self.modules = int(modules[-1]) if modules else None + count = int(SUMMARY_LINE.search(out_file.read_text()).group(1)) + self.counts.append((count, out_file)) + return count + + def best(self): + return min(self.counts) + + +def function_diff(base_file, head_file, limit): + """The functions whose counts moved most, from cg_annotate --diff.""" + result = subprocess.run( + ["cg_annotate", "--diff", str(base_file), str(head_file)], + capture_output=True, + text=True, + ) + if result.returncode != 0: + return f"cg_annotate failed: {result.stderr.strip()}" + lines = result.stdout.splitlines() + try: + start = next(i for i, line in enumerate(lines) if "File:function summary" in line) + except StopIteration: + return result.stdout + body = [] + for line in lines[start + 3 :]: + if line.startswith("----"): + break + if line.strip(): + body.append(line) + return "\n".join(body[:limit]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--base", nargs=2, metavar=("RESCRIPT", "CHECKOUT"), required=True) + parser.add_argument("--head", nargs=2, metavar=("RESCRIPT", "CHECKOUT"), required=True) + parser.add_argument("--project", default="tests/tests", help="project to build, relative to each checkout") + parser.add_argument("--runs", type=int, default=5) + parser.add_argument("--threshold", type=float, default=0.1, help="allowed increase, in percent") + parser.add_argument("--allow-increase", action="store_true", help="report an increase without failing") + parser.add_argument("--summary", help="file to append the Markdown report to") + parser.add_argument("--work-dir", help="where to keep the cachegrind files") + args = parser.parse_args() + + work_dir = Path(args.work_dir or tempfile.mkdtemp(prefix="instruction-count-")) + work_dir.mkdir(parents=True, exist_ok=True) + base = Side("base", *args.base, args.project, work_dir) + head = Side("head", *args.head, args.project, work_dir) + if base.project == head.project: + raise SystemExit("the base and head projects must be separate checkouts") + + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + list(pool.map(Side.prepare, (base, head))) + for index in range(args.runs): + base_count, head_count = pool.map(lambda side: side.measure(index), (base, head)) + print(f"run {index + 1}: base {base_count:,} head {head_count:,}", file=sys.stderr) + + (base_count, base_file), (head_count, head_file) = base.best(), head.best() + delta = head_count - base_count + percent = 100.0 * delta / base_count + regressed = percent > args.threshold + + def runs(side): + return ", ".join(f"{count / 1e6:,.1f}" for count, _ in side.counts) + + if regressed and args.allow_increase: + verdict = f"More instructions than the threshold of +{args.threshold}%, accepted by the pull request." + elif regressed: + verdict = f"**More instructions than the threshold of +{args.threshold}%: this change makes the compiler slower.**" + elif percent < -args.threshold: + verdict = "Fewer instructions." + else: + verdict = f"Within the threshold of +{args.threshold}%." + + report = [ + f"### Instructions of a clean `{args.project}` build", + "", + verdict, + "", + "| | instructions | runs (millions) | modules |", + "| --- | ---: | --- | ---: |", + f"| base | {base_count:,} | {runs(base)} | {base.modules} |", + f"| head | {head_count:,} | {runs(head)} | {head.modules} |", + f"| change | {delta:+,} ({percent:+.3f}%) | | |", + "", + "One worker thread, counted by cachegrind; the smallest run of each side.", + "", + "
Functions that changed most", + "", + "```", + function_diff(base_file, head_file, 40), + "```", + "", + "
", + "", + ] + text = "\n".join(report) + print(text) + if args.summary: + with open(args.summary, "a") as summary: + summary.write(text) + if base.modules != head.modules: + print(f"::warning::base compiled {base.modules} modules and head {head.modules}", file=sys.stderr) + return 1 if regressed and not args.allow_increase else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test_error_output_parity.sh b/scripts/test_error_output_parity.sh index f47a1bf6c9..3e5a83f09c 100755 --- a/scripts/test_error_output_parity.sh +++ b/scripts/test_error_output_parity.sh @@ -13,6 +13,7 @@ RUN_COMPILER=true INCLUDE_SUPER_ERRORS=true FILE_ARG="" TIMEOUT_SECONDS="${TIMEOUT_SECONDS:-10}" +PARITY_JOBS="${PARITY_JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)}" usage() { cat <<'EOF' @@ -34,6 +35,8 @@ OPTIONS: ENV: OCAML_BSC, RUST_BSC, OCAML_PARSER, RUST_PARSER can override binary paths. TIMEOUT_SECONDS defaults to 10. + PARITY_JOBS is how many cases run at once; it defaults to the number of + CPUs, and 1 runs every case and compares it before starting the next. EOF } @@ -149,12 +152,60 @@ cd "$PROJECT_ROOT" mkdir -p "$PROJECT_ROOT/src" safe_name() { - printf '%s' "$1" | tr '/ ' '__' | tr -c 'A-Za-z0-9_.-' '_' + printf '%s' "${1//[^A-Za-z0-9_.-]/_}" +} + +# Set variable $1 to the safe name of $2, without a subshell: the case loops +# call this a few thousand times. +set_safe_name() { + printf -v "$1" '%s' "${2//[^A-Za-z0-9_.-]/_}" +} + +# With PARITY_JOBS above 1 the cases run in two phases. In the `collect` +# phase the case loops queue each case's OCaml and Rust commands as one task +# instead of running them; the tasks then run PARITY_JOBS at a time, each +# case's two commands one after the other as before. In the `compare` phase +# the same loops compare the captured outputs in order, and a command whose +# output was not captured runs then. Packages and interfaces a case needs are +# still prepared serially, in the collect phase, before any task runs. +PHASE=direct +TASK_FILE="" +pending_task="" + +# Queue command $2... (capturing into $1 the way run_capture does when $0 is +# `out`, or as run_capture_stderr when it is `err`) for the current case. +queue_capture() { + local mode="$1" output="$2" + shift 2 + local command redirect status_file + printf -v command '%q ' timeout "$TIMEOUT_SECONDS" "$@" + if [[ "$mode" == "out" ]]; then + printf -v redirect '> %q 2>&1' "$output" + else + printf -v redirect '> %q 2> %q' "$output.stdout" "$output" + fi + printf -v status_file '%q' "$output.status" + pending_task+="$command$redirect; printf '%s\\n' \$? > $status_file; " +} + +# End the current case's task in the collect phase. +flush_task() { + if [[ -n "$pending_task" ]]; then + printf '%s\0' "$pending_task" >> "$TASK_FILE" + pending_task="" + fi } run_capture() { local output="$1" shift + if [[ "$PHASE" == "collect" ]]; then + queue_capture out "$output" "$@" + return 0 + fi + if [[ "$PHASE" == "compare" && -f "$output.status" ]]; then + return 0 + fi local status=0 if timeout "$TIMEOUT_SECONDS" "$@" > "$output" 2>&1; then status=0 @@ -167,6 +218,13 @@ run_capture() { run_capture_stderr() { local output="$1" shift + if [[ "$PHASE" == "collect" ]]; then + queue_capture err "$output" "$@" + return 0 + fi + if [[ "$PHASE" == "compare" && -f "$output.status" ]]; then + return 0 + fi local status=0 if timeout "$TIMEOUT_SECONDS" "$@" > "$output.stdout" 2> "$output"; then status=0 @@ -200,8 +258,12 @@ compare_outputs() { local rust_out="$4" local diff_out="$5" local ocaml_status rust_status - ocaml_status=$(cat "$ocaml_out.status") - rust_status=$(cat "$rust_out.status") + if [[ "$PHASE" == "collect" ]]; then + flush_task + return 0 + fi + read -r ocaml_status < "$ocaml_out.status" || true + read -r rust_status < "$rust_out.status" || true total=$((total + 1)) if [[ "$VERBOSE" == "true" ]]; then @@ -290,7 +352,7 @@ run_parser_cases() { fi local safe ocaml_out rust_out diff_out - safe=$(safe_name "parser_${number}_${source_file}") + set_safe_name safe "parser_${number}_${source_file}" ocaml_out="$CACHE_DIR/parser/ocaml_${safe}.out" rust_out="$CACHE_DIR/parser/rust_${safe}.out" diff_out="$CACHE_DIR/diffs/${safe}.diff" @@ -368,13 +430,14 @@ run_compiler_case() { shift local flags=("$@") local safe ocaml_out rust_out diff_out - safe=$(safe_name "compiler_${source_file}") + set_safe_name safe "compiler_${source_file}" ocaml_out="$CACHE_DIR/compiler/ocaml_${safe}.out" rust_out="$CACHE_DIR/compiler/rust_${safe}.out" diff_out="$CACHE_DIR/diffs/${safe}.diff" prebuild_ocaml_packages "${flags[@]}" || return 1 - if [[ "$source_file" == .parity-cache/error-output/compiler/* ]]; then + if [[ "$source_file" == .parity-cache/error-output/compiler/* && + ! ( "$PHASE" == "compare" && -f "$ocaml_out.status" ) ]]; then prepare_cached_case "$source_file" "${flags[@]}" || return 1 fi run_capture_stderr "$ocaml_out" "$OCAML_BSC" "${flags[@]}" "$source_file" @@ -430,6 +493,26 @@ run_compiler_cases() { fi } +# Run the queued commands of the parser and compiler cases. The JSX warning +# cases are few and check statuses inline, so they always run directly. +if [[ "$PARITY_JOBS" -gt 1 ]]; then + TASK_FILE="$CACHE_DIR/tasks" + : > "$TASK_FILE" + PHASE=collect + if [[ "$RUN_PARSER" == "true" ]]; then + run_parser_cases > /dev/null || true + fi + if [[ "$RUN_COMPILER" == "true" ]]; then + run_compiler_cases > /dev/null || true + fi + flush_task + if [[ -s "$TASK_FILE" ]]; then + xargs -0 -n 1 -P "$PARITY_JOBS" bash -c < "$TASK_FILE" || true + fi + rm -f "$TASK_FILE" + PHASE=compare +fi + if [[ "$RUN_PARSER" == "true" ]]; then run_parser_cases || true run_jsx_parser_warning_cases || true diff --git a/scripts/test_error_output_parity_exit.py b/scripts/test_error_output_parity_exit.py index 625033f652..24a26dcb49 100644 --- a/scripts/test_error_output_parity_exit.py +++ b/scripts/test_error_output_parity_exit.py @@ -1,4 +1,5 @@ -"""Test the exit-status guard of the res_parser JSX warning stage. +"""Test the exit-status guard of the res_parser JSX warning stage, and that +the compiler cases report the same results run one at a time or in parallel. Runs the real test_error_output_parity.sh (`--parser-only`, limited to the JSX warning fixtures) with fake OCaml and Rust parsers. The fakes print the @@ -80,5 +81,56 @@ def test_shared_error_status_fails_a_valid_fixture(self): self.assertIn(f"OCaml {status}, Rust {status}, expected 0", output) +# `bsc flags... file`: prints a diagnostic naming the file. The Rust side +# (FAKE_SIDE=rust) prints a different one for files containing FAKE_DIFFER and +# exits 124, like a timeout, for files containing FAKE_TIMEOUT. +FAKE_BSC = r''' +import os, sys +path = sys.argv[-1] +side = os.environ["FAKE_SIDE"] +if side == "rust" and os.environ["FAKE_TIMEOUT"] in path: + sys.exit(124) +text = "rust" if side == "rust" and os.environ["FAKE_DIFFER"] in path else "same" +sys.stderr.write(f"\\n {text} diagnostic\\n {path}:1:1\\n\\n") +sys.exit(1) +''' + + +class ParallelCompilerCaseTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = tempfile.TemporaryDirectory() + root = Path(cls.dir.name) + (root / "fake_bsc.py").write_text(FAKE_BSC) + for side in ("ocaml", "rust"): + exe = root / f"{side}_bsc" + exe.write_text(f'#!/bin/sh\nFAKE_SIDE={side} exec python3 -I "{root}/fake_bsc.py" "$@"\n') + exe.chmod(0o755) + cls.root = root + + @classmethod + def tearDownClass(cls): + cls.dir.cleanup() + + def run_cases(self, jobs): + env = dict(os.environ, OCAML_BSC=str(self.root / "ocaml_bsc"), + RUST_BSC=str(self.root / "rust_bsc"), RUST_TARGET="none", + PARITY_JOBS=str(jobs), FAKE_DIFFER="jsx_warning_then_error", + FAKE_TIMEOUT="jsx_error_then_warning") + result = subprocess.run(["bash", str(SCRIPT), "--compiler-only", "fixtures/jsx_"], + env=env, capture_output=True, text=True, timeout=120) + output = (result.stdout + result.stderr).replace("\x1b", "") + summary = output[output.index("Error output parity summary"):] + summary = "\n".join(line for line in summary.splitlines() if "cache:" not in line) + return result.returncode, summary + + def test_parallel_cases_report_what_serial_cases_report(self): + serial = self.run_cases(1) + self.assertEqual(serial[0], 1, serial[1]) + self.assertIn("jsx_warning_then_error.res (output differs)", serial[1]) + self.assertIn("jsx_error_then_warning.res (exit status differs)", serial[1]) + self.assertEqual(self.run_cases(4), serial) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/test_gentype_output_parity.sh b/scripts/test_gentype_output_parity.sh index efb0c8c84a..2997184489 100755 --- a/scripts/test_gentype_output_parity.sh +++ b/scripts/test_gentype_output_parity.sh @@ -7,6 +7,9 @@ # .gen.ts/.gen.tsx files that correspond to local .res/.resi source artifacts # from the OCaml compiler against the Rust in-process compiler. Do not add # normalization or repo-selection options here. +# +# The one exception is GENTYPE_PARITY_WITHOUT_TELLA=1, for CI, which has no +# Tella checkout: it runs the in-repo suites only and says so in the summary. set -uo pipefail @@ -28,6 +31,7 @@ REWATCH_BIN="${REWATCH_BIN:-$PROJECT_ROOT/rewatch/target/$REWATCH_TARGET/rescrip RESCRIPT_CLI="${RESCRIPT_CLI:-$PROJECT_ROOT/packages/@rescript/$("$script_dir/platform.sh")/bin/rescript.exe}" RESCRIPT_RUNTIME="${RESCRIPT_RUNTIME:-$PROJECT_ROOT/packages/@rescript/runtime}" TELLA_DIR="${TELLA_DIR:-$HOME/dev/tella-fusion}" +WITHOUT_TELLA="${GENTYPE_PARITY_WITHOUT_TELLA:-}" CACHE_DIR="$PROJECT_ROOT/.parity-cache/gentype-output" export RESCRIPT_RUNTIME @@ -73,7 +77,7 @@ check_prerequisites() { missing=true fi - if [[ ! -d "$TELLA_DIR" ]]; then + if [[ "$WITHOUT_TELLA" != "1" && ! -d "$TELLA_DIR" ]]; then echo -e "${RED}Error: Tella checkout not found at $TELLA_DIR${RESET}" >&2 echo "This script always includes Tella; set TELLA_DIR to the local checkout before running." >&2 missing=true @@ -599,7 +603,11 @@ echo "Cache: $CACHE_DIR" run_suite "typescript-react-example" "$PROJECT_ROOT/tests/gentype_tests/typescript-react-example" run_suite "stdlib-no-shims" "$PROJECT_ROOT/tests/gentype_tests/stdlib-no-shims" -run_suite "tella" "$TELLA_DIR" +if [[ "$WITHOUT_TELLA" == "1" ]]; then + echo -e "${YELLOW}Skipping the Tella suite (GENTYPE_PARITY_WITHOUT_TELLA=1)${RESET}" +else + run_suite "tella" "$TELLA_DIR" +fi echo "" echo -e "${BOLD}GenType parity summary${RESET}"