Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/Lean/Mathlib/.github/workflows/     Datei vom 15.10.2026 mit Größe 71 kB image not shown  

SSL build_template.yml  Interaktion und
Portierbarkeitunbekannt

 
Spracherkennung für: .yml vermutete Sprache: SQL {SQL[37] Fortran[36] VDM[30]} [Methode: maximale Elemente, drei Dimensionen]

# Reusable workflow invoked by build.yml, bors.yml, build_fork.yml, ci_dev.yml,
# and release_cache.yml.

on:
  workflow_call:
    inputs:
      concurrency_group:
        type: string
        required: true
      tools_branch_ref:
        type: string
        required: false
        default: ''
      pr_branch_ref:
        type: string
        required: true
      run_post_ci:
        type: boolean
        required: false
        default: true
      runs_on:
        type: string
        required: true
      cache_environment:
        # GitHub environment for the `upload_cache` and `upload_test_cache` jobs. Its only
        # role is to fix the OIDC `sub` claim to `...:environment:<name>`, which the cache
        # writer credentials are scoped to.
        type: string
        required: true
      publish_cache:
        # On a successful build, publish this run's `.ltar` set as `cache-snapshot`.
        # Set by callers ONLY for the master-`push` build — the single producer.
        type: boolean
        required: false
        default: false

env:
  # Disable Lake'
s automatic fetching of cloud builds.
  # Lake's cache is currently incompatible with Mathlib's `lake exe cache`.
  # This is because Mathlib's Cache assumes all build artifacts present in the build directory
  # are valid by-products of the Mathlib build. Build artifacts fetched from Lake'
s cache do
  # not necessarily satisfy this property.
  LAKE_NO_CACHE: true
  MATHLIB_CACHE_BASE_URL: ${{ vars.MATHLIB_CACHE_BASE_URL }}
  MATHLIB_CACHE_PARALLEL_MAX: ${{ vars.MATHLIB_CACHE_PARALLEL_MAX }}

jobs:
  build:
    name: Build
    runs-on: ${{ inputs.runs_on }}
    # This job builds (potentially fork) PR code, so it must not inherit any
    # write-capable token. `actions: read` lets get-tools and get-cache download
    # artifacts from master's runs.
    permissions:
      contents: read
      actions: read
    outputs:
      build-outcome: ${{ steps.build.outcome }}
      archive-outcome: ${{ steps.archive.outcome }}
      counterexamples-outcome: ${{ steps.counterexamples.outcome }}
      wanted-outcome: ${{ steps.wanted.outcome }}
      cache-staging-has-files: ${{ steps.cache_staging_check.outputs.has_files }}
      mk_all-outcome: ${{ steps.mk_all.outcome }}
      noisy-outcome: ${{ steps.noisy.outcome }}
      # shake-outcome: ${{ steps.shake.outcome }}
    # PR code can write `pr-branch/.lake/` from setup-build-env'
s "download dependencies"
    # step onward, so later steps that use it run inside landrun. The one exception is
    # "prune local cache to this commit's set", which runs only on a trusted checkout.
    defaults: # The self-hosted runner image provides landrun.
      run: # setup-build-env creates the paths below that the runner image can lack.
        shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rox /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI -- bash -euxo pipefail {0}
    steps:
      - name: job info
        env:
          WORKFLOW: ${{ github.workflow }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          REF: ${{ github.ref }}
          EVENT_NAME: ${{ github.event_name }}
          RUN_ID: ${{ github.run_id }}
          CONCURRENCY_GROUP: ${{ inputs.concurrency_group }}
        shell: bash # there is no script body, so this is safe to "run" outside landrun.
        run: |
          # We just populate the env vars for this step to make them viewable in the logs

      - name: Checkout local actions
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.workflow_sha }}
          fetch-depth: 1
          sparse-checkout: .github/actions
          path: workflow-actions
          persist-credentials: false # no later step needs git credentials

      # Validate lake-manifest.json before setup downloads dependencies.
      # Check that dependencies use allowed repositories and references, with full commit hashes.
      # Check pins against their branch or tag, and detect accidental dependency downgrades.
      # Full rules:
      # https://github.com/leanprover-community/mathlib-ci/blob/master/.github/actions/validate-lake-manifest/README.md
      # Bors uses strict mode; other runs can test unmerged dependencies with warnings.
      # For an intentional revert, an admin sets MATHLIB_ALLOW_OLDER_DEPENDENCY_PINS to true
      # and deletes the variable after the revert merges.
      - name: Validate lake-manifest.json
        # Skip `bump/*` branches and PRs that target them, because their dependencies track `nightly-testing`.
        # For PRs, use `github.base_ref`: `pull_request_target` sets `github.ref_name` to the default branch.
        # Bors batches still run the check on `staging`.
        if: >-
          github.repository == 'leanprover-community/mathlib4'
          && !startsWith(github.ref_name, 'bump/')
          && !startsWith(github.base_ref, 'bump/')
        uses: leanprover-community/mathlib-ci/.github/actions/validate-lake-manifest@e08feb664fe178b59a3fff5de1aa9893535b8a6c
        with:
          ref: ${{ inputs.pr_branch_ref }}
          strict: ${{ github.ref_name == 'staging' || github.ref_name == 'trying' }}
          allow-older-pins: ${{ vars.MATHLIB_ALLOW_OLDER_DEPENDENCY_PINS == 'true' }}

      # Shared self-hosted setup (cache-trust dispatch,
      # PR-branch checkout, elan + toolchain/LEAN_SRC_PATH env, CI tools, dependency
      # download); see the action for per-step rationale. It is loaded from the
      # `Checkout local actions` checkout above, which therefore runs first.
      - name: Set up build environment
        uses: ./workflow-actions/.github/actions/setup-build-env
        with:
          pr_branch_ref: ${{ inputs.pr_branch_ref }}
          tools_branch_ref: ${{ inputs.tools_branch_ref }}

      # TEMPORARY: remove once active branches have merged #43308.
      # CI uploads `forks` artifacts to R2 alone. A cache tool from before #43308
      # reads `forks` directly from Azure, so `lake exe cache get` on the
      # contributor's machine misses the artifacts this run builds for the branch.
      # Hard-fail here (same style as the `lake lint` predates-config gate below in 'lint mathlib')
      # and tell the author to merge master, which brings in a current cache tool.
      # The marker is `Cache/Env.lean`, a module that #43308 added.
      #
      # TODO: Remove this check eventually. Note that there is no 'correctness' issue if we don't check this:
      #       it's just that locally, the user will not get the artifacts this run has produced (also meaning the upload is 'waste').
      - name: check the cache tool is recent
        # Canonical repo only. This nudge targets human fork-PR / dev-branch
        # contributors who run `lake exe cache get` locally. The nightly-testing
        # repo's `batteries-pr-testing-*` branches are machine-managed, so
        # "merge master and push" is the wrong remedy there.
        if: github.repository == 'leanprover-community/mathlib4'
        shell: bash
        run: |
          if [ ! -f pr-branch/Cache/Env.lean ]; then
            echo "::error title=Outdated cache tool::Your branch's cache tool is outdated; merge master so 'lake exe cache get' can read your branch's artifacts."
            echo ""
            echo "=============================================================================="
            echo "ERROR: Your branch's 'lake exe cache' tool is outdated."
            echo "It reads from storage that CI does not write for your branch, so it will miss"
            echo "the artifacts CI builds for your branch and rebuild them locally instead."
            echo "Please merge 'master' into your PR branch and push again."
            echo ""
            echo "You can do this with:"
            echo "  git fetch upstream"
            echo "  git merge upstream/master"
            echo "  git push"
            echo "=============================================================================="
            echo ""
            exit 1
          fi

      # Get this commit's oleans into the local cache — see the action for the steps.
      - name: Get cache
        uses: ./workflow-actions/.github/actions/get-cache
        with:
          working_directory: pr-branch
          cache_bin: ../tools-branch/.lake/build/bin/cache

      - name: update {Mathlib, Tactic, Counterexamples, Archive}.lean
        id: mk_all
        continue-on-error: true # Allow workflow to continue, outcome checked later
        # This runs `mk_all --check` from the `pr-branch` inside landrun
        run: |
          cd pr-branch
          echo "Running mk_all --check (from pr-branch)..."
          lake exe mk_all --check

      - name: begin gh-problem-match-wrap for build step
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: add # In order to be able to run a multiline script, we need to add/remove the problem matcher before and after.
          linters: lean
      - name: build mathlib
        id: build
        run: |
          cd pr-branch
          echo "::group::{test curl}"
          # Test curl - should fail when landrun network isolation is working
          if curl --silent --head --fail https://www.example.com/ >/dev/null 2>&1; then
            echo "ERROR: curl to example.com succeeded, but it should fail when landrun is working correctly!"
            exit 1
          else
            echo "curl to example.com failed as expected - landrun network isolation is working"
          fi
          echo "::endgroup::"

          ../tools-branch/scripts/lake-build-with-retry.sh Mathlib
          # results of build at pr-branch/.lake/build_summary_Mathlib.json
      - name: end gh-problem-match-wrap for build step
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: remove
          linters: lean

      - name: print the sizes of the oleans
        run: |
          cd pr-branch
          du .lake/build/lib/lean/Mathlib || echo "This code should be unreachable"

      # Note: we should not be including `Archive` and `Counterexamples` in the cache.
      # We do this for now for the sake of not rebuilding them in every CI run
      # even when they are not touched.
      # Since `Archive` and `Counterexamples` files have very simple dependencies,
      # it should be possible to determine whether they need to be built without actually
      # storing and transferring oleans over the network.
      # Hopefully a future re-implementation of `cache` will obviate the present need for this hack.

      - name: fetch archive, counterexamples and wanted cache
        # Same sandbox as "Fetch cache from remote" in get-cache.
        shell: landrun --unrestricted-network --rox /usr --rox /etc --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rwx /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --env PATH --env HOME --env CI --env TERM --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX --env MATHLIB_CACHE_FROM --env MATHLIB_CACHE_REPO_SCOPE --env MATHLIB_CACHE_GET_URL --env MATHLIB_CACHE_BASE_URL --env MATHLIB_CACHE_PARALLEL_MAX -- bash -euxo pipefail {0}
        run: |
          # Use the trusted toolchain's `lean`/`leantar` (see setup-build-env).
          export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
          cd pr-branch
          ../tools-branch/.lake/build/bin/cache get Archive.lean
          ../tools-branch/.lake/build/bin/cache get Counterexamples.lean
          ../tools-branch/.lake/build/bin/cache get Wanted.lean

      - name: prepare staging directory
        if: ${{ always() && (steps.build.outcome == 'success' || steps.build.outcome == 'failure' || steps.build.outcome == 'cancelled') }}
        shell: bash
        run: |
          # Clean the staging directory first, though it should be empty at this point, to be safe
          rm -rf cache-staging
          mkdir -p cache-staging
          # Mark the start of the staging: see "stage Mathlib cache files after a cancellation".
          touch "${{ runner.temp }}/staging-start"

      # The library build and the Mathlib staging are independent: `lake build`
      # writes only the three library targets, and `cache stage` reads
      # `.lake/build/lib/lean/Mathlib` and writes `cache-staging/`.
      - parallel:
          # One `lake build` builds the three libraries, so their modules share
          # one scheduler, and Lake keeps building the other targets when one
          # fails.
          - name: build archive, counterexamples and wanted
            id: libraries
            continue-on-error: true
            run: |
              cd pr-branch
              ../tools-branch/scripts/lake-build-with-retry.sh Archive Counterexamples Wanted
              # results of build at pr-branch/.lake/build_summary_Archive_Counterexamples_Wanted.json

          - name: stage Mathlib cache files
            if: ${{ always() && (steps.build.outcome == 'success' || steps.build.outcome == 'failure' || steps.build.outcome == 'cancelled') }}
            shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
            run: |
              # Run `cache` directly, as the get/clean steps do, rather than via `lake env`:
              # it reads its context from LEAN_SRC_PATH (forwarded above), and no PR code
              # runs with write access to `cache-staging/`. Use the trusted toolchain's
              # `lean`/`leantar` (see setup-build-env).
              export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
              cd pr-branch
              ../tools-branch/.lake/build/bin/cache --staging-dir="../cache-staging" stage

      # A cancelled run does not start the members of a parallel group,
      # including the members with `always()`, and the runner reports the
      # outcome `success` for a member that it did not start. Thus this step
      # stages the Mathlib cache files of every cancelled run, so the next run
      # can use the modules that this run built. `cache stage` copies only the
      # `.ltar` files that it packs in the same call. Thus the step first
      # deletes the `.ltar` files that "stage Mathlib cache files" packed,
      # which are the files newer than the mark of "prepare staging
      # directory", and `cache stage` packs them again. `cp` overwrites the
      # staged files, so the step can follow a complete or an interrupted
      # staging.
      - name: stage Mathlib cache files after a cancellation
        if: ${{ cancelled() && (steps.build.outcome == 'success' || steps.build.outcome == 'failure' || steps.build.outcome == 'cancelled') }}
        shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
        run: |
          # No `lake env`, trusted toolchain: see "stage Mathlib cache files".
          export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
          find "$HOME/.cache/mathlib" -maxdepth 1 -name '*.ltar' -newer "${{ runner.temp }}/staging-start" -delete
          cd pr-branch
          ../tools-branch/.lake/build/bin/cache --staging-dir="../cache-staging" stage

      # The three checks ask Lake whether each target is up to date and free
      # of warnings, so each target reports its own outcome to the staging
      # gates, the test gate and the Batteries PR comment. They only read.
      - parallel:
          - name: check that Archive built
            id: archive
            continue-on-error: true
            run: |
              cd pr-branch
              lake build --no-build --wfail Archive

          - name: check that Counterexamples built
            id: counterexamples
            continue-on-error: true
            run: |
              cd pr-branch
              lake build --no-build --wfail Counterexamples

          - name: check that Wanted built
            id: wanted
            continue-on-error: true
            run: |
              cd pr-branch
              lake build --no-build --wfail Wanted

      # The noisy-output replay only reads; the three stagings write
      # disjoint files under `cache-staging/`.
      - parallel:
          # Runs in the build job because it only needs the freshly-built Mathlib/
          # Archive/Counterexamples/Wanted oleans, which are present here; keeping it in
          # `build` also spares `test_lint` from fetching Archive/Counterexamples.
          - name: check for noisy stdout lines
            id: noisy
            run: |
              cd pr-branch
              ## `lake` replays the saved output of every module, and `--iofail`
              ## fails the step if any module logged anything.
              lake build --no-build -q --iofail Mathlib Archive Counterexamples Wanted

          - name: stage Archive cache files
            if: ${{ steps.archive.outcome == 'success' }}
            shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
            run: |
              # No `lake env`, trusted toolchain: see "stage Mathlib cache files".
              export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
              cd pr-branch
              ../tools-branch/.lake/build/bin/cache --staging-dir="../cache-staging" stage Archive.lean

          - name: stage Counterexamples cache files
            if: ${{ steps.counterexamples.outcome == 'success' }}
            shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
            run: |
              # No `lake env`, trusted toolchain: see "stage Mathlib cache files".
              export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
              cd pr-branch
              ../tools-branch/.lake/build/bin/cache --staging-dir="../cache-staging" stage Counterexamples.lean

          - name: stage Wanted cache files
            if: ${{ steps.wanted.outcome == 'success' }}
            shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
            run: |
              # No `lake env`, trusted toolchain: see "stage Mathlib cache files".
              export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
              cd pr-branch
              ../tools-branch/.lake/build/bin/cache --staging-dir="../cache-staging" stage Wanted.lean

      - name: check cache staging contents
        id: cache_staging_check
        if: ${{ always() && (steps.build.outcome == 'success' || steps.build.outcome == 'failure' || steps.build.outcome == 'cancelled') }}
        shell: bash
        run: |
          # The staging directory is uploaded as-is, so it must hold only regular files.
          # Only the stage steps can write to it, and they run no PR code, so nothing
          # can change it between this check and the upload.
          other=$(find cache-staging -mindepth 1 ! -type f ! -type d)
          if [ -n "${other}" ]; then
            echo "::error::cache-staging contains entries that are not regular files:"
            echo "${other}"
            exit 1
          fi
          if find cache-staging -type f -name '*.ltar' -print -quit | grep -q .; then
            echo "has_files=true" >> "$GITHUB_OUTPUT"
          else
            echo "has_files=false" >> "$GITHUB_OUTPUT"
          fi

      - name: upload cache staging artifact
        if: ${{ always() && steps.cache_staging_check.outputs.has_files == 'true' }}
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: cache-staging
          path: cache-staging/
          # The `.ltar` files are already zstd-compressed; recompressing wastes CPU.
          compression-level: 0

      # Prune to this commit's `.ltar` set so the published snapshot is exactly master's
      # current cache. The local directory can also hold other `.ltar` files, such as
      # the snapshot this run warmed from or files that the runner image provides.
      - name: prune local cache to this commit's set
        if: ${{ inputs.publish_cache && steps.build.outcome == 'success' }}
        continue-on-error: true # best-effort; never fail the build
        shell: bash # only master pushes publish the cache, so the checkout is trusted
        run: |
          # Use the trusted toolchain's `lean`/`leantar` (see setup-build-env).
          export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
          cd pr-branch
          ../tools-branch/.lake/build/bin/cache clean

      # Publish this run's pruned `.ltar` set as `cache-snapshot` for other runs to warm
      # from. The files are already zstd-compressed, so the upload skips compression.
      # The retention covers how far back a PR's merge-base can be matched.
      - name: upload cache snapshot warming artifact
        if: ${{ inputs.publish_cache && steps.build.outcome == 'success' }}
        continue-on-error: true # best-effort; never fail the build
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: cache-snapshot
          path: /home/lean/.cache/mathlib/*.ltar
          compression-level: 0
          retention-days: 14
          if-no-files-found: warn

      - name: Check if building Archive or Counterexamples failed
        if: steps.archive.outcome == 'failure' || steps.counterexamples.outcome == 'failure'
        run: |
          if [ "${{ steps.archive.outcome }}" == "failure" ]; then
            echo "❌ Archive did not build; check the logs of the \"build archive, counterexamples and wanted\" step above."
          fi
          if [ "${{ steps.counterexamples.outcome }}" == "failure" ]; then
            echo "❌ Counterexamples did not build; check the logs of the \"build archive, counterexamples and wanted\" step above."
          fi
          exit 1

      - name: Check {Mathlib, Tactic, Counterexamples, Archive}.lean
        if: ${{ always() && steps.mk_all.outcome != 'skipped' }}
        run: |
          if [[ "${{ steps.mk_all.outcome }}" != "success" ]]; then
            echo "Please run 'lake exe mk_all' to regenerate the import all files"
            exit 1
          else
            echo "'mk_all --check' passed successfully."
          fi

  test_lint:
    name: Test and lint
    needs: [build]
    # Runs `test` and `lint` on the same self-hosted pool as `build`, but as a
    # separate job so it runs in parallel with the GitHub-hosted post-build chain
    # (upload_cache -> post_steps) rather than ahead of it. `build` and `test_lint`
    # run sequentially on the pool, so peak per-run concurrency is unchanged; the
    # only cost is a second setup prefix on a fresh runner.
    #
    # It does not depend on `upload_cache`: it reconstitutes this run's oleans
    # from the `cache-staging` artifact `build` produces (this commit's
    # freshly-built delta) and warms the rest from the master `cache-snapshot`
    # via the `get-cache` action. The `verify the Mathlib cache is complete`
    # step below fails loudly if that reconstitution is incomplete,
    # rather than silently rebuilding under landrun (which has no network).
    #
    # Gating: runs when `build` succeeded or failed (not cancelled/skipped). Running
    # on build FAILURE too means `lint` still reports results on a failed build,
    # best-effort over whatever oleans were built. The per-step conditions below
    # match: `test` only on a clean build, `lint` on success-or-failure.
    if: ${{ always() && (needs.build.result == 'success' || needs.build.result == 'failure') }}
    runs-on: ${{ inputs.runs_on }}
    # Same as `build`: this job runs (potentially fork) PR code, so it must not
    # inherit any write-capable token.
    permissions:
      contents: read
      actions: read
    outputs:
      lint-outcome: ${{ steps.lint.outcome }}
      test-outcome: ${{ steps.test.outcome }}
      test-cache-staging-has-files: ${{ steps.test_cache_staging.outputs.has_files }}
    # `RUN_TESTS` is true on a clean build: `build` itself, the `mk_all` check, and
    # the archive, counterexamples, and Wanted builds all succeeded. It reads these
    # from the outputs of `build`. It gates `test`, the problem-matcher wrap of
    # `test`, and the MathlibTest cache fetch.
    env:
      RUN_TESTS: ${{ needs.build.outputs.build-outcome == 'success' && needs.build.outputs.mk_all-outcome == 'success' && needs.build.outputs.archive-outcome == 'success' && needs.build.outputs.counterexamples-outcome == 'success' &n>& needs.build.outputs.wanted-outcome == 'success' }}
    defaults: # The self-hosted runner image provides landrun.
      run: # setup-build-env creates the paths below that the runner image can lack.
        shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rox /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI -- bash -euxo pipefail {0}
    steps:
      - name: Checkout local actions
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.workflow_sha }}
          fetch-depth: 1
          sparse-checkout: .github/actions
          path: workflow-actions
          persist-credentials: false # no later step needs git credentials

      # Shared self-hosted setup (see the action).
      - name: Set up build environment
        uses: ./workflow-actions/.github/actions/setup-build-env
        with:
          pr_branch_ref: ${{ inputs.pr_branch_ref }}
          tools_branch_ref: ${{ inputs.tools_branch_ref }}

      # Pre-populate the local cache with this commit's freshly-built delta: the
      # `cache-staging` artifact `build` produces holds its newly-built `.ltar` —
      # the oleans not already in the master snapshot. `get-cache` below then warms
      # the unchanged bulk from the master `cache-snapshot` and unpacks everything.
      # Gated on `cache-staging-has-files`: a full cache hit stages nothing (no
      # artifact is uploaded), and `get-cache` alone then covers the commit.
      - name: download cache staging artifact
        if: ${{ needs.build.outputs.cache-staging-has-files == 'true' }}
        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          name: cache-staging
          path: /home/lean/.cache/mathlib

      # Warm the unchanged bulk from the master `cache-snapshot` and fetch/unpack
      # this commit's oleans. The staged `.ltar` placed above are already local, so
      # `get-cache`'s `cache get` decompresses them and downloads only the missing
      # files.
      - name: Get cache
        uses: ./workflow-actions/.github/actions/get-cache
        with:
          working_directory: pr-branch
          cache_bin: ../tools-branch/.lake/build/bin/cache

      - name: verify the Mathlib cache is complete
        # Enforced only when the build succeeded (then the cache must be complete):
        # fail fast rather than silently trying to rebuild under landrun (which has
        # no network). On a failed build the cache is expected to be partial, so this
        # is skipped and `lint` runs best-effort below.
        if: ${{ needs.build.outputs.build-outcome == 'success' }}
        # TODO: remove if there are no issues
        continue-on-error: true
        run: |
          cd pr-branch
          lake build --no-build --rehash -v Mathlib

      # Fetch the `MathlibTest` oleans that the cache holds. `test` rebuilds only the
      # test files that the cache does not hold.
      - name: get the MathlibTest cache
        if: ${{ env.RUN_TESTS == 'true' }}
        continue-on-error: true
        # Same sandbox as "Fetch cache from remote" in get-cache.
        shell: landrun --unrestricted-network --rox /usr --rox /etc --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rwx /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --env PATH --env HOME --env CI --env TERM --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX --env MATHLIB_CACHE_FROM --env MATHLIB_CACHE_REPO_SCOPE --env MATHLIB_CACHE_GET_URL --env MATHLIB_CACHE_BASE_URL --env MATHLIB_CACHE_PARALLEL_MAX --env CACHE_REPO -- bash -euxo pipefail {0}
        env:
          CACHE_REPO: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
        run: |
          # Use the trusted toolchain's `lean`/`leantar` (see setup-build-env).
          export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
          cd pr-branch
          ../tools-branch/.lake/build/bin/cache --repo="${CACHE_REPO}" get 'MathlibTest.+'

      - name: begin gh-problem-match-wrap for test step
        if: ${{ env.RUN_TESTS == 'true' }}
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: add # In order to be able to run a multiline script, we need to add/remove the problem matcher before and after.
          linters: lean
      - name: test mathlib
        if: ${{ env.RUN_TESTS == 'true' }}
        id: test
        run: |
          cd pr-branch
          ../tools-branch/scripts/lake-build-wrapper.py .lake/build_summary_MathlibTest.json lake --iofail test
      - name: end gh-problem-match-wrap for test step
        if: ${{ env.RUN_TESTS == 'true' }}
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: remove
          linters: lean

      # For `upload_test_cache`, stage the `MathlibTest` oleans that `test` built. Only
      # runs that write the `master` container stage them. A test file that fails leaves
      # no build output, so `stage` skips it. `test` ran the PR's code with write access
      # to `pr-branch/.lake/`, so `stage` runs in landrun.
      - name: prepare the MathlibTest staging directory
        id: test_cache_prepare
        if: ${{ always() && env.MATHLIB_CACHE_PRIMARY == 'master' && (steps.test.outcome == 'success' || steps.test.outcome == 'failure') }}
        continue-on-error: true
        shell: bash
        run: |
          rm -rf test-cache-staging
          mkdir -p test-cache-staging

      - name: stage MathlibTest cache files
        id: test_cache_stage
        if: ${{ always() && steps.test_cache_prepare.outcome == 'success' }}
        continue-on-error: true
        shell: landrun --rox /usr --ro /etc/timezone --rw /dev --rox /home/lean/.elan --rox /home/lean/actions-runner/_work --rw /home/lean/.cache/mathlib/ --rw pr-branch/.lake/ --rw test-cache-staging/ --env PATH --env HOME --env GITHUB_OUTPUT --env CI --env LEAN_SRC_PATH --env TRUSTED_LEAN_PREFIX -- bash -euxo pipefail {0}
        run: |
          # No `lake env`, trusted toolchain: see "stage Mathlib cache files".
          export PATH="${TRUSTED_LEAN_PREFIX:?trusted toolchain sysroot not set}/bin:${PATH}"
          cd pr-branch
          ../tools-branch/.lake/build/bin/cache --staging-dir="../test-cache-staging" stage 'MathlibTest.+'

      - name: check MathlibTest cache staging contents
        id: test_cache_staging
        if: ${{ always() && steps.test_cache_stage.outcome == 'success' }}
        shell: bash
        run: |
          # The staging directory is uploaded as-is, so it must hold only regular files.
          other=$(find test-cache-staging -mindepth 1 ! -type f ! -type d)
          if [ -n "${other}" ]; then
            echo "::error::test-cache-staging contains entries that are not regular files:"
            echo "${other}"
            exit 1
          fi
          if find test-cache-staging -type f -name '*.ltar' -print -quit | grep -q .; then
            echo "has_files=true" >> "$GITHUB_OUTPUT"
          fi

      - name: upload MathlibTest cache staging artifact
        if: ${{ always() && steps.test_cache_staging.outputs.has_files == 'true' }}
        continue-on-error: true
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: cache-staging-test
          path: test-cache-staging/
          # The `.ltar` files are already zstd-compressed; recompressing wastes CPU.
          compression-level: 0

      # `lint` runs on a build that succeeded or failed (not cancelled). On a failed
      # build it lints best-effort over whatever oleans the cache has, so partial
      # lint feedback is still reported. The problem-matcher wrap is gated to match.
      - name: begin gh-problem-match-wrap for shake and lint steps
        if: ${{ always() && (needs.build.outputs.build-outcome == 'success' || needs.build.outputs.build-outcome == 'failure') }}
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: add # In order to be able to run a multiline script, we need to add/remove the problem matcher before and after.
          linters: gcc

      # With the arrival of the module system, the old `shake` is no longer functional.
      # This will be replaced soon.
      # - name: check for unused imports
      #   id: shake
      #   run: |
      #     cd pr-branch
      #     env LEAN_ABORT_ON_PANIC=1 lake exe shake --gh-style
      - name: lint mathlib
        if: ${{ always() && (needs.build.outputs.build-outcome == 'success' || needs.build.outputs.build-outcome == 'failure') }}
        id: lint
        timeout-minutes: 40
        run: |
          cd pr-branch
          set -o pipefail
          # If lint fails because the PR predates lake-lint configuration or the
          # old --trace argument-parsing behavior, ask the author to merge master.
          # We use .lake/ for the output file because landrun restricts /tmp access
          for attempt in 1 2; do
            if timeout 10m env LEAN_ABORT_ON_PANIC=1 stdbuf -oL lake lint -- --trace 2>&1 | tee ".lake/lint_output_attempt_${attempt}.txt"; then
              break
            fi
            status=${PIPESTATUS[0]}
            if grep -qE "cannot parse arguments|no lint driver configured" ".lake/lint_output_attempt_${attempt}.txt"; then
              echo ""
              echo "=============================================================================="
              echo "ERROR: Your branch predates the current 'lake lint' configuration."
              echo "Please merge 'master' into your PR branch and push again."
              echo ""
              echo "You can do this with:"
              echo "  git fetch upstream"
              echo "  git merge upstream/master"
              echo "  git push"
              echo "=============================================================================="
              echo ""
              exit 1
            fi
            if [ "$status" -eq 124 ]; then
              echo "runLinter timed out (attempt $attempt)."
              if [ "$attempt" -lt 2 ]; then
                echo "Retrying runLinter after timeout..."
                continue
              fi
            fi
            exit $status
          done

      - name: end gh-problem-match-wrap for shake and lint steps
        if: ${{ always() && (needs.build.outputs.build-outcome == 'success' || needs.build.outputs.build-outcome == 'failure') }}
        uses: leanprover-community/gh-problem-matcher-wrap@65a654fcdf7b64ff7633bc7a558f7b46d59a27bf # 2026-06-25
        with:
          action: remove
          linters: gcc

  # TODO: Remove this job after leanprover-community/batteries#2049 is deployed
  # and no active Batteries adaptations remain in mathlib4-nightly-testing.
  # Keep its App token on a fresh runner, separate from the branch build.
  batteries_pr_comment:
    name: Comment on batteries-pr-testing branch
    needs: [build, test_lint]
    # Report only after test_lint finishes; cancellation before it starts has no results.
    if: ${{ always() && github.repository == 'leanprover-community/mathlib4-nightly-testing' && startsWith(github.ref_name, 'batteries-pr-testing-') &&</span> (needs.test_lint.result == 'success' || needs.test_lint.result == 'failure') }}
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: read
    steps:
      - name: Checkout local actions
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.workflow_sha }}
          fetch-depth: 1
          sparse-checkout: .github/actions
          path: workflow-actions
          persist-credentials: false # no later step needs git credentials

      - name: Get mathlib-ci
        uses: ./workflow-actions/.github/actions/get-mathlib-ci

      - name: Generate batteries-pr-testing app token
        id: batteries-pr-testing-token
        uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
        with:
          app-id: ${{ secrets.MATHLIB_NIGHTLY_TESTING_APP_ID }}
          private-key: ${{ secrets.MATHLIB_NIGHTLY_TESTING_PRIVATE_KEY }}
          owner: leanprover-community
          repositories: batteries
          permission-pull-requests: write # labels and comments on the Batteries PR

      - name: Post comments for batteries-pr-testing-NNNN branches
        shell: bash
        env:
          TOKEN: ${{ steps.batteries-pr-testing-token.outputs.token }}
          GITHUB_CONTEXT: ${{ toJson(github) }}
          WORKFLOW_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
          BUILD_OUTCOME: ${{ needs.build.outputs.build-outcome }}
          NOISY_OUTCOME: ${{ needs.build.outputs.noisy-outcome }}
          ARCHIVE_OUTCOME: ${{ needs.build.outputs.archive-outcome }}
          COUNTEREXAMPLES_OUTCOME: ${{ needs.build.outputs.counterexamples-outcome }}
          LINT_OUTCOME: ${{ needs.test_lint.outputs.lint-outcome }}
          TEST_OUTCOME: ${{ needs.test_lint.outputs.test-outcome }}
          NIGHTLY_TESTING_REPO: leanprover-community/mathlib4-nightly-testing
        run: |
          "${CI_SCRIPTS_DIR}/maintainer/lean-pr-testing-comments.sh" batteries

  # Report from a fresh runner so the Batteries write token never reaches PR code.
  batteries_adaptation_comment:
    name: Report Mathlib CI to Batteries
    needs: [build, test_lint]
    # Report for Batteries adaptation PRs from the shared fork after test_lint finishes, unless the run was cancelled.
    if: >-
      !cancelled() && github.repository == 'leanprover-community/mathlib4' &&</span>
      github.event.pull_request.head.repo.full_name == 'leanprover-community/mathlib4-adaptations' &&
      startsWith(github.head_ref, 'batteries-pr-testing-') &&
      (needs.test_lint.result == 'success' || needs.test_lint.result == 'failure')
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      pull-requests: read
    steps:
      - name: Check the adaptation PR and read its Batteries pin
        id: adaptation
        uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
        with:
          script: |
            const pr = context.payload.pull_request;
            const match = /^batteries-pr-testing-([0-9]+)$/.exec(pr.head.ref);
            if (!match) return;
            const { data: current } = await github.rest.pulls.get({ ...context.repo, pull_number: pr.number });
            if (current.state !== 'open' || current.head.sha !== pr.head.sha) return;
            const { data: file } = await github.rest.repos.getContent({
              ...context.repo, path: 'lake-manifest.json', ref: pr.head.sha,
            });
            const manifest = JSON.parse(Buffer.from(file.content, 'base64').toString());
            core.setOutput('batteries-sha', manifest.packages.find(p => p.name === 'batteries').rev);
            core.setOutput('batteries-pr', match[1]);

      - name: Checkout local actions
        if: steps.adaptation.outputs.batteries-pr != ''
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.workflow_sha }}
          fetch-depth: 1
          sparse-checkout: .github/actions
          path: workflow-actions
          persist-credentials: false

      - name: Get mathlib-ci
        if: steps.adaptation.outputs.batteries-pr != ''
        uses: ./workflow-actions/.github/actions/get-mathlib-ci

      - name: Generate Batteries status token
        if: steps.adaptation.outputs.batteries-pr != ''
        id: token
        uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0
        with:
          app-id: ${{ secrets.BATTERIES_STATUS_APP_ID }}
          private-key: ${{ secrets.BATTERIES_STATUS_PRIVATE_KEY }}
          owner: leanprover-community
          repositories: batteries
          permission-pull-requests: write

      - name: Update the Batteries status comment and labels
        if: steps.adaptation.outputs.batteries-pr != ''
        shell: bash
        env:
          TOKEN: ${{ steps.token.outputs.token }}
          BOT_LOGIN: mathlib-adaptations-status[bot]
          GITHUB_CONTEXT: ${{ toJSON(github) }}
          BATTERIES_SHA: ${{ steps.adaptation.outputs.batteries-sha }}
          WORKFLOW_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
          BUILD_OUTCOME: ${{ needs.build.outputs.build-outcome }}
          NOISY_OUTCOME: ${{ needs.build.outputs.noisy-outcome }}
          ARCHIVE_OUTCOME: ${{ needs.build.outputs.archive-outcome }}
          COUNTEREXAMPLES_OUTCOME: ${{ needs.build.outputs.counterexamples-outcome }}
          WANTED_OUTCOME: ${{ needs.build.outputs.wanted-outcome }}
          MK_ALL_OUTCOME: ${{ needs.build.outputs.mk_all-outcome }}
          LINT_OUTCOME: ${{ needs.test_lint.outputs.lint-outcome }}
          TEST_OUTCOME: ${{ needs.test_lint.outputs.test-outcome }}
        run: |
          "${CI_SCRIPTS_DIR}/maintainer/lean-pr-testing-comments.sh" batteries

  upload_cache:
    name: Upload to cache
    needs: [build]
    runs-on: ubuntu-latest # These steps run on a GitHub runner; no landrun sandboxing is needed.
    timeout-minutes: 20
    # Pins the OIDC `sub` claim to `...:environment:<cache_environment>`, which the cache writer
    # credentials are scoped to. A token minted by any job without this environment
    # (e.g. the untrusted build/post_steps/style_lint jobs) cannot satisfy that trust.
    environment:
      name: ${{ inputs.cache_environment }}
      # Skip creating a GitHub deployment record/UI; we use the environment only to
      # pin the OIDC `sub` claim and gate access to its federated credential.
      deployment: false
    permissions:
      contents: read
      id-token: write
    # We only upload the cache if the build started (whether succeeding, failing, or cancelled)
    # but not if any earlier step failed or was cancelled.
    # See discussion at https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Some.20files.20not.20found.20in.20the.20cache/near/407183836
    if: ${{ always() && needs.build.outputs.cache-staging-has-files == 'true' }}
    steps:
      # The artifact download needs nothing from the checkout, so it runs in
      # the background while the cache tool builds. The download lands outside
      # the workspace, because the checkout below deletes every entry of the
      # workspace before it clones.
      - name: Download cache staging artifact
        id: download_staging
        background: true
        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          name: cache-staging
          path: ${{ runner.temp }}/cache-staging

      # Build the write-side cache tool (and load the trust-dispatch action below)
      # from the branch under test, so a PR's `--container`-aware tool is what
      # writes the cache. This job only runs in trusted in-repo contexts (bors,
      # dev branches, the nightly-testing repo) — fork PRs run master's
      # `build_template` via `pull_request_target`, never this one — so
      # `pr_branch_ref` is always a trusted ref here. Fork PRs keep `master`.
      - &checkout_tools_branch
        name: Checkout tools branch
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.tools_branch_ref != '' && inputs.tools_branch_ref || (github.event.pull_request.head.repo.fork && 'master' || inputs.pr_branch_ref) }}
          fetch-depth: 1
          persist-credentials: false # no later step needs git credentials

      # Same trust dispatch as in the `build` and `post_steps` jobs, loaded from
      # the tools-branch checkout above.
      - &compute_cache_trust_dispatch
        name: Compute cache trust dispatch
        uses: ./.github/actions/cache-trust-dispatch
        with:
          repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
          branch: ${{ github.head_ref || github.ref_name }}
          head-sha: ${{ github.event.pull_request.head.sha || github.sha }}

      - &configure_lean_for_cache
        name: Configure Lean
        uses: leanprover/lean-action@fe408643ea7367d8c0404a8be3975bb145f5fb64 # v1.7.0
        with:
          auto-config: false # Don't run `lake build`, `lake test`, or `lake lint` automatically.
          use-github-cache: false
          use-mathlib-cache: false # This can be re-enabled once we are confident in the cache again.
          reinstall-transient-toolchain: true

      - &install_curl
        name: Install curl
        env:
          PINNED_CURL_RELEASE: v8.23.0
          PINNED_CURL_SHA256: 83a56256434a3d3f6edbdad2cbdb1f23a44fe8fd52968d18ab57763fdc0afba0
        run: |
          dir="$RUNNER_TEMP/curl-install"
          mkdir -p "$dir"
          cd "$dir"
          curl -fsSL --retry 5 -o curl \
            "https://github.com/leanprover-community/static-curl/releases/download/${PINNED_CURL_RELEASE}/curl-x86_64-linux-static"
          echo "${PINNED_CURL_SHA256}  curl" | sha256sum -c -
          chmod u+x curl
          echo "$dir" >> "$GITHUB_PATH"
          ./curl --version

      - &build_cache_executable
        name: build cache executable
        run: |
          lake build cache
          CACHE_BIN="$(pwd)/.lake/build/bin/cache"
          if [ ! -x "$CACHE_BIN" ]; then
            echo "cache binary not found: $CACHE_BIN"
            exit 1
          fi
          echo "CACHE_BIN=$CACHE_BIN" >> "$GITHUB_ENV"

      - name: wait for the artifact download
        wait: download_staging

      # Upload the staged set to R2. `master` writes the public cache bucket,
      # flat. `forks` writes the developer cache bucket in the container's
      # layout, which the cache resolver serves. The mint action returns
      # short-lived S3 credentials as masked step outputs. A failed mint or
      # upload fails the job.
      - &mint_r2_credentials
        name: Mint R2 credentials
        id: mint-r2
        uses: leanprover-community/mathlib-ci/.github/actions/mint-s3-credentials@d6393a535c054122e507b6c5e1b2f4c31c604121
        with:
          broker-url: ${{ vars.MATHLIB_CACHE_BROKER_URL }}
          audience: mathlib-cache-broker

      - name: Upload staged cache to R2
        shell: bash
        env:
          REPO: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
          CACHE_STAGING_DIR: ${{ runner.temp }}/cache-staging
          MATHLIB_CACHE_S3_ACCESS_KEY_ID: ${{ steps.mint-r2.outputs.access-key-id }}
          MATHLIB_CACHE_S3_SECRET_ACCESS_KEY: ${{ steps.mint-r2.outputs.secret-access-key }}
          MATHLIB_CACHE_S3_SESSION_TOKEN: ${{ steps.mint-r2.outputs.session-token }}
          # R2 signs every request in the region `auto`.
          MATHLIB_CACHE_S3_REGION: auto
          # The public cache bucket's master prefix, `https://<endpoint>/<bucket>/mathlib4`.
          # The flat write puts `{url}/f/{hash}.ltar` under it, which the cache
          # resolver serves.
          MASTER_PUT_URL: ${{ secrets.MATHLIB_CACHE_R2_PUT_URL }}
          # The developer cache bucket, `https://<endpoint>/<bucket>`. The container
          # write puts `{base}/mathlib4-forks/f/{repo}/{sha}/{hash}.ltar` under it,
          # with the completeness marker `{base}/mathlib4-forks/m/{repo}/{sha}`, for
          # the per-commit scope the dispatch sets.
          DEVELOPER_PUT_BASE_URL: ${{ secrets.MATHLIB_CACHE_R2_DEVELOPER_PUT_BASE_URL }}
        run: |
          # $MATHLIB_CACHE_PRIMARY is the container the dispatch selected.
          case "$MATHLIB_CACHE_PRIMARY" in
            master)
              if [ -z "$MASTER_PUT_URL" ]; then
                echo "::error::the secret MATHLIB_CACHE_R2_PUT_URL is unset"
                exit 1
              fi
              export MATHLIB_CACHE_PUT_URL="$MASTER_PUT_URL"
              container_args=()
              ;;
            forks)
              if [ -z "$DEVELOPER_PUT_BASE_URL" ]; then
                echo "::error::the secret MATHLIB_CACHE_R2_DEVELOPER_PUT_BASE_URL is unset"
                exit 1
              fi
              export MATHLIB_CACHE_PUT_BASE_URL="$DEVELOPER_PUT_BASE_URL"
              container_args=(--container=forks)
              ;;
          esac
          echo "Uploading cache to R2 (container: $MATHLIB_CACHE_PRIMARY)..."
          lake env "$CACHE_BIN" put-staged --backend=s3 "${container_args[@]}" --staging-dir="$CACHE_STAGING_DIR" --repo="$REPO"

  upload_test_cache:
    name: Upload tests to cache
    needs: [test_lint]
    # The upload is best effort: if it fails, later runs rebuild these test files.
    continue-on-error: true
    runs-on: ubuntu-latest # These steps run on a GitHub runner; no landrun sandboxing is needed.
    timeout-minutes: 20
    # The environment of `upload_cache` gives this job the same OIDC `sub` claim.
    environment:
      name: ${{ inputs.cache_environment }}
      deployment: false
    permissions:
      contents: read
      id-token: write
    # Uploads the `MathlibTest` oleans that `test_lint` staged to the public R2 bucket,
    # where `upload_cache` writes the `master` container. No other job needs this one.
    if: ${{ always() && needs.test_lint.outputs.test-cache-staging-has-files == 'true' }}
    steps:
      # Each `*name` repeats the step of `upload_cache` that `&name` marks.
      - *checkout_tools_branch
      - *compute_cache_trust_dispatch
      - *configure_lean_for_cache
      - *install_curl
      - *build_cache_executable

      - name: Download MathlibTest cache staging artifact
        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
        with:
          name: cache-staging-test
          path: cache-staging

      - *mint_r2_credentials

      - name: Upload staged MathlibTest cache to R2
        if: steps.mint-r2.outputs.success == 'true' && env.MATHLIB_CACHE_PRIMARY == 'master'
        continue-on-error: true
        shell: bash
        env:
          MATHLIB_CACHE_S3_ACCESS_KEY_ID: ${{ steps.mint-r2.outputs.access-key-id }}
          MATHLIB_CACHE_S3_SECRET_ACCESS_KEY: ${{ steps.mint-r2.outputs.secret-access-key }}
          MATHLIB_CACHE_S3_SESSION_TOKEN: ${{ steps.mint-r2.outputs.session-token }}
          MATHLIB_CACHE_S3_REGION: auto
          # The flat write under the public bucket's master prefix. An unset secret
          # fails the upload.
          MATHLIB_CACHE_PUT_URL: ${{ secrets.MATHLIB_CACHE_R2_PUT_URL }}
        run: lake env "$CACHE_BIN" put-staged --backend=s3 --staging-dir="cache-staging"

  post_steps:
    name: Post-Build Step
    needs: [build, upload_cache]
    if: ${{ always() && needs.build.result == 'success' && (needs.upload_cache.result == 'success' || needs.upload_cache.result == 'skipped') }}
    runs-on: ubuntu-latest # Note these steps run on disposable GitHub runners, so no landrun sandboxing is needed.
    timeout-minutes: 30
    # This job checks out and executes (potentially fork) PR code unsandboxed,
    # so it must not inherit any write-capable token.
    permissions:
      contents: read
    steps:

      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.pr_branch_ref }}
          # Untrusted (potentially fork) checkout: don't persist the GITHUB_TOKEN into its .git/config.
          persist-credentials: false
          # This job runs with only `contents: read` and no persisted credentials,
          # so checking out fork PR code under pull_request_target is safe.
          allow-unsafe-pr-checkout: true

      # Sparse-checkout master's `.github/actions/` so the trust dispatch
      # below loads from a trust-rooted source, not from PR-branch-controlled
      # content. Mirrors the `Checkout local actions` step in the `build` job.
      # Also check out the cache tool (`Cache/`) at this ref. The verify step
      # below compares it against the PR branch's `Cache/` to classify a cache
      # miss. `github.workflow_sha` is the base ref the workflow runs from,
      # master for fork PRs, whose `cache` binary wrote the cache.
      - name: Checkout local actions and Cache baseline
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ github.workflow_sha }}
          fetch-depth: 1
          sparse-checkout: |
            .github/actions
            Cache
          path: workflow-actions
          persist-credentials: false # no later step needs git credentials

      # Sets MATHLIB_CACHE_FROM in env so the `cache get` calls below pick
      # up the trust-class-appropriate read fallback automatically. Every job
      # that reads or writes the cache gets this policy from the same composite
      # action.
      - name: Compute cache trust dispatch
        uses: ./workflow-actions/.github/actions/cache-trust-dispatch
        with:
          repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
          branch: ${{ github.head_ref || github.ref_name }}
          head-sha: ${{ github.event.pull_request.head.sha || github.sha }}

      - name: Configure Lean
        uses: leanprover/lean-action@fe408643ea7367d8c0404a8be3975bb145f5fb64 # v1.7.0
        with:
          auto-config: false # Don't run `lake build`, `lake test`, or `lake lint` automatically.
          use-github-cache: false
          use-mathlib-cache: false # This can be re-enabled once we are confident in the cache again.
          reinstall-transient-toolchain: true

      # The pinned curl keeps curl's retries on every runner image: the tool
      # runs curl 8.18 (Ubuntu 26.04) without them.
      - *install_curl

      - name: get cache for Mathlib
        run: |
          # Run once without --repo, so we can diagnose what `lake exe cache get` wants to do by itself.
          lake exe cache get
          # Run again with --repo, so ensure we actually get the oleans.
          lake exe cache --repo=${{ github.event.pull_request.head.repo.full_name || github.repository }} get

      # The declaration dump needs the mathlib-ci scripts; the action is loaded from
      # the `Checkout local actions and Cache baseline` checkout above.
      - name: Get mathlib-ci
        uses: ./workflow-actions/.github/actions/get-mathlib-ci

      # The dump is single-threaded and needs only the Mathlib oleans, so it runs in
      # the background from here; the job waits for it before the upload.
      # Everything the `import-graph` artifact holds goes into one directory specified by
      # `--out-dir`.
      - name: dump declarations and transitive-import counts
        id: dump
        background: true
        run: |
          mkdir -p "$RUNNER_TEMP/import-graph"
          lake env lean --run "${CI_SCRIPTS_DIR}/pr_summary/dumpReasonableDecls.lean" \
            --out-dir "$RUNNER_TEMP/import-graph" Mathlib
          ## Record the PR number so the post-build `decls-diff` workflow can find
          ## the comment to patch without the (laggy) commit-SHA search API. Empty
          ## for non-PR builds (push to master / bors); the consumer then falls
          ## back to the commit's associated PRs.
          printf '%s' "${{ github.event.pull_request.number }}" > "$RUNNER_TEMP/import-graph/pr_number.txt"

      - name: get cache for Archive and Counterexamples
        run: |
          # Run once without --repo, so we can diagnose what `lake exe cache get` wants to do by itself.
          lake exe cache get Archive Counterexamples
          # Run again with --repo, so ensure we actually get the oleans.
          lake exe cache --repo=${{ github.event.pull_request.head.repo.full_name || github.repository }} get Archive Counterexamples

      - name: verify that everything was available in the cache
        id: verify_cache
        # Verify the cache reconstitutes this commit's oleans. This job reads
        # the cache with the PR branch's own `lake exe cache get`. The write
        # path uses master's `cache` binary for fork PRs and the PR branch's
        # binary for every other build. So a fork PR whose `Cache/` differs
        # from master reads a different `.ltar` key space (say, after a
        # `rootHashGeneration` bump) and misses every file. That is an expected
        # invalidation: warn and continue. Any other build reads and writes
        # with the same binary, so a miss there is a real gap and is fatal.
        env:
          # GitHub sets this from the event payload; it is empty for pushes
          # (master, bors), so those fail closed below.
          HEAD_REPO_IS_FORK: ${{ github.event.pull_request.head.repo.fork }}
        run: |
          set +e
          fail=0
          for target in Mathlib Archive Counterexamples; do
            echo "::group::{verify ${target} cache}"
            lake build --no-build --rehash -v "${target}" || fail=1
            echo "::endgroup::"
          done
          if [ "${fail}" -eq 0 ]; then
            exit 0
          fi

          missing="The cache is missing build outputs. The log above names the modules that Lake needs to rebuild."
          retry_hint="Hint: to rule out a transient network error, push an empty commit to re-run all jobs: git commit --allow-empty -m 'chore: re-run CI' && git push. If the error persists, ask in the #mathlib4 channel on Zulip."

          # Only fork PRs read and write the cache with different binaries.
          # Every other build (master, bors, dev branches) uses one binary, so
          # a miss is a real gap.
          if [ "${HEAD_REPO_IS_FORK}" != "true" ]; then
            echo "::error title=Cache incomplete::${missing}"
            echo "${retry_hint}"
            exit 1
          fi

          # `workflow-actions/Cache` is master's cache tool at
          # `github.workflow_sha`; `Cache` is the PR branch's. Matching source
          # means the key spaces agree, so the miss is a real gap. Differing
          # source means the PR changed the key space, so the miss is expected.
          # The cache writer is master's binary at upload time, which can be
          # newer than `workflow_sha` when a `Cache/` change lands on master
          # mid-build; that skew can only hard-fail like an unguarded verify
          # or soft-pass a key space that genuinely diverged.
          dout=$(diff -rq workflow-actions/Cache Cache 2>&1)
          dstat=$?
          if [ "${dstat}" -eq 0 ]; then
            echo "::error title=Cache incomplete::${missing}"
            echo "${retry_hint}"
            exit 1
          elif [ "${dstat}" -eq 1 ]; then
            echo "::notice title=Cache check skipped::This PR changes Cache/, so CI cannot check the cache for this PR."
            echo "${dout}"
            # The downstream check below reads the same key space, so skip it.
            echo "key_space_changed=true" >> "$GITHUB_OUTPUT"
            exit 0
          else
            echo "::error title=Cache incomplete::${missing}"
            echo "Note: CI could not compare this PR's Cache/ with master's (diff exit status ${dstat})."
            echo "${dout}"
            exit 1
          fi

      - name: check the cache from a downstream project
        # `DownstreamTest/` is a minimal project that requires mathlib by path. Fetching
        # the cache from there runs the cache tool's downstream-only checks (toolchain
        # and manifest mismatches), and `lake build --no-build` checks that Lake accepts
        # the cached oleans in a dependency context. The path dependency shares mathlib's
        # `.lake/build`, so Mathlib's oleans are already in place from the steps above;
        # the dependencies' oleans are fetched into `DownstreamTest/.lake/packages/`.
        if: steps.verify_cache.outputs.key_space_changed != 'true'
        env:
          REPO: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
        run: |
          cd DownstreamTest
          cp ../lean-toolchain .
          # Skip mathlib's `post_update` hook, so that the `cache get` below is the one tested.
          MATHLIB_NO_CACHE_ON_UPDATE=1 lake update
          lake exe cache --repo="${REPO}" get
          lake build --no-build Mathlib

      - name: check declarations in db files
        run: |
          python3 scripts/yaml_check.py docs/100.yaml docs/1000.yaml docs/overview.yaml docs/undergrad.yaml
          lake exe check-yaml

      - name: generate our import graph
        run: |
          mkdir -p "$RUNNER_TEMP/import-graph"
          lake exe graph "$RUNNER_TEMP/import-graph/import_graph.dot"

      - name: wait for the declaration dump
        wait: dump

      - name: ensure dump outputs are regular files
        run: |
          DIR="$RUNNER_TEMP/import-graph"
          if [ -L "$DIR" ] || [ ! -d "$DIR" ]; then
            echo "Refusing to upload: $DIR is not a directory." >&2
            exit 1
          fi
          BAD="$(find "$DIR" -mindepth 1 ! -type f)"
          if [ -n "$BAD" ]; then
            echo "Refusing to upload: these are not regular files:" >&2
            printf '%s\n' "$BAD" >&2
            exit 1
          fi
          ## The outputs written above, so that a missing one fails this build rather than
          ## `decls-diff.yml` for every PR based on this commit. New outputs need not be listed.
          for f in api.jsonl imports.json import_graph.dot pr_number.txt; do
            if [ ! -f "$DIR/$f" ]; then
              echo "Refusing to upload: $f is missing." >&2
              exit 1
            fi
          done
          ls -la -- "$DIR"

      - name: upload the import graph
        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
        with:
          name: import-graph
          ## The directory's contents, at the artifact's top level as before.
          path: ${{ runner.temp }}/import-graph/
          ## Master pushes: 90 days, so later PRs forked from these commits
          ## can consume the dumps from the artifact. Other branches: 7 days.
          retention-days: ${{ github.ref == 'refs/heads/master' && '90' || '7' }}

      - name: clean up the import graph files
        run: rm -rf "$RUNNER_TEMP/import-graph"

      - name: check all scripts build successfully
        run: |
          lake env lean scripts/create_deprecated_modules.lean
          lake env lean scripts/autolabel.lean
          # Executing this also runs the export and writes a (gitignored) `crossrefs.json`,
          # which doubles as a smoke test of the `export_crossrefs.yml` workflow.
          lake env lean scripts/export_crossrefs.lean
          lake exe check-title-labels --labels "t-algebra" "feat: dummy PR for testing"

      - name: build everything
        # make sure everything is available for test/import_all.lean
        # and that miscellaneous executables still work
        run: |
          lake build Batteries Qq Aesop ProofWidgets Plausible

      # We no longer run `lean4checker` in regular CI, as it is quite expensive for little benefit.
      # Instead we run it in a cron job on master: see `daily.yml`.

  style_lint:
    name: Lint style
    runs-on: ubuntu-latest
    # This job lints (potentially fork) PR code, so it must not inherit any write-capable token.
    # In `check` mode lint-style-action only reads and validates code locally (no API calls).
    permissions:
      contents: read
    steps:
      # lint-style-action can check out `pr_branch_ref` itself, but its `actions/checkout` refuses
      # fork PR code under pull_request_target with no input to opt in, so check out here instead.
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          ref: ${{ inputs.pr_branch_ref }}
          # Untrusted (potentially fork) checkout: don't persist the GITHUB_TOKEN into its .git/config.
          persist-credentials: false
          # This job runs with only `contents: read` and no persisted credentials,
          # so checking out fork PR code under pull_request_target is safe.
          allow-unsafe-pr-checkout: true
      - uses: leanprover-community/lint-style-action@a5e3ef275cc682ba79c1f8ba34ae2ade5d8d2101 # 2026-10-28
        with:
          mode: check
          lint-bib-file: true
          checkout: false

  final:
    name: Post-CI job
    # ensure that this runs iff direct dependencies succeeded even if transitive dependencies  were skipped
    if: ${{ always() && inputs.run_post_ci && needs.style_lint.result == 'success' && needs.build.result == 'success' && needs.test_lint.result == 'success' && needs.post_steps.result == 'success' }}
    needs: [style_lint, build, test_lint, post_steps]
    runs-on: ubuntu-latest
    steps:
      - id: PR
        uses: 8BitJonny/gh-get-current-pr@4056877062a1f3b624d5d4c2bedefa9cf51435c9 # 4.0.0
        # TODO: this may not work properly if the same commit is pushed to multiple branches:
        # https://github.com/8BitJonny/gh-get-current-pr/issues/8
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          # Only return if PR is still open
          filterOutClosed: true

      - id: remove_labels
        name: Remove "awaiting-CI"
        # we use curl rather than octokit/request-action so that the job won't fail
        # (and send an annoying email) if the labels don't exist
        run: |
          curl --request DELETE \
            --url https://api.github.com/repos/${{ github.repository }}/issues/${{ steps.PR.outputs.number }}/labels/awaiting-CI \
            --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}'

      - if: contains(steps.PR.outputs.pr_labels, 'auto-merge-after-CI')
        name: Generate auto merge app token
        id: auto-merge-app-token
        uses: leanprover-community/mathlib-ci/.github/actions/azure-create-github-app-token@d6393a535c054122e507b6c5e1b2f4c31c604121
        with:
          app-id: ${{ secrets.MATHLIB_AUTO_MERGE_APP_ID }}
          key-vault-name: ${{ vars.MATHLIB_AZ_KEY_VAULT_NAME }}
          key-name: mathlib-auto-merge-app-pk
          azure-client-id: ${{ vars.GH_APP_AZURE_CLIENT_ID_CI_AUTO_MERGE }}
          azure-tenant-id: ${{ secrets.LPC_AZ_TENANT_ID }}

      - if: contains(steps.PR.outputs.pr_labels, 'auto-merge-after-CI')
        name: Get PR label timeline data
        # 'auto-merge-after-CI' must be within the last 100 labels added (could be increased to 250 if needed)
        # query from https://stackoverflow.com/a/67939355
        # unfortunately we cannot query only for 'auto-merge-after-CI' events
        # so we have to process this with jq in the next step
        id: get-timeline
        uses: octokit/graphql-action@ddde8ebb2493e79f390e6449c725c21663a67505 # v3.0.2
        with:
          query: |
            query($owner: String!, $name: String!, $number: Int!) {
              repository(owner: $owner, name: $name) {
                pullRequest(number: $number) {
                  timelineItems(itemTypes: LABELED_EVENT, last: 100) {
                    nodes {
                      ... on LabeledEvent {
                        createdAt
                        actor { login __typename }
                        label { name }
                      }
                    }
                  }
                }
              }
            }
          owner: leanprover-community
          name: mathlib4
          number: ${{ steps.PR.outputs.number }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - if: contains(steps.PR.outputs.pr_labels, 'auto-merge-after-CI')
        name: Extract label actor username
        id: get-label-actor
        env:
          TIMELINE: ${{ steps.get-timeline.outputs.data }}
        run: |
          # Parse the GraphQL response and filter for the specific label
          echo "$TIMELINE"
          ACTOR=$(echo "$TIMELINE" | jq -c '
            .repository.pullRequest.timelineItems.nodes
            | map(select(.label.name == "auto-merge-after-CI"))
            | sort_by(.createdAt)
            | last
            | .actor // empty
          ')
          USERNAME=$(echo "$ACTOR" | jq -r '.login // empty')
          # 'Bot' for GitHub App actors (whose GraphQL logins lack the '[bot]' suffix),
          # 'User' for regular accounts
          ACTOR_TYPE=$(echo "$ACTOR" | jq -r '.__typename // empty')

          # Validate username format (GitHub usernames are alphanumeric + hyphens, max 39 chars)
          printf 'USERNAME: %s\nACTOR_TYPE: %s\n' "$USERNAME" "$ACTOR_TYPE"
          if [[ -z "$USERNAME" ]]; then
            echo "Error: No actor found for the specified label"
            exit 1
          elif ! [[ "$USERNAME" =~ ^[a-zA-Z0-9-]{1,39}$ ]]; then
            echo "Error: Invalid username format: $USERNAME"
            exit 1
          fi

          echo "username=$USERNAME" >> "$GITHUB_OUTPUT"
          echo "actor_type=$ACTOR_TYPE" >> "$GITHUB_OUTPUT"
          echo "Found label actor: $USERNAME ($ACTOR_TYPE)"

      # bot usernames will cause this step to error with "Could not resolve to a User...",
      # so we skip it for all non-user actors; allowed bots are validated in the next step
      - if: >-
          contains(steps.PR.outputs.pr_labels, 'auto-merge-after-CI') &&
          steps.get-label-actor.outputs.actor_type == 'User'
        name: check team membership
        uses: tspascoal/get-user-teams-membership@b2546c5affc730fd8e3d8483ae9ad3621938c2f9 # v4.0.2
        id: actorTeams
        with:
          organization: leanprover-community # optional. Default value ${{ github.repository_owner }}
                  # Organization to get membership from.
          username: ${{ steps.get-label-actor.outputs.username }}
          GITHUB_TOKEN: ${{ secrets.MATHLIB_REVIEWERS_TEAM_KEY }} # (Requires scope: `read:org`)

      - if: >-
          contains(steps.PR.outputs.pr_labels, 'auto-merge-after-CI') &&
          (
            (
              steps.get-label-actor.outputs.actor_type == 'Bot' &&
              (
                steps.get-label-actor.outputs.username == 'mathlib-nolints' ||
                steps.get-label-actor.outputs.username == 'mathlib-update-dependencies' ||
                steps.get-label-actor.outputs.username == 'mathlib-splicebot'
              )
            ) ||
            contains(steps.actorTeams.outputs.teams, 'mathlib-maintainers') ||
            contains(steps.actorTeams.outputs.teams, 'lean-release-managers') ||
            contains(steps.actorTeams.outputs.teams, 'bot-users')
          )
        name: If `auto-merge-after-CI` is present, add a `bors merge` comment.
        uses: GrantBirki/comment@937820f3623fd0e300294bcc64ac7577fc0ad4cc # v3.0.3
        with:
          # This token is masked by the token minting action and will not be logged accidentally.
          token: ${{ steps.auto-merge-app-token.outputs.token }}
          issue-number: ${{ steps.PR.outputs.number }}
          body: |
            As this PR is labelled `auto-merge-after-CI`, we are now sending it to bors:

            bors merge

[Verzeichnis aufwärts0.122unsichere VerbindungÜbersetzung europäischer Sprachen durch Browser2026-11-18]