diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 40b34a38ac..03d9a2f83a 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -2,8 +2,14 @@ name: Provider CI Build description: Build full debug test products with lane-specific caches and source-matched Metal inputs: lane: - description: provider, sdk or cluster; each owns independent build outputs + description: provider or cluster; each owns independent build outputs required: true + save-caches: + description: "'true' to save this lane's caches; provider-tests.yml passes true only for pushes to master and dev" + default: 'false' + strict-cache: + description: "'true' to restore only an entry of this exact recipe (provider-tests.yml passes true for master)" + default: 'false' runs: using: composite steps: @@ -13,7 +19,7 @@ runs: LANE: ${{ inputs.lane }} run: | case "$LANE" in - provider|sdk|cluster) ;; + provider|cluster) ;; *) echo "Unknown provider CI lane: $LANE" >&2; exit 2 ;; esac - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 @@ -33,22 +39,57 @@ runs: shell: bash env: LANE: ${{ inputs.lane }} - run: python3 scripts/provider-ci-cache.py keys --lane "$LANE" >> "$GITHUB_OUTPUT" + run: | + python3 scripts/provider-ci-cache.py keys --lane "$LANE" >> "$GITHUB_OUTPUT" + # actions/cache stores a path outside the workspace relative to the + # workspace, so SwiftPM's cache is shared only between equal layouts. + echo "home-layout=$(printf '%s\n' "$HOME" "$GITHUB_WORKSPACE" | shasum -a 256 | cut -c1-12)" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + # Dependency clones for a cold build; the lane's own build cache already + # holds them when it is restored. + - name: Restore SwiftPM repositories + id: spm-repos + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ~/Library/Caches/org.swift.swiftpm/repositories + key: spm-repos-v1-${{ runner.os }}-${{ steps.keys.outputs.home-layout }}-${{ inputs.lane }}-${{ hashFiles('**/Package.resolved', '!**/.build/**') }} + restore-keys: spm-repos-v1-${{ runner.os }}-${{ steps.keys.outputs.home-layout }}-${{ inputs.lane }}- + # A Darkbloom host keeps the entries it saved, 10 GiB per repository, so a + # push saves at most one build per lane and UTC day there; every other + # runner keys the build by commit. + - name: Choose the Swift test build's cache key + id: build-key + shell: bash + env: + PREFIX: ${{ steps.keys.outputs.swift-prefix }} + COMMIT_KEY: ${{ steps.keys.outputs.swift-key }} + run: | + case "${RUNNER_NAME:-}" in + darkbloom-*) echo "key=${PREFIX}day-$(date -u +%F)" >> "$GITHUB_OUTPUT" ;; + *) echo "key=$COMMIT_KEY" >> "$GITHUB_OUTPUT" ;; + esac + # Restore tiers: this recipe's newest entry; then any recipe's with the + # same toolchain, dependencies and checkout path; then any entry with the + # same toolchain, checkout path and MLX pins, whose MLX objects stay valid. + # The build steps build once more from nothing if a looser entry fails. + # strict-cache (master) keeps only the first tier. - name: Restore lane-specific Swift test build id: swift-cache uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: | provider-swift/.build - libs/mlx-swift-lm/.build libs/darkbloom-cluster/.build - key: ${{ steps.keys.outputs.swift-key }} - restore-keys: ${{ steps.keys.outputs.swift-prefix }} + key: ${{ steps.build-key.outputs.key }} + restore-keys: | + ${{ steps.keys.outputs.swift-prefix }} + ${{ inputs.strict-cache != 'true' && steps.keys.outputs.swift-loose-prefix || '' }} + ${{ inputs.strict-cache != 'true' && steps.keys.outputs.swift-mlx-prefix || '' }} - name: Revalidate source timestamps and discard cached runtime resources shell: bash run: | python3 scripts/provider-release-cache.py restore-mtimes - for root in provider-swift/.build libs/mlx-swift-lm/.build libs/darkbloom-cluster/.build; do + for root in provider-swift/.build libs/darkbloom-cluster/.build; do [ -d "$root" ] || continue find "$root" -type f -name mlx.metallib -delete find "$root" -mindepth 3 -maxdepth 3 -type d \ @@ -59,43 +100,47 @@ runs: id: provider-build shell: bash working-directory: provider-swift + env: + PROVIDER_CI_MATCHED_KEY: ${{ steps.swift-cache.outputs.cache-matched-key }} + PROVIDER_CI_STRICT_PREFIX: ${{ steps.keys.outputs.swift-prefix }} # Instrumented for the coverage report. Both builds use the same flags, # so neither rebuilds the other. run: | - swift build --build-tests --enable-code-coverage - swift build --product darkbloom-fan-helper --enable-code-coverage - - name: Build all SDK test products against local MLX - if: inputs.lane == 'sdk' - id: sdk-build - shell: bash - working-directory: libs/mlx-swift-lm - run: | - swift package unedit --force mlx-swift >/dev/null 2>&1 || true - swift package edit --path ../mlx-swift mlx-swift - swift build --build-tests + build() { + swift build --build-tests --enable-code-coverage && + swift build --product darkbloom-fan-helper --enable-code-coverage + } + build || { ../scripts/provider-ci-cold-retry.sh && build; } - name: Build all cluster test products if: inputs.lane == 'cluster' id: cluster-build shell: bash working-directory: libs/darkbloom-cluster - run: swift build --build-tests + env: + PROVIDER_CI_MATCHED_KEY: ${{ steps.swift-cache.outputs.cache-matched-key }} + PROVIDER_CI_STRICT_PREFIX: ${{ steps.keys.outputs.swift-prefix }} + run: swift build --build-tests || { ../../scripts/provider-ci-cold-retry.sh && swift build --build-tests; } - name: Record timestamps for successfully built sources - if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success' || steps.cluster-build.outcome == 'success') }} + if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.cluster-build.outcome == 'success') }} id: timestamps shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes - # Pushes save their build. A pull request saves only when it restored - # nothing, so its later pushes do not each add an entry that evicts the - # base branch's entry from the repository cache. + # Only callers' trusted pushes save (save-caches): a pull request's entry + # is scoped to its merge ref, where nothing else restores it. - name: Save lane-specific Swift test build - if: ${{ !cancelled() && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.swift-cache.outputs.cache-matched-key == '') }} + if: ${{ !cancelled() && inputs.save-caches == 'true' && steps.timestamps.outcome == 'success' && steps.swift-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: | provider-swift/.build - libs/mlx-swift-lm/.build libs/darkbloom-cluster/.build - key: ${{ steps.keys.outputs.swift-key }} + key: ${{ steps.build-key.outputs.key }} + - name: Save SwiftPM repositories + if: ${{ !cancelled() && inputs.save-caches == 'true' && steps.timestamps.outcome == 'success' && steps.spm-repos.outputs.cache-hit != 'true' }} + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ~/Library/Caches/org.swift.swiftpm/repositories + key: ${{ steps.spm-repos.outputs.cache-primary-key }} - name: Restore source-matched Metal cache id: metallib-cache uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 @@ -111,14 +156,13 @@ runs: run: | cmake --version case "$LANE" in - sdk) package=libs/mlx-swift-lm ;; cluster) package=libs/darkbloom-cluster ;; *) package=provider-swift ;; esac bin=$(swift build --package-path "$package" --show-bin-path) ./scripts/stage-test-metallib.sh "$bin" - name: Save validated source-matched Metal cache - if: ${{ !cancelled() && steps.metallib.outcome == 'success' && steps.metallib-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && inputs.save-caches == 'true' && steps.metallib.outcome == 'success' && steps.metallib-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ${{ runner.temp }}/metallib-cache diff --git a/.github/workflows/ci-dev.yml b/.github/workflows/ci-dev.yml new file mode 100644 index 0000000000..a5f3cf2018 --- /dev/null +++ b/.github/workflows/ci-dev.yml @@ -0,0 +1,52 @@ +name: CI (dev) + +# Pull requests into any branch but master (dev, and stacked feature +# branches) and pushes to dev run the provider and cluster tests +# (.github/workflows/provider-tests.yml) and nothing else: Release Integrity, +# Docs Lint and the contribution gates run only for master +# (.github/workflows/ci-master.yml, docs-impact.yml). +on: + push: + # Pushes to dev save the caches that pull requests into dev restore. + branches: [dev] + pull_request: + branches-ignore: [master, main] + +permissions: + contents: read + +# Only revisions of the same PR supersede each other; pushes stay independent. +# A push whose tree a pull request run already tested runs no test job +# (provider-plan.yml), so most push runs are a few GitHub-hosted steps. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + plan: + uses: ./.github/workflows/provider-plan.yml + permissions: + contents: read + actions: read + + tests: + name: Tests + needs: plan + if: ${{ !cancelled() }} + uses: ./.github/workflows/provider-tests.yml + permissions: + contents: read + with: + provider: ${{ needs.plan.outputs.provider }} + cluster: ${{ needs.plan.outputs.cluster }} + mimo_audio: ${{ needs.plan.outputs.mimo_audio }} + changed_provider: ${{ needs.plan.outputs.changed_provider }} + changed_cluster: ${{ needs.plan.outputs.changed_cluster }} + changes_result: ${{ needs.plan.outputs.changes_result }} + skip: ${{ needs.plan.outputs.skip }} + tested_run: ${{ needs.plan.outputs.tested_run }} + tree: ${{ needs.plan.outputs.tree }} + base: ${{ needs.plan.outputs.base }} + head: ${{ needs.plan.outputs.head }} + routes: ${{ needs.plan.outputs.routes }} + strict_cache: false diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml new file mode 100644 index 0000000000..e2b93acc5e --- /dev/null +++ b/.github/workflows/ci-master.yml @@ -0,0 +1,228 @@ +name: CI (master) + +# Pull requests into master and pushes to master run the provider and +# cluster tests (.github/workflows/provider-tests.yml), Release Integrity and +# Docs Lint. Pull requests into dev run only the tests (ci-dev.yml). +on: + push: + # Pushes to master save the caches that pull requests into master restore. + branches: [master, main] + pull_request: + branches: [master, main] + +permissions: + contents: read + +env: + # Only pushes to master save the .git caches of the jobs below. A pull + # request restores its base branch's entries and saves none + # (docs/developer/build.md#ci-caching). + SAVE_CACHES: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + # Every checkout but Docs Lint's skips the evidence tarballs and landing media + # (408 MB of the tree), which only Docs Lint reads. The rest of the evidence + # stays: provider-ci-cache.py hashes every tracked Package.swift. + CHECKOUT_SPARSE: | + /* + !/docs/reports/evidence/**/*.gz + !/landing/public/media/ + +# Only revisions of the same PR supersede each other; pushes stay independent. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + plan: + uses: ./.github/workflows/provider-plan.yml + permissions: + contents: read + actions: read + with: + linux_lanes: | + release-integrity linux_arm64 blacksmith-4vcpu-ubuntu-2404 + docs linux_arm64 blacksmith-4vcpu-ubuntu-2404 + + tests: + name: Tests + needs: plan + if: ${{ !cancelled() }} + uses: ./.github/workflows/provider-tests.yml + permissions: + contents: read + with: + provider: ${{ needs.plan.outputs.provider }} + cluster: ${{ needs.plan.outputs.cluster }} + mimo_audio: ${{ needs.plan.outputs.mimo_audio }} + changed_provider: ${{ needs.plan.outputs.changed_provider }} + changed_cluster: ${{ needs.plan.outputs.changed_cluster }} + changes_result: ${{ needs.plan.outputs.changes_result }} + skip: ${{ needs.plan.outputs.skip }} + tested_run: ${{ needs.plan.outputs.tested_run }} + tree: ${{ needs.plan.outputs.tree }} + base: ${{ needs.plan.outputs.base }} + head: ${{ needs.plan.outputs.head }} + routes: ${{ needs.plan.outputs.routes }} + strict_cache: true + + release-integrity: + name: Release Integrity + # A top-level job, so its check is named exactly Release Integrity, the + # name master's ruleset requires. It reads its lane of the run's one route + # request (provider-plan.yml). + needs: plan + if: ${{ !cancelled() }} + runs-on: ${{ fromJSON(needs.plan.outputs.routes)['release-integrity'] }} + timeout-minutes: 30 + steps: + # Every checkout in this workflow uses the same five steps: restore the + # newest .git a push saved, discard it unless git fsck accepts it, check + # out, and save .git once a day per branch (docs/developer/build.md#ci-caching). + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false # Keeps the job token out of the saved .git/config. + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} + # A plain build of master must be prod and a plain build of dev must be + # dev. The target is the pull request's base branch, or the pushed branch. + - name: Check the provider's plain-build default for the target branch + env: + TARGET_BRANCH: ${{ github.base_ref || github.ref_name }} + run: | + python3 scripts/test-provider-build-default.py + python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH" + - name: Validate changelog fragments + run: | + python3 scripts/test-changelog.py + make changelog-check + - name: Check provider release and installer integrity + run: | + ./scripts/check-release-version.sh + python3 scripts/test-provider-release-resolution.py + python3 scripts/test-provider-release-resume.py + python3 scripts/test-provider-release-toolchain.py + python3 scripts/test-provider-release-cache.py + python3 scripts/test-prepare-metal-toolchain.py + python3 scripts/test-provider-release-pipeline.py + python3 scripts/test-provider-release-publication.py + python3 scripts/test-provider-release-notes.py + python3 scripts/test-provider-cluster-runtime-models.py + python3 scripts/test-release-dev-branch.py + python3 scripts/test-provider-release-artifact.py + python3 scripts/test-provider-signing-validation.py + python3 scripts/test-provider-identity.py + python3 scripts/test-provider-test-watchdog.py + python3 scripts/test-stage-test-metallib.py + python3 scripts/test-provider-ci-cache.py + python3 scripts/test-provider-ci-workflow.py + python3 scripts/test-provider-test-shards.py + python3 scripts/test-cluster-test-plan.py + python3 scripts/test-ci-component-paths.py + python3 scripts/test-darkbloom-route.py + python3 scripts/test-ci-tested-tree.py + python3 scripts/test-prepare-prompt-fixtures.py + python3 provider-swift/Tests/test_protocol_fixture_resources.py + python3 scripts/test-app-attest-entitlements.py + ./scripts/test-setup-macos-homebrew.sh + - name: Test advisory threat review with local HTTP fixtures + run: | + python3 .github/scripts/test-threat-model-review.py + python3 .github/scripts/test-threat-full-scan.py + python3 .github/scripts/test-threat-ensemble.py + python3 .github/scripts/test-threat-budget.py + python3 .github/scripts/test-threat-bedrock.py + python3 .github/scripts/test-threat-diagnostics.py + python3 .github/scripts/test-threat-integration-scope.py + - name: Test native GPU CI routing without a GPU + run: python3 scripts/test-native-gpu-ci.py + - name: Test model registry workflow with loopback HTTP + run: python3 scripts/test_model_registry_workflow.py + - name: Test bounded MiMo provider fixture provisioning offline + run: python3 scripts/test-prepare-mimo-provider-fixtures.py + - name: Test serving qualification evidence and catalogs without a GPU + run: python3 -m unittest discover -s scripts/serving_performance -t scripts -p 'test_*.py' + - name: Test actual-call and bounded timing receipts without a GPU + run: | + python3 -m unittest discover -s scripts/benchmarks -p test_radix_forward_shapes.py + python3 reports/runtime-kv-path-2026-10-09/qualification/test_curate_runs.py + python3 reports/runtime-kv-path-2026-10-09/qualification/test_run_suite.py + + docs: + name: Docs Lint + needs: plan + if: ${{ !cancelled() }} + runs-on: ${{ fromJSON(needs.plan.outputs.routes)['docs'] }} + # Full-history checkouts of this repository have taken up to 21 minutes. + timeout-minutes: 45 + steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + # Full history: a separate key family, so shallow jobs never restore it. + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-full-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-full-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-full-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 # Frozen source links require committed document provenance. + filter: blob:none # Old file contents are fetched only when read. + persist-credentials: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} + - name: Initialize pinned SDK documentation + run: git submodule update --init --depth 1 libs/mlx-swift-lm + - name: Test historical source-link validation + run: python3 scripts/test-docs-check-historical-links.py + - name: Test date-only freshness stamping + run: python3 scripts/test-docs-stamp.py + - name: Check freshness stamps, links, cited paths, orphans + run: ./scripts/docs-check.sh diff --git a/.github/workflows/component-changes.yml b/.github/workflows/component-changes.yml index 1d2e566fb8..fdb08b9745 100644 --- a/.github/workflows/component-changes.yml +++ b/.github/workflows/component-changes.yml @@ -5,10 +5,10 @@ on: outputs: provider: value: ${{ jobs.changes.outputs.provider }} - sdk: - value: ${{ jobs.changes.outputs.sdk }} cluster: value: ${{ jobs.changes.outputs.cluster }} + mimo_audio: + value: ${{ jobs.changes.outputs.mimo_audio }} permissions: contents: read @@ -21,8 +21,8 @@ jobs: runs-on: ubuntu-24.04 outputs: provider: ${{ steps.paths.outputs.provider }} - sdk: ${{ steps.paths.outputs.sdk }} cluster: ${{ steps.paths.outputs.cluster }} + mimo_audio: ${{ steps.paths.outputs.mimo_audio }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: diff --git a/.github/workflows/darkbloom-route.yml b/.github/workflows/darkbloom-route.yml index 4528c2c718..07aee13139 100644 --- a/.github/workflows/darkbloom-route.yml +++ b/.github/workflows/darkbloom-route.yml @@ -4,6 +4,9 @@ name: Darkbloom Route # plane grants one, otherwise the lane's fallback label. Callers run each job on # `fromJSON(needs.route.outputs.routes)['']`. Routing is off unless the # DARKBLOOM_ROUTING variable is exactly `on`; the plane can never fail this job. +# DARKBLOOM_MACOS_LANES, when set, caps the macOS jobs one run asks for: lanes +# are kept in the caller's order while they fit, and the others keep their +# fallback without asking. on: workflow_call: inputs: @@ -36,6 +39,7 @@ jobs: env: LANES: ${{ inputs.lanes }} ROUTING: ${{ vars.DARKBLOOM_ROUTING }} + MACOS_LANES: ${{ vars.DARKBLOOM_MACOS_LANES }} PLANE_URL: ${{ vars.DARKBLOOM_SANDBOX_URL }} REPOSITORY: ${{ github.repository }} EVENT_NAME: ${{ github.event_name }} @@ -75,7 +79,24 @@ jobs: --argjson count "$count" '. + [{$lane, $profile, $fallback, $count}]' <<<"$configured") done <<<"${LANES:-}" [ "$configured" != '[]' ] || configuration_error "no lanes are configured" - requested=$(jq -c '[.[] | select(.count > 0) | {lane, profile, count}]' <<<"$configured") + + # The macOS cap is a repository setting, not caller configuration: a + # value other than 0 to 99 asks for no macOS lane rather than failing. + macos_cap=${MACOS_LANES:-} + cap_note="" + if [ -n "$macos_cap" ] && ! [[ $macos_cap =~ ^(0|[1-9][0-9]?)$ ]]; then + cap_note=" DARKBLOOM_MACOS_LANES is not a number from 0 to 99, so no macOS lane was requested." + macos_cap=0 + fi + configured=$(jq -c --arg cap "$macos_cap" ' + reduce .[] as $entry ({used: 0, lanes: []}; + if $cap != "" and $entry.profile == "macos_arm64" and $entry.count > 0 + and .used + $entry.count > ($cap | tonumber) + then .lanes += [$entry + {capped: true}] + else .used += (if $entry.profile == "macos_arm64" then $entry.count else 0 end) + | .lanes += [$entry + {capped: false}] + end) | .lanes' <<<"$configured") + requested=$(jq -c '[.[] | select(.count > 0 and (.capped | not)) | {lane, profile, count}]' <<<"$configured") plane_url=${PLANE_URL:-https://api-sandbox.darkbloom.dev} body=$(mktemp) @@ -138,6 +159,7 @@ jobs: | ($plane_decisions[.lane] | if type == "object" then . else {} end) as $decision | if .count == 0 then .target = "fallback" | .reason = "not requested" elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason + elif .capped then .target = "fallback" | .reason = "over the macOS lane cap (DARKBLOOM_MACOS_LANES)" elif $decision.target == "darkbloom" and $decision.runs_on == $profiles[.profile] then .target = "darkbloom" | .reason = "granted" elif $decision.target == "fallback" @@ -148,6 +170,7 @@ jobs: routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions") echo "routes=$routes" >> "$GITHUB_OUTPUT" + note="$note$cap_note" echo "$note" jq -r '.[] | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason))"' <<<"$decisions" { diff --git a/.github/workflows/darkbloom-watchdog.yml b/.github/workflows/darkbloom-watchdog.yml new file mode 100644 index 0000000000..d7ed62e138 --- /dev/null +++ b/.github/workflows/darkbloom-watchdog.yml @@ -0,0 +1,296 @@ +name: Darkbloom Watchdog + +# Rescues runs stranded on Darkbloom: a job routed to Darkbloom can only run +# on a Darkbloom runner, so when one waits queued with no runner for +# DARKBLOOM_WATCHDOG_MINUTES (default 30) while Darkbloom makes no progress +# on the run, this cancels the run and re-runs the route job and its +# dependents (the whole run when the cancel interrupted other jobs). The new +# attempt's route job then keeps its fallback labels: the plane unreachable, +# or answering run_fallback_forced. It needs only GitHub and this +# repository's GITHUB_TOKEN, so it works while Darkbloom's plane is down. +# What it cannot see, it does not guess: a payer at its concurrency limit +# looks like a fault to it once nothing has moved for the whole wait. +# Darkbloom's own watchdog acts first (after 15 minutes, on the plane's +# evidence) and marks the run with a `Darkbloom watchdog` check run, which +# this leaves alone for 20 minutes. A run is rescued at most once, by either: +# stranded again, it is only cancelled. Off when the repository variable +# DARKBLOOM_WATCHDOG is `off`. +# +# Copy this file into the repository as .github/workflows/darkbloom-watchdog.yml, +# beside darkbloom-route.yml, unchanged. See README.md. +on: + schedule: + - cron: '*/10 * * * *' + workflow_dispatch: + +permissions: {} + +concurrency: + group: darkbloom-watchdog + cancel-in-progress: false + +jobs: + watch: + name: Rescue Stranded Runs + runs-on: ubuntu-24.04 + # A minute of jitter, then at most two rescues of three minutes each. + timeout-minutes: 12 + permissions: + actions: write + checks: write + steps: + - name: Cancel and re-run runs whose Darkbloom jobs are stranded + shell: bash + env: + GH_TOKEN: ${{ github.token }} + API_URL: ${{ github.api_url }} + REPOSITORY: ${{ github.repository }} + SELF_RUN_ID: ${{ github.run_id }} + WATCHDOG: ${{ vars.DARKBLOOM_WATCHDOG }} + MINUTES: ${{ vars.DARKBLOOM_WATCHDOG_MINUTES }} + ROUTE_JOB: ${{ vars.DARKBLOOM_ROUTE_JOB }} + APP_SLUG: ${{ vars.DARKBLOOM_APP_SLUG }} + run: | + set -euo pipefail + export LC_ALL=C + summary() { echo "$1"; echo "$1" >> "$GITHUB_STEP_SUMMARY"; } + configuration_error() { + echo "::error title=Darkbloom watchdog configuration::$1" + exit 1 + } + + if [ "${WATCHDOG:-}" = off ]; then + summary "The Darkbloom watchdog is off: DARKBLOOM_WATCHDOG is 'off'." + exit 0 + fi + minutes=${MINUTES:-30} + if ! [[ $minutes =~ ^[0-9]{1,4}$ ]] || ((10#$minutes < 15 || 10#$minutes > 1440)); then + configuration_error "DARKBLOOM_WATCHDOG_MINUTES must be 15 to 1440" + fi + minutes=$((10#$minutes)) + route_job=${ROUTE_JOB:-Select Runners} + api=${API_URL:-https://api.github.com} + [[ $api == https://* ]] || configuration_error "the API URL must start with https://" + [[ ${REPOSITORY:-} =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]] || configuration_error "no repository" + # A random delay, so that repositories and Darkbloom's rounds do not + # move in step. Tests set these. + jitter=${JITTER_SECONDS:-60} + poll=${POLL_SECONDS:-10} + cancel_wait=${CANCEL_WAIT_SECONDS:-120} + app=${APP_SLUG:-darkbloom-sandbox} + max_rescues=2 + rerun_title="Cancelled to re-run on the fallback runners" + cancel_title="Cancelled: rescued once already, not re-run" + sleep $((RANDOM % (jitter + 1))) + + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + # One API call: sets STATUS (000 when the transport failed); the + # body is in $tmp/body. + request() { # method path [JSON body] + local method=$1 path=$2 + if [ $# -ge 3 ]; then + set -- --header 'Content-Type: application/json' --data-binary "$3" + else + set -- + fi + STATUS=$(curl --disable --silent --show-error --proto '=https' --max-time 20 \ + --max-filesize 16777216 --user-agent darkbloom-watchdog/1 --request "$method" "$@" \ + --header "Authorization: Bearer $GH_TOKEN" --header 'Accept: application/vnd.github+json' \ + --header 'X-GitHub-Api-Version: 2022-11-28' --output "$tmp/body" --write-out '%{http_code}' \ + "${api%/}/repos/$REPOSITORY/$path") || STATUS=000 + } + # The repository's runs with `status` created in the last day, as + # one JSON array, up to 1,000; fails when GitHub does. + runs_with() { # status + local all='[]' page=1 count + while :; do + request GET "actions/runs?status=$1&created=%3E%3D$since&per_page=100&page=$page" + [ "$STATUS" = 200 ] || return 1 + all=$(jq -c --argjson all "$all" '$all + (.workflow_runs // [])' "$tmp/body") + count=$(jq '.workflow_runs // [] | length' "$tmp/body") + [ "$count" = 100 ] && [ "$page" -lt 10 ] || break + page=$((page + 1)) + done + echo "$all" + } + # The run's jobs (filter latest or all) as one JSON array, up to + # 1,000; fails when GitHub does. + jobs_of() { # run filter + local all='[]' page=1 count + while :; do + request GET "actions/runs/$1/jobs?filter=$2&per_page=100&page=$page" + [ "$STATUS" = 200 ] || return 1 + all=$(jq -c --argjson all "$all" '$all + (.jobs // [])' "$tmp/body") + count=$(jq '.jobs // [] | length' "$tmp/body") + [ "$count" = 100 ] && [ "$page" -lt 10 ] || break + page=$((page + 1)) + done + echo "$all" + } + # Waits up to $2 seconds for GitHub to report the run completed. + completed() { # run seconds + local deadline=$((SECONDS + $2)) + while :; do + request GET "actions/runs/$1" + [ "$STATUS" = 200 ] && [ "$(jq -r .status "$tmp/body")" = completed ] && return 0 + [ "$SECONDS" -lt "$deadline" ] || return 1 + sleep "$poll" + done + } + # Darkbloom's labels (self-hosted beside a darkbloom-* label), a + # GitHub time in Unix seconds (null when absent), a name safe to + # print (no workflow commands, no markup), and a marker check run. + # shellcheck disable=SC2016 # jq's variables + defs='def darkbloom: (.labels // [] | map(ascii_downcase)) + | index("self-hosted") != null and any(.[]; startswith("darkbloom-")); + def at: if type == "string" then sub("[.][0-9]+Z$"; "Z") | fromdateiso8601 else null end; + def clean: tostring | gsub("[^A-Za-z0-9 ._()/,+-]"; "?") | .[0:80]; + def marker($id): .check_runs[]? | select(.name == "Darkbloom watchdog" and .external_id == $id);' + + # Re-runs run $1 after its cancel: the route job and its dependents, + # or the whole run when it has no single route job or the cancel + # interrupted a job that started before the route job completed (a + # route job's rerun would leave it cancelled). Prints what it re-ran. + rerun() { # run attempt + local jobs route + jobs=$(jobs_of "$1" latest) || return 1 + route=$(jq -r --arg name "$route_job" --argjson attempt "$2" "$defs"' + [.[] | select((.name == $name or (.name | endswith(" / " + $name))) and .conclusion == "success")] as $r + | if ($r | length) != 1 then empty + else ($r[0].completed_at | at // 0) as $done + | if any(.[]; .run_attempt == $attempt and .conclusion == "cancelled" and (.runner_id // 0) != 0 + and ((.started_at | at) // 1e12) < $done) then empty else $r[0].id end + end' <<<"$jobs") + if [ -n "$route" ]; then + request POST "actions/jobs/$route/rerun" + what="its route job and dependents" + else + request POST "actions/runs/$1/rerun" + what="the whole run" + fi + case $STATUS in + 201) echo "$what" ;; + 403) echo "nothing: it is re-running already" ;; + *) return 1 ;; + esac + } + + now=$(date -u +%s) + since=$(date -u -d "@$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \ + || date -u -r "$((now - 86400))" +%Y-%m-%dT%H:%M:%SZ) + before=$((now - minutes * 60)) + failed=0 + acted=0 + runs='[]' + for status in in_progress queued; do + more=$(runs_with "$status") || { echo "::warning::Listing $status runs failed (HTTP $STATUS)"; exit 1; } + runs=$(jq -c --argjson more "$more" '. + $more' <<<"$runs") + done + + # Rescues this workflow cancelled and did not re-run (cut short + # between the two): cancelled runs changed in the last half hour + # whose current attempt carries this workflow's own marker. + cancelled=$(runs_with cancelled) || { echo "::warning::Listing cancelled runs failed (HTTP $STATUS)"; exit 1; } + resumable=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson recent "$((now - 1800))" "$defs"' + .[] | select((.id | tostring) != $self and ((.updated_at | at) // 0) >= $recent) + | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$cancelled") + while read -r run attempt sha; do + [ -n "$run" ] || continue + request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100" + [ "$STATUS" = 200 ] || continue + jq -e --arg id "run:$run:$attempt" --arg title "$rerun_title" "$defs"'[marker($id) + | select(.app.slug == "github-actions" and .output.title == $title)] | length > 0' \ + "$tmp/body" >/dev/null || continue + acted=1 + if what=$(rerun "$run" "$attempt"); then + summary "Run $run attempt $attempt: resumed its rescue, re-ran $what." + else + echo "::warning::Run $run: re-running it failed (HTTP $STATUS)" + failed=1 + fi + done <<<"$resumable" + + # Runs whose attempt started before the wait, other than this. + candidates=$(jq -r --arg self "${SELF_RUN_ID:-0}" --argjson before "$before" "$defs"' + unique_by(.id) | .[] | select((.id | tostring) != $self) + | select((.run_started_at // .created_at | at) as $t | $t != null and $t <= $before) + | "\(.id) \(.run_attempt) \(.head_sha)"' <<<"$runs") + rescues=0 + while read -r run attempt sha; do + [ -n "$run" ] || continue + jobs=$(jobs_of "$run" latest) || { echo "::warning::Run $run: listing its jobs failed"; failed=1; continue; } + # Stranded: no Darkbloom job of the run started (given a runner) + # or completed within the wait, and one of this attempt queued + # with no runner since before it: timed from the later of its + # creation and the attempt's last completion (a job behind + # `needs:` is queued only once those are done). + stranded=$(jq -r --argjson before "$before" --argjson attempt "$attempt" "$defs"' + ([.[] | select(.run_attempt == $attempt) | (.completed_at | at) // 0] | max // 0) as $last + | if any(.[]; darkbloom and ((((.runner_id // 0) != 0) and ((.started_at | at) // 0) > $before) + or ((.completed_at | at) // 0) > $before)) then "" + else [.[] | select(.run_attempt == $attempt and .status == "queued" and (.runner_id // 0) == 0 + and darkbloom and ([(.created_at | at) // 1e12, $last] | max) <= $before) | .name | clean] + | join(", ") end' <<<"$jobs") + [ -n "$stranded" ] || continue + request GET "commits/$sha/check-runs?check_name=Darkbloom%20watchdog&filter=all&per_page=100" + [ "$STATUS" = 200 ] || { echo "::warning::Run $run: reading its checks failed (HTTP $STATUS)"; failed=1; continue; } + # Darkbloom's watchdog (its App) marked this attempt within 20 + # minutes: it is rescuing it. + if jq -e --arg id "run:$run:$attempt" --arg app "$app" --argjson since "$((now - 1200))" "$defs"' + [marker($id) | select(.app.slug == $app and ((.started_at // .completed_at | at) // 0) >= $since)] + | length > 0' "$tmp/body" >/dev/null; then + summary "Run $run attempt $attempt: Darkbloom's watchdog is rescuing it." + continue + fi + # Rescued before, by either watchdog: a marker of an earlier + # attempt, or an earlier attempt's Darkbloom job cancelled with no + # runner after the whole wait. Then it is only cancelled. + marked=$(jq -r --arg run "run:$run:" --argjson attempt "$attempt" '[.check_runs[]? + | select(.name == "Darkbloom watchdog" and (.external_id // "" | startswith($run))) + | .external_id | ltrimstr($run) | tonumber? | select(. < $attempt)] | length > 0' "$tmp/body") + all=$(jobs_of "$run" all) || { echo "::warning::Run $run: listing its attempts failed"; failed=1; continue; } + once=$(jq -r --argjson attempt "$attempt" --argjson wait "$((minutes * 60))" --argjson marked "$marked" "$defs"' + $marked or any(.[]; .run_attempt < $attempt and .conclusion == "cancelled" and (.runner_id // 0) == 0 + and darkbloom and ((.completed_at | at) // 0) - ((.created_at | at) // 1e12) >= $wait)' <<<"$all") + if [ "$rescues" -ge "$max_rescues" ]; then + summary "Run $run attempt $attempt: stranded; left for the next round ($max_rescues rescues a round)." + continue + fi + # Nobody re-ran it since it was listed. + request GET "actions/runs/$run" + [ "$STATUS" = 200 ] && [ "$(jq -r .run_attempt "$tmp/body")" = "$attempt" ] || continue + rescues=$((rescues + 1)) + acted=1 + # Marked first: a rescue cut short after the cancel resumes next time. + title=$rerun_title + [ "$once" != true ] || title=$cancel_title + mark=$(jq -cn --arg sha "$sha" --arg id "run:$run:$attempt" --arg title "$title" --arg jobs "$stranded" '{ + name: "Darkbloom watchdog", head_sha: $sha, external_id: $id, status: "completed", + conclusion: "neutral", output: {title: $title, + summary: "A Darkbloom job of this run attempt got no runner (\($jobs)): the repository watchdog cancelled it."}}') + request POST check-runs "$mark" + [ "$STATUS" = 201 ] || { echo "::warning::Run $run: marking it failed (HTTP $STATUS)"; failed=1; continue; } + request POST "actions/runs/$run/cancel" + case $STATUS in + 202) ;; + 409) summary "Run $run attempt $attempt: someone else is cancelling it; not re-run."; continue ;; + *) echo "::warning::Run $run: cancelling it failed (HTTP $STATUS)"; failed=1; continue ;; + esac + if ! completed "$run" "$cancel_wait"; then + request POST "actions/runs/$run/force-cancel" + completed "$run" 60 || { echo "::warning::Run $run: GitHub did not cancel it"; failed=1; continue; } + fi + if [ "$once" = true ]; then + summary "Run $run attempt $attempt: cancelled ($stranded waited ${minutes}+ minutes for a Darkbloom runner); it was rescued once already, so it is not re-run again." + continue + fi + if what=$(rerun "$run" "$attempt"); then + summary "Run $run attempt $attempt: $stranded waited ${minutes}+ minutes for a Darkbloom runner; cancelled and re-ran $what on the fallback runners." + else + echo "::warning::Run $run: re-running it failed (HTTP $STATUS)" + failed=1 + fi + done <<<"$candidates" + [ "$acted" = 1 ] || summary "No run is stranded on Darkbloom." + exit "$failed" diff --git a/.github/workflows/docs-impact.yml b/.github/workflows/docs-impact.yml index 681d40640c..304a8723c2 100644 --- a/.github/workflows/docs-impact.yml +++ b/.github/workflows/docs-impact.yml @@ -1,7 +1,10 @@ name: Contribution Policy +# Pull requests into master only: dev keeps no contribution gates (CI (dev) +# runs only the tests). on: pull_request: + branches: [master, main] types: [opened, synchronize, reopened, labeled, unlabeled] permissions: @@ -58,6 +61,14 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 + # The diff needs commits and trees; old file contents are fetched only + # when read. Evidence tarballs and landing media are never read. + filter: blob:none + sparse-checkout: | + /* + !/docs/reports/evidence/**/*.gz + !/landing/public/media/ + sparse-checkout-cone-mode: false - name: Test documentation-impact validation run: python3 scripts/test-docs-impact-check.py - name: Check documentation impact diff --git a/.github/workflows/provider-plan.yml b/.github/workflows/provider-plan.yml new file mode 100644 index 0000000000..536d633213 --- /dev/null +++ b/.github/workflows/provider-plan.yml @@ -0,0 +1,160 @@ +name: Provider Plan + +# What one CI run tests and where, shared by CI (dev) and CI (master). The +# classifier selects the components a change touches; the tree lookup skips +# every test job when a successful run of the same workflow already tested +# this exact tree (scripts/ci-tested-tree.py); the route asks the Darkbloom +# plane once for every lane of the run (the plane routes a run attempt once), +# the caller's own Linux lanes included. +on: + workflow_call: + inputs: + linux_lanes: + description: The caller's own route lanes, one per line (darkbloom-route.yml format) + type: string + default: '' + outputs: + provider: + description: "'true' when the provider jobs run (selected, and the tree is untested)" + value: ${{ jobs.components.outputs.provider }} + cluster: + value: ${{ jobs.components.outputs.cluster }} + mimo_audio: + value: ${{ jobs.components.outputs.mimo_audio }} + changed_provider: + description: The classifier's provider selection, before the tree lookup + value: ${{ jobs.components.outputs.changed_provider }} + changed_cluster: + value: ${{ jobs.components.outputs.changed_cluster }} + changes_result: + value: ${{ jobs.components.outputs.changes_result }} + skip: + description: "'true' when a successful run already tested this tree" + value: ${{ jobs.tested.outputs.skip }} + tested_run: + value: ${{ jobs.tested.outputs.tested_run }} + tree: + value: ${{ jobs.tested.outputs.tree }} + base: + description: The tested change's base (`push` for a push) + value: ${{ jobs.tested.outputs.base }} + head: + value: ${{ jobs.tested.outputs.head }} + routes: + value: ${{ jobs.route.outputs.routes }} + +permissions: + contents: read + +jobs: + changes: + uses: ./.github/workflows/component-changes.yml + permissions: + contents: read + + tested: + name: Find an earlier test of this tree + needs: changes + if: ${{ !cancelled() && needs.changes.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + actions: read + outputs: + skip: ${{ steps.lookup.outputs.skip }} + tested_run: ${{ steps.lookup.outputs.tested_run }} + tree: ${{ steps.tree.outputs.tree }} + base: ${{ steps.tree.outputs.base }} + head: ${{ steps.tree.outputs.head }} + steps: + # On a pull request github.sha is its test merge commit of the event's + # base and head; on a push, the pushed commit. Only the lookup script is + # checked out. + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + sparse-checkout: scripts/ci-tested-tree.py + sparse-checkout-cone-mode: false + - name: Name the change this run tests + id: tree + env: + BASE: ${{ github.event.pull_request.base.sha || 'push' }} + HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + { + echo "tree=$(git rev-parse 'HEAD^{tree}')" + echo "base=$BASE" + echo "head=$HEAD" + } >> "$GITHUB_OUTPUT" + - name: Look for a successful run that tested it + id: lookup + env: + GITHUB_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + WORKFLOW_REF: ${{ github.workflow_ref }} + EVENT: ${{ github.event_name }} + SHA: ${{ github.sha }} + TREE: ${{ steps.tree.outputs.tree }} + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + SELECTED: provider=${{ needs.changes.outputs.provider }},cluster=${{ needs.changes.outputs.cluster }},mimo_audio=${{ needs.changes.outputs.mimo_audio }} + RUN_ID: ${{ github.run_id }} + run: | + python3 scripts/ci-tested-tree.py lookup --repository "$REPOSITORY" \ + --workflow-ref "$WORKFLOW_REF" --event "$EVENT" --sha "$SHA" --tree "$TREE" \ + --base "$BASE" --head "$HEAD" --components "$SELECTED" --run-id "$RUN_ID" + + # The components the test jobs run: the classifier's, or none when the tree + # was tested. A failed lookup has already answered "test". + components: + name: Choose the components to test + needs: [changes, tested] + if: ${{ !cancelled() }} + runs-on: ubuntu-24.04 + timeout-minutes: 2 + permissions: {} + outputs: + provider: ${{ steps.choose.outputs.provider }} + cluster: ${{ steps.choose.outputs.cluster }} + mimo_audio: ${{ steps.choose.outputs.mimo_audio }} + changed_provider: ${{ needs.changes.outputs.provider }} + changed_cluster: ${{ needs.changes.outputs.cluster }} + changes_result: ${{ needs.changes.result }} + steps: + - name: Choose the components to test + id: choose + env: + SKIP: ${{ needs.tested.outputs.skip }} + PROVIDER: ${{ needs.changes.outputs.provider }} + CLUSTER: ${{ needs.changes.outputs.cluster }} + MIMO_AUDIO: ${{ needs.changes.outputs.mimo_audio }} + run: | + if [ "$SKIP" = true ]; then PROVIDER=false CLUSTER=false MIMO_AUDIO=false; fi + { + echo "provider=$PROVIDER" + echo "cluster=$CLUSTER" + echo "mimo_audio=$MIMO_AUDIO" + } >> "$GITHUB_OUTPUT" + + # Chooses a Darkbloom Sandbox or the Blacksmith fallback for each lane. A lane + # is granted whole or falls back whole, so each job (each shard) has a lane + # of its own and falls back alone. The macOS lanes are listed in the order + # the DARKBLOOM_MACOS_LANES cap keeps them: the critical-path shards first. + # refresh-caches is the only build of a push whose tree was tested. + route: + needs: [components, tested] + if: ${{ !cancelled() }} + uses: ./.github/workflows/darkbloom-route.yml + permissions: {} + with: + lanes: | + ${{ inputs.linux_lanes }} + test-cluster-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} + test-provider-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.provider == 'true' && 1 || 0 }} + test-provider-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.provider == 'true' && 1 || 0 }} + test-cluster-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} + test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} + test-cluster-gpu-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} + test-cluster-gpu-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} + refresh-caches macos_arm64 blacksmith-12vcpu-macos-27 ${{ github.event_name == 'push' && needs.tested.outputs.skip == 'true' && (needs.components.outputs.changed_provider == 'true' || needs.components.outputs.changed_cluster == 'true') && 1 || 0 }} diff --git a/.github/workflows/ci.yml b/.github/workflows/provider-tests.yml similarity index 53% rename from .github/workflows/ci.yml rename to .github/workflows/provider-tests.yml index 87f1a7e096..d3d8537b8f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/provider-tests.yml @@ -1,10 +1,28 @@ -name: CI +name: Provider Tests +# The provider and cluster test jobs and the Provider Tests gate, shared by +# CI (dev) (.github/workflows/ci-dev.yml) and CI (master) +# (.github/workflows/ci-master.yml). Their plan (provider-plan.yml) chooses +# the components and the runners; pull requests and pushes run the same jobs. +# Only pushes save caches. on: - push: - # dev pushes save the build caches that pull requests into dev restore. - branches: [master, main, dev] - pull_request: + workflow_call: + inputs: + provider: {type: string, required: true} + cluster: {type: string, required: true} + mimo_audio: {type: string, required: true} + changed_provider: {type: string, required: true} + changed_cluster: {type: string, required: true} + changes_result: {type: string, required: true} + skip: {type: string, required: true} + tested_run: {type: string, required: true} + tree: {type: string, required: true} + base: {type: string, required: true} + head: {type: string, required: true} + routes: {type: string, required: true} + # true: restore only this recipe's builds (master: release-bound + # builds never reuse objects of another recipe or dependency set). + strict_cache: {type: boolean, default: false} permissions: contents: read @@ -14,162 +32,82 @@ permissions: # master; BuildEnvironmentTests checks that the build is the one requested. env: DARKBLOOM_RELEASE_ENVIRONMENT: prod - -# Only revisions of the same PR supersede each other; pushes stay independent. -concurrency: - group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # Only pushes to master and dev save caches. A pull request restores its + # base branch's entries and saves none (docs/developer/build.md#ci-caching). + SAVE_CACHES: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/dev') }} + # Every checkout but Docs Lint's skips the evidence tarballs and landing media + # (408 MB of the tree), which only Docs Lint reads. The rest of the evidence + # stays: provider-ci-cache.py hashes every tracked Package.swift. + CHECKOUT_SPARSE: | + /* + !/docs/reports/evidence/**/*.gz + !/landing/public/media/ jobs: - changes: - uses: ./.github/workflows/component-changes.yml - permissions: - contents: read - - # Chooses a Darkbloom Sandbox or the Blacksmith fallback for each read-only - # job below. It follows the classifier so only jobs that will run are - # requested, and still routes the unconditional jobs if the classifier fails. - # A lane is granted whole or falls back whole, so each shard has a lane of - # its own and gets a free Mac even when there is not one per shard. - route: - needs: changes - if: ${{ !cancelled() }} - uses: ./.github/workflows/darkbloom-route.yml - permissions: {} - with: - lanes: | - release-integrity linux_arm64 blacksmith-4vcpu-ubuntu-2404 - docs linux_arm64 blacksmith-4vcpu-ubuntu-2404 - test-provider-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-summary macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} - test-provider-sdk macos_arm64 blacksmith-12vcpu-macos-27 ${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }} - test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-gpu-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-gpu-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }} - - release-integrity: - name: Release Integrity - needs: route - runs-on: ${{ fromJSON(needs.route.outputs.routes)['release-integrity'] }} - timeout-minutes: 30 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - # A plain build of master must be prod and a plain build of dev must be - # dev. The target is the pull request's base branch, or the pushed branch. - - name: Check the provider's plain-build default for the target branch - env: - TARGET_BRANCH: ${{ github.base_ref || github.ref_name }} - run: | - python3 scripts/test-provider-build-default.py - python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH" - - name: Validate changelog fragments - run: | - python3 scripts/test-changelog.py - make changelog-check - - name: Check provider release and installer integrity - run: | - ./scripts/check-release-version.sh - python3 scripts/test-provider-release-resolution.py - python3 scripts/test-provider-release-resume.py - python3 scripts/test-provider-release-toolchain.py - python3 scripts/test-provider-release-cache.py - python3 scripts/test-prepare-metal-toolchain.py - python3 scripts/test-provider-release-pipeline.py - python3 scripts/test-provider-release-publication.py - python3 scripts/test-provider-release-notes.py - python3 scripts/test-provider-cluster-runtime-models.py - python3 scripts/test-release-dev-branch.py - python3 scripts/test-provider-release-artifact.py - python3 scripts/test-provider-signing-validation.py - python3 scripts/test-provider-identity.py - python3 scripts/test-provider-test-watchdog.py - python3 scripts/test-stage-test-metallib.py - python3 scripts/test-provider-ci-cache.py - python3 scripts/test-provider-ci-workflow.py - python3 scripts/test-provider-test-shards.py - python3 scripts/test-cluster-test-plan.py - python3 scripts/test-ci-component-paths.py - python3 scripts/test-darkbloom-route.py - python3 scripts/test-prepare-prompt-fixtures.py - python3 provider-swift/Tests/test_protocol_fixture_resources.py - python3 scripts/test-app-attest-entitlements.py - ./scripts/test-setup-macos-homebrew.sh - - name: Test advisory threat review with local HTTP fixtures - run: | - python3 .github/scripts/test-threat-model-review.py - python3 .github/scripts/test-threat-full-scan.py - python3 .github/scripts/test-threat-ensemble.py - python3 .github/scripts/test-threat-budget.py - python3 .github/scripts/test-threat-bedrock.py - python3 .github/scripts/test-threat-diagnostics.py - python3 .github/scripts/test-threat-integration-scope.py - - name: Test native GPU CI routing without a GPU - run: python3 scripts/test-native-gpu-ci.py - - name: Test model registry workflow with loopback HTTP - run: python3 scripts/test_model_registry_workflow.py - - name: Test bounded MiMo provider fixture provisioning offline - run: python3 scripts/test-prepare-mimo-provider-fixtures.py - - name: Test serving qualification evidence and catalogs without a GPU - run: python3 -m unittest discover -s scripts/serving_performance -t scripts -p 'test_*.py' - - name: Test actual-call and bounded timing receipts without a GPU - run: | - python3 -m unittest discover -s scripts/benchmarks -p test_radix_forward_shapes.py - python3 reports/runtime-kv-path-2026-10-09/qualification/test_curate_runs.py - python3 reports/runtime-kv-path-2026-10-09/qualification/test_run_suite.py - - docs: - name: Docs Lint - needs: route - runs-on: ${{ fromJSON(needs.route.outputs.routes)['docs'] }} - # Full-history checkouts of this repository have taken up to 21 minutes. - timeout-minutes: 45 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - fetch-depth: 0 # Frozen source links require committed document provenance. - - name: Initialize pinned SDK documentation - run: git submodule update --init --depth 1 libs/mlx-swift-lm - - name: Test historical source-link validation - run: python3 scripts/test-docs-check-historical-links.py - - name: Test date-only freshness stamping - run: python3 scripts/test-docs-stamp.py - - name: Check freshness stamps, links, cited paths, orphans - run: ./scripts/docs-check.sh - test-provider: # The provider suite runs in shards on separate Macs # (scripts/provider-test-shards.py), each routed through its own - # test-provider- lane above. Each shard runs its suites serially in - # one process. Shard 1 also runs the MLX-free test targets in one parallel - # process; shard 2 also runs Prompt Parity. The last shard runs every suite - # that no other shard selects, the isolated processes and the native gates - # below. Provider Unit Tests Summary checks that the shards together - # executed the full suite and reports coverage. + # test-provider- lane above. Each shard builds once and runs + # PROVIDER_TEST_PROCESSES selections at the same time, each serially in its + # own process (scripts/run-provider-tests.sh). Selection 1 also runs the + # MLX-free test targets in one parallel process; shard 1 also runs Prompt + # Parity. The last selection runs every suite that no other selection + # picks; the last shard then runs the isolated processes and the native + # gates below, alone. Each shard then checks that its selections executed + # exactly their plans (the last shard also that the plans cover the suite + # once) and reports its own coverage. name: Provider Unit Tests (shard ${{ matrix.shard }}) - needs: [changes, route] - if: ${{ needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-provider-{0}', matrix.shard)] }} + if: ${{ inputs.provider == 'true' }} + runs-on: ${{ fromJSON(inputs.routes)[format('test-provider-{0}', matrix.shard)] }} timeout-minutes: 60 strategy: # A failed shard does not cancel the other shards. fail-fast: false matrix: - shard: [1, 2, 3] + shard: [1, 2] steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive + persist-credentials: false + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} - name: Build provider CI prerequisites id: provider-ci-build uses: ./.github/actions/provider-ci-build with: lane: provider + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} # The provider lane builds with --enable-code-coverage. Every provider # process after this step writes its own profile here, and the report # step at the end of this job merges them. @@ -188,13 +126,28 @@ jobs: - name: Test profile inventory authentication in a terminal if: ${{ matrix.shard == strategy.job-total }} run: python3 scripts/test-profile-inventory-auth.py + # The pinned metadata downloads, named by their SHA-256; each script + # uses an entry only if its bytes still have the pinned digest. + - name: Restore verified MiMo metadata downloads + id: mimo-metadata-cache + if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ${{ runner.temp }}/mimo-metadata-cache + key: mimo-metadata-v1-${{ hashFiles('scripts/prepare-mimo-prompt-fixtures.py', 'scripts/prepare-mimo-audio-fixtures.py') }} - name: Prepare pinned public MiMo metadata and original corpus id: mimo-prompt-fixtures if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} run: | python3 scripts/test-prepare-mimo-image-http-fixtures.py - python3 scripts/prepare-mimo-prompt-fixtures.py --output "$RUNNER_TEMP/mimo-prompt-fixtures" --github-env "$GITHUB_ENV" - python3 scripts/prepare-mimo-image-http-fixtures.py --output "$RUNNER_TEMP/mimo-image-http-fixtures" --github-env "$GITHUB_ENV" + python3 scripts/prepare-mimo-prompt-fixtures.py --output "$RUNNER_TEMP/mimo-prompt-fixtures" --github-env "$GITHUB_ENV" --cache "$RUNNER_TEMP/mimo-metadata-cache" + python3 scripts/prepare-mimo-image-http-fixtures.py --output "$RUNNER_TEMP/mimo-image-http-fixtures" --github-env "$GITHUB_ENV" --cache "$RUNNER_TEMP/mimo-metadata-cache" + - name: Save verified MiMo metadata downloads + if: ${{ !cancelled() && env.SAVE_CACHES == 'true' && steps.mimo-prompt-fixtures.outcome == 'success' && steps.mimo-metadata-cache.outputs.cache-hit != 'true' }} + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: ${{ runner.temp }}/mimo-metadata-cache + key: ${{ steps.mimo-metadata-cache.outputs.cache-primary-key }} - name: Prepare bounded synthetic MiMo provider fixtures offline id: mimo-fixtures if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} @@ -208,6 +161,8 @@ jobs: env: MIMO_V26_PROVIDER_LIFETIME_METADATA_TESTS: '1' PROVIDER_TEST_SHARD: ${{ matrix.shard }}/${{ strategy.job-total }} + # Selections per shard, at the same time: 3 on a 12-vCPU runner. + PROVIDER_TEST_PROCESSES: '3' PROVIDER_TEST_REPORT_DIR: ${{ runner.temp }}/provider-unit-shard working-directory: provider-swift # Reuse the built bundle and matched metallib. The exact allocator @@ -222,15 +177,20 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: provider-test-diagnostics-${{ matrix.shard }} - path: ${{ runner.temp }}/provider-test-diagnostics + # The watchdog's diagnostics, and each process's whole output, which + # the runner prints only after all of the shard's processes end. + path: | + ${{ runner.temp }}/provider-test-diagnostics + ${{ runner.temp }}/provider-unit-shard/slot-*.out if-no-files-found: warn retention-days: 7 - # Prompt Parity runs once, in shard 2, against this shard's build. A - # failure fails the shard, and with it the Provider Tests gate. The - # summary checks each run's executed count against the suite list. + # Prompt Parity runs once, in shard 1 (the shard of selection + # PARITY_SHARD), against this shard's build. A failure fails the shard, + # and with it the Provider Tests gate. The summary checks each run's + # executed count against the suite list. - name: Verify public prompt golden vectors id: prompt-parity - if: ${{ !cancelled() && matrix.shard == 2 && steps.provider-ci-build.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 1 && steps.provider-ci-build.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' }} env: PROMPT_PARITY_SKIP_BUILD: '1' run: | @@ -241,7 +201,7 @@ jobs: python3 scripts/provider-test-shards.py counts parity ProductionPromptParityTests \ "$report/parity-prompt.log" "$report/shard-parity-prompt.json" - name: Verify pinned Nemotron prompts and numeric cache plans - if: ${{ !cancelled() && matrix.shard == 2 && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 1 && steps.provider-ci-build.outcome == 'success' }} run: | set -o pipefail report="$RUNNER_TEMP/provider-unit-shard" @@ -303,8 +263,10 @@ jobs: DARKBLOOM_PREFIX_CACHE: '0' DARKBLOOM_PREFIX_CACHE_MEMORY: '0' run: ../scripts/run-nested-suite.sh testGracefulDrainAfterServedRequestRetiresNativeOwnerWithinDeadline --no-parallel + # The 1.87 GB codec is fetched only when the audio gate's inputs changed + # (scripts/ci-component-paths.py MIMO_AUDIO) and on master pushes. - name: Restore pinned MiMo audio codec - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && inputs.mimo_audio == 'true' }} uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 id: mimo-audio-cache with: @@ -312,10 +274,10 @@ jobs: key: mimo-audio-source-v2-077033345d80eef3a315e8d394e0589667e80e4cdaba9bc5a7488410c6657265 - name: Prepare selected MiMo audio fixture id: mimo-audio-fixtures - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && inputs.mimo_audio == 'true' }} run: python3 scripts/prepare-mimo-audio-fixtures.py --cache "$RUNNER_TEMP/mimo-audio-source" --output "$RUNNER_TEMP/mimo-audio-fixtures" --github-env "$GITHUB_ENV" - name: Cache verified MiMo audio codec - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.mimo-audio-fixtures.outcome == 'success' && steps.mimo-audio-cache.outputs.cache-hit != 'true' }} + if: ${{ !cancelled() && env.SAVE_CACHES == 'true' && matrix.shard == strategy.job-total && steps.mimo-audio-fixtures.outcome == 'success' && steps.mimo-audio-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 with: path: ${{ runner.temp }}/mimo-audio-source @@ -332,8 +294,8 @@ jobs: if: ${{ !cancelled() && matrix.shard == strategy.job-total }} timeout-minutes: 2 run: ./scripts/test-install-atomic.sh - # Report-only coverage: each shard merges its own profiles, and Provider - # Unit Tests Summary merges the shards and writes the report. + # Report-only coverage: each shard merges its own profiles and writes + # its own report. - name: Merge shard coverage profiles if: ${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }} run: | @@ -347,84 +309,34 @@ jobs: echo "Merging ${#profiles[@]} provider coverage profiles" mkdir -p "$RUNNER_TEMP/provider-unit-shard" xcrun llvm-profdata merge -sparse -o "$RUNNER_TEMP/provider-unit-shard/provider.profdata" "${profiles[@]}" - - name: Upload shard counts, timings and coverage + # The full-suite audit, split by job: this shard's selections each ran + # exactly their plan, and the last shard checks that all plans cover + # `swift test list` once (scripts/provider-test-shards.py audit-job). + - name: Check this shard's selections against the suite list if: ${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: provider-unit-shard-${{ matrix.shard }} - path: | - ${{ runner.temp }}/provider-unit-shard/*.json - ${{ runner.temp }}/provider-unit-shard/*.xml - ${{ runner.temp }}/provider-unit-shard/provider.profdata - if-no-files-found: error - retention-days: 14 - - test-provider-summary: - # Checks the shards against the full suite list and reports coverage. - name: Provider Unit Tests Summary - needs: [changes, route, test-provider] - if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-summary'] }} - timeout-minutes: 30 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - # This restores the shards' build, or on a pull request the base - # branch's build, and rebuilds it from the same sources and flags. - # `swift test list` and llvm-cov read its binaries. - - name: Build provider CI prerequisites - id: provider-ci-build - uses: ./.github/actions/provider-ci-build - with: - lane: provider - - name: Download shard reports - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 - with: - pattern: provider-unit-shard-* - path: ${{ runner.temp }}/provider-unit-shards - - name: Check that the shards executed the full provider suite - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} working-directory: provider-swift + env: + PROVIDER_TEST_PROCESSES: '3' + SHARD: ${{ matrix.shard }}/${{ strategy.job-total }} run: | set -euo pipefail swift test list --skip-build > "$RUNNER_TEMP/provider-tests.txt" - python3 ../scripts/provider-test-shards.py audit "$RUNNER_TEMP/provider-tests.txt" "$RUNNER_TEMP/provider-unit-shards" - # Report-only: measured seconds per suite, the input for - # scripts/provider-test-shard-weights.json when the shards drift apart. - - name: Measure suite times for shard balance - if: ${{ !cancelled() }} - run: | - set -euo pipefail - mkdir -p "$RUNNER_TEMP/provider-test-shard-weights" - python3 scripts/provider-test-shards.py weights "$RUNNER_TEMP"/provider-unit-shards/*/shard-*.xml \ - > "$RUNNER_TEMP/provider-test-shard-weights/provider-test-shard-weights.json" - - name: Upload measured suite times - if: ${{ !cancelled() }} - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: provider-test-shard-weights - path: ${{ runner.temp }}/provider-test-shard-weights/provider-test-shard-weights.json - if-no-files-found: warn - retention-days: 14 + python3 ../scripts/provider-test-shards.py audit-job "$RUNNER_TEMP/provider-tests.txt" \ + "$RUNNER_TEMP/provider-unit-shard" "$SHARD" # Report-only. The test steps above keep their own exit codes, so a # coverage failure here cannot hide or replace a test failure. - name: Report provider coverage id: provider-coverage - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }} working-directory: provider-swift run: | set -euo pipefail shopt -s nullglob - profiles=("$RUNNER_TEMP"/provider-unit-shards/*/provider.profdata) - if [ "${#profiles[@]}" -eq 0 ]; then - echo "::error::No provider coverage profiles in $RUNNER_TEMP/provider-unit-shards" - exit 1 - fi - echo "Merging ${#profiles[@]} shard coverage profiles" + # This shard's processes only: the shards run at the same time, so + # no job sees the others' profiles. out="$RUNNER_TEMP/provider-coverage" mkdir -p "$out" - xcrun llvm-profdata merge -sparse -o "$out/provider.profdata" "${profiles[@]}" + cp "$RUNNER_TEMP/provider-unit-shard/provider.profdata" "$out/provider.profdata" bin=$(swift build --show-bin-path) # The test bundle holds the libraries and the executables the tests # import; the executables are added so their own code also counts. @@ -506,7 +418,7 @@ jobs: { cat "$out/provider-coverage-summary.md" echo - echo "Denominator: Swift lines and regions in \`provider-swift/Sources\`, from every provider test process in the Provider Unit Tests shards, Prompt Parity included; the Provider SDK Tests lane runs in another job and does not count." + echo "Denominator: Swift lines and regions in \`provider-swift/Sources\`, from this shard's provider test processes (each shard reports its own); Prompt Parity counts in shard 1." echo echo "Excluded: \`Tests/\`, \`.build/\` (dependencies and generated code), the \`libs/\` checkouts, and the one C++ file in \`ProviderMetallibControl\`, which is not instrumented; Swift has no branch counters, so branches are not reported." } >> "$GITHUB_STEP_SUMMARY" @@ -514,197 +426,201 @@ jobs: if: ${{ !cancelled() && steps.provider-coverage.outcome == 'success' }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: provider-coverage + name: provider-coverage-${{ matrix.shard }} path: | ${{ runner.temp }}/provider-coverage/provider-coverage.txt ${{ runner.temp }}/provider-coverage/provider-coverage.json ${{ runner.temp }}/provider-coverage/provider-coverage-summary.md if-no-files-found: error retention-days: 14 + - name: Upload shard counts, timings and coverage + if: ${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: provider-unit-shard-${{ matrix.shard }} + path: | + ${{ runner.temp }}/provider-unit-shard/*.json + ${{ runner.temp }}/provider-unit-shard/*.xml + ${{ runner.temp }}/provider-unit-shard/attempt-1-*.log + ${{ runner.temp }}/provider-unit-shard/provider.profdata + if-no-files-found: error + retention-days: 14 - test-provider-sdk: - # Not part of the Provider Tests gate. A pull request runs it only when an - # SDK-lane input changes (scripts/ci-component-paths.py SDK); every push to - # dev or master runs it, and a failure there notifies without blocking. - name: Provider SDK Tests - needs: [changes, route] - if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-sdk'] }} + test-cluster: + # DarkbloomClusterRuntimeTests in selections, each in its own process, on + # separate Macs (scripts/cluster-test-plan.py): every test without a + # switch, and the switched tests that pass on these runners. Shard 1 runs + # the base selection alone; shard 2 runs its ordered groups of selections + # at the same time. + name: Cluster Runtime Tests (shard ${{ matrix.shard }}) + if: ${{ inputs.cluster == 'true' }} + runs-on: ${{ fromJSON(inputs.routes)[format('test-cluster-{0}', matrix.shard)] }} timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2] steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive - - name: Build SDK CI prerequisites + persist-credentials: false + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} + - name: Build cluster test products id: provider-ci-build - timeout-minutes: 35 uses: ./.github/actions/provider-ci-build with: - lane: sdk - # FLAKE-ORDERING GUARD (audit fix, v0.8.0): every nested step below runs - # under !cancelled() with successful build/metallib prerequisites. A - # failed suite cannot hide a later correctness gate, and a failed build - # produces one attributable failure rather than cascading test failures. - - name: Verify DiffusionGemma artifact and expert reduction - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - run: ../../scripts/run-nested-suite.sh 'DiffusionGemma(ArtifactFixture|ExpertReduction)Tests' --no-parallel - # NOTE (v0.8.0): the guards below exist because these gates once - # reported GREEN while executing NOTHING. `Tests/BenchCBv2Tests` - # depended on the BenchCBv2 EXECUTABLE target, so SwiftPM routed the - # swift-testing pass at that binary, which rejects - # `--test-bundle-path` and exits — every `@Test` in the package was - # unreachable and only XCTestCase classes ran. `swift test` exits 0 in - # that state, which is why it went unnoticed. - # - # FIXED: BenchCBv2 is now split into a `BenchCBv2Core` library plus a - # thin executable shim, and the test target depends on the library. - # - # The guards STAY as a permanent tripwire. This failure mode is silent - # by construction — a dark suite and a passing one are - # indistinguishable by exit code — so any future change that re-routes - # the swift-testing pass must be RED here, not green. - # The suites below are already compiled by the `swift build - # --build-tests` action above but were never executed, so the paged-KV - # migration had no automated numerical gate. They add no compile time, - # only run time; one step each so a slow or failing suite is - # attributable straight from the job summary. They reuse the metallib - # placed by the step above. - # - # The bodies are ONE script (scripts/run-nested-suite.sh), which is what - # carries the executed-count and zero-skip tripwires. ALL six suites go - # through it — a bare `swift test --filter` here would bypass the - # tripwire and reintroduce the dark-gate hole the script closes (the - # safety and prompt-hash suites below used to run bare for exactly that - # reason). Inline copies of a check whose failure mode is silence are - # that many chances to edit one and miss the rest. - - name: Run nested MiMo media decode tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 - run: ../../scripts/run-nested-suite.sh 'MiMoV26(OpenRouterMedia|VisionWorkingSet|AudioWorkingSet|VisualDecodeMemory|EncodedVisualDecoder|EncodedAudioDecoder|EncodedAACAudio|EncodedAudiovisualDecoder)Tests|MiMoV26PixelsTests.test(RGB|Temporal|Invalid|Explicit)' --no-parallel - - name: Verify native historical retention policy - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 - run: ../../scripts/run-nested-suite.sh CBv2NativeHistoricalRetentionTests --no-parallel - - name: Verify demanded checkpoint scheduling and projection - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 - run: ../../scripts/run-nested-suite.sh CBv2DemandedCheckpointPartitionTests --no-parallel - - name: Verify demanded long range continuation and projection - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 - run: ../../scripts/run-nested-suite.sh CBv2DemandedCheckpointContinuationTests --no-parallel - - name: Prepare asymmetric tiny MiMo fixture for native retention - id: sdk-mimo-retention-fixture + lane: cluster + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} + - name: Run cluster runtime tests if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - run: python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-native-retention" --asymmetric - - name: Verify native retained frontier after donor retirement - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.sdk-mimo-retention-fixture.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 + timeout-minutes: 40 env: - MIMO_V26_SERIAL_NATIVE_TESTS: '1' - MIMO_V26_SERIAL_LOAD_FIXTURES: ${{ runner.temp }}/mimo-native-retention - run: ../../scripts/run-nested-suite.sh MiMoV26NativeHistoricalRetentionTests.testDemandedMiddleFrontierSurvivesNativePublicationAndReopenedFork --no-parallel - - name: Prepare tiny MiMo fixture for media-to-text isolation - id: sdk-mimo-isolation-fixture + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run blocking "$SHARD" + + test-cluster-gpu: + # The switched cluster runtime tests these runners cannot pass, the long + # ones and the benchmarks (scripts/cluster-test-plan.py). They run and + # report whenever the cluster jobs run; a failure does not fail the + # workflow. + name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) + if: ${{ inputs.cluster == 'true' }} + runs-on: ${{ fromJSON(inputs.routes)[format('test-cluster-gpu-{0}', matrix.shard)] }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + shard: [1, 2] + steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + persist-credentials: false + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} + - name: Build cluster test products + id: provider-ci-build + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} + - name: Run non-blocking cluster GPU tests if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - run: python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-media-isolation" - - name: Verify media refusal leaves the native text engine usable - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.sdk-mimo-isolation-fixture.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 5 + continue-on-error: true + timeout-minutes: 40 env: - MIMO_V26_SERIAL_NATIVE_TESTS: '1' - MIMO_V26_NATIVE_MEDIA_DEADLINE_TESTS: '1' - MIMO_V26_SERIAL_LOAD_FIXTURES: ${{ runner.temp }}/mimo-media-isolation - run: ../../scripts/run-nested-suite.sh MiMoV26NativeMediaDeadlineTests --no-parallel - - name: Run nested paged safety tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Runtime smoke over the JIT-compiled paged Metal kernels. - timeout-minutes: 10 - run: ../../scripts/run-nested-suite.sh CBv2PagedSafetyTests - - name: Run nested prompt-hash tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Prefix-cache prompt-hash identity; pure Swift. - timeout-minutes: 10 - run: ../../scripts/run-nested-suite.sh CBv2PrefixCacheHasherTests - - name: Run nested paged eligibility tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Pure Swift threadgroup-budget arithmetic; no GPU dispatch. - timeout-minutes: 5 - run: ../../scripts/run-nested-suite.sh CBv2PagedEligibilityTests - - name: Run nested paged backend tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Pool bookkeeping, per-sequence page tables, windowed rings, - # reservation admission, backend lifecycle. Small MLX arrays only. - timeout-minutes: 10 - run: ../../scripts/run-nested-suite.sh CBv2PagedBackendTests - - name: Run nested paged kernel parity tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Heaviest of the set: fp32 decode-kernel parity, bitwise - # batch-composition invariance, and a 200-step greedy token match. - # Dispatches the JIT-compiled Metal kernels, exactly as - # CBv2PagedSafetyTests' runtimeSmoke already does in this job. - timeout-minutes: 20 - # The composition assertion opts in only in its own test process; - # both invocations retain the nonempty/no-skips tripwires. - run: ../../scripts/run-paged-kernel-tests.sh - - name: Run nested KV-sharing contiguous/paged parity tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - # Two-arm differential over TinyTestModel's KV-sharing variant. The - # paged arm used to XCTSkip when the backend was unavailable; the - # runner script now FAILS on any skip, because "paged unavailable on - # the gate runner" is precisely the condition this lane must not be - # green under. - timeout-minutes: 10 - run: ../../scripts/run-nested-suite.sh CBv2KVSharingParityTests - - name: Run Nemotron production SDK gates - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - working-directory: libs/mlx-swift-lm - timeout-minutes: 20 - run: | - # Each filter has its own nonzero/no-skip tripwire. Continue after a - # failure so one broken suite cannot hide another unexecuted gate. - onboarding_failed=0 - for suite in SSMDecodeBoundsTests NemotronHTests \ - NemotronH35BackendParityTests NemotronH35StorageParityTests \ - NemotronH35MTPTests NemotronH35MTPPrimingTests \ - MutableInputKernelTests MutableInputExportTests \ - CBv2QwenMTPIntegrationTests CBv2MTPDepthControllerTests \ - PagedMTPBatchedColumnsTests CBv2CompleteCheckpointEngineTests \ - NemotronH35ProductionDefaultsTests \ - OpenAIServiceTests ToolCallParserIntegrationTests; do - if ! ../../scripts/run-nested-suite.sh "$suite"; then - onboarding_failed=1 - fi - done - exit "$onboarding_failed" + SHARD: ${{ matrix.shard }} + run: python3 scripts/cluster-test-plan.py run nonblocking "$SHARD" - test-cluster-checks: - # The model-free cluster check runners. Each compiles its own source closure - # (the capability runner links the actual Runtime and MLX, but executes only - # metadata and argument checks) and runs it on the retained fixtures: no GPU, - # no model load, no weights. Every runner runs even after another fails. - name: Cluster Metadata Checks - needs: [changes, route] - if: ${{ needs.changes.outputs.cluster == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-checks'] }} + test-cluster-focused: + # The model-free cluster check runners on one Mac: first the metadata + # runners with their retained release build of the cluster runtime and MLX + # (each compiles its own source closure and runs on the retained fixtures: + # no GPU, no model load, no weights; every runner runs even after another + # fails), then the other runner scripts under libs/darkbloom-cluster/Tests + # (scripts/cluster-test-plan.py focused lane). + name: Cluster Focused Checks + if: ${{ inputs.cluster == 'true' }} + runs-on: ${{ fromJSON(inputs.routes)['test-cluster-focused'] }} timeout-minutes: 60 steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: submodules: recursive + persist-credentials: false + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: '3.12.10' @@ -715,7 +631,8 @@ jobs: # reused across runs: SwiftPM rebuilds what changed, and source timestamps # are restored only for files whose contents match the cached build's # (scripts/provider-release-cache.py). The key binds the toolchain, the - # package manifests, the submodule pins, the runner script and the paths. + # package manifests, the submodule pins, the runner script and the paths; + # it drops `git describe` text, which depends on the refs a cached .git holds. - name: Resolve cluster metadata build cache key id: cluster-build-key if: ${{ steps.toolchain.outcome == 'success' }} @@ -724,7 +641,7 @@ jobs: run: | set -euo pipefail identity=$( { swift --version 2>&1; xcodebuild -version; xcrun --show-sdk-path; \ - git submodule status --recursive; echo "$GITHUB_WORKSPACE $RUNNER_TEMP $MANIFESTS"; } | shasum -a 256 | cut -c1-32) + git submodule status --recursive | awk '{print $1, $2}'; echo "$GITHUB_WORKSPACE $RUNNER_TEMP $MANIFESTS"; } | shasum -a 256 | cut -c1-32) echo "prefix=cluster-metadata-release-v1-$identity-" >> "$GITHUB_OUTPUT" echo "key=cluster-metadata-release-v1-$identity-$GITHUB_SHA" >> "$GITHUB_OUTPUT" - name: Restore cluster metadata build @@ -760,15 +677,14 @@ jobs: DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata run: bash libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh - # Pushes save the cluster build; a pull request saves it only when it - # restored nothing (as the provider lane's Swift build). + # Only pushes to master and dev save the cluster build (SAVE_CACHES). - name: Record source timestamps for the cluster build - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} + if: ${{ !cancelled() && env.SAVE_CACHES == 'true' && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} run: | python3 scripts/provider-release-cache.py snapshot-mtimes cp provider-swift/.build/provider-release-source-mtimes.json "$RUNNER_TEMP/cluster-native-metadata/" - name: Upload cluster metadata build cache - if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '') }} + if: ${{ !cancelled() && env.SAVE_CACHES == 'true' && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ${{ runner.temp }}/cluster-native-metadata @@ -791,84 +707,6 @@ jobs: - name: Run cluster onboarding checks if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh - - test-cluster: - # DarkbloomClusterRuntimeTests in selections, each in its own process, on - # separate Macs (scripts/cluster-test-plan.py): every test without a - # switch, and the switched tests that pass on these runners. - name: Cluster Runtime Tests (shard ${{ matrix.shard }}) - needs: [changes, route] - if: ${{ needs.changes.outputs.cluster == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-cluster-{0}', matrix.shard)] }} - timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - shard: [1, 2, 3] - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - - name: Build cluster test products - id: provider-ci-build - uses: ./.github/actions/provider-ci-build - with: - lane: cluster - - name: Run cluster runtime tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - timeout-minutes: 40 - env: - SHARD: ${{ matrix.shard }} - run: python3 scripts/cluster-test-plan.py run blocking "$SHARD" - - test-cluster-gpu: - # The switched cluster runtime tests these runners cannot pass, the long - # ones and the benchmarks (scripts/cluster-test-plan.py). They run and - # report on every pull request; a failure does not fail the workflow. - name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) - needs: [changes, route] - if: ${{ needs.changes.outputs.cluster == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)[format('test-cluster-gpu-{0}', matrix.shard)] }} - timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - shard: [1, 2] - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - - name: Build cluster test products - id: provider-ci-build - uses: ./.github/actions/provider-ci-build - with: - lane: cluster - - name: Run non-blocking cluster GPU tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} - continue-on-error: true - timeout-minutes: 40 - env: - SHARD: ${{ matrix.shard }} - run: python3 scripts/cluster-test-plan.py run nonblocking "$SHARD" - - test-cluster-focused: - # The model-free runner scripts under libs/darkbloom-cluster/Tests that - # Cluster Metadata Checks does not run (scripts/cluster-test-plan.py). - name: Cluster Focused Checks - needs: [changes, route] - if: ${{ needs.changes.outputs.cluster == 'true' }} - runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-focused'] }} - timeout-minutes: 60 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - submodules: recursive - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: '3.12.10' - - name: Select SDK 27 provider toolchain - id: toolchain - run: ./scripts/prepare-provider-release-toolchain.sh - name: Run cluster focused checks if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} timeout-minutes: 40 @@ -877,29 +715,36 @@ jobs: provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 - needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused] + needs: [test-provider, test-cluster, test-cluster-focused] if: ${{ always() }} + permissions: + contents: read steps: - name: Require selected provider lanes or verified intentional skips env: - CHANGES_RESULT: ${{ needs.changes.result }} - PROVIDER_CHANGED: ${{ needs.changes.outputs.provider }} - CLUSTER_CHANGED: ${{ needs.changes.outputs.cluster }} + CHANGES_RESULT: ${{ inputs.changes_result }} + SKIP: ${{ inputs.skip }} + TESTED_RUN: ${{ inputs.tested_run }} + PROVIDER_CHANGED: ${{ inputs.provider }} + CLUSTER_CHANGED: ${{ inputs.cluster }} UNIT_RESULT: ${{ needs.test-provider.result }} - SUMMARY_RESULT: ${{ needs.test-provider-summary.result }} CLUSTER_RESULT: ${{ needs.test-cluster.result }} CLUSTER_FOCUSED_RESULT: ${{ needs.test-cluster-focused.result }} run: | test "$CHANGES_RESULT" = success + # A tree that a successful run of this workflow already tested runs + # no test job here (provider-plan.yml); the plan then selects none. + if [ "$SKIP" = true ]; then + echo "::notice title=Tested once::This tree passed in $TESTED_RUN; no test job ran." + fi case "$PROVIDER_CHANGED" in true) expected=success ;; false) expected=skipped ;; *) exit 1 ;; esac test "$UNIT_RESULT" = "$expected" - test "$SUMMARY_RESULT" = "$expected" - # The cluster jobs run only when their inputs changed (and on - # pushes); a skip passes only when the classifier did not select them. + # The cluster jobs run only when their inputs changed; a skip passes + # only when the classifier did not select them. case "$CLUSTER_CHANGED" in true) cluster_expected=success ;; false) cluster_expected=skipped ;; @@ -907,3 +752,109 @@ jobs: esac test "$CLUSTER_RESULT" = "$cluster_expected" test "$CLUSTER_FOCUSED_RESULT" = "$cluster_expected" + # The CI plans run on dev too, not only in master's Release Integrity: + # the cluster plan's audit against the sources and this workflow, the + # provider shard plan, the component classifier, the tested-change + # lookup, the route and the workflow pins. Python only; no build. They + # run even when a test job failed. + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + if: ${{ !cancelled() }} + with: + persist-credentials: false + filter: blob:none + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Check the CI plans + if: ${{ !cancelled() }} + run: | + python3 scripts/cluster-test-plan.py audit + python3 scripts/test-cluster-test-plan.py + python3 scripts/test-provider-test-shards.py + python3 scripts/test-ci-component-paths.py + python3 scripts/test-ci-tested-tree.py + python3 scripts/test-darkbloom-route.py + python3 scripts/test-provider-ci-workflow.py + # The record a later run of the same change finds (scripts/ci-tested-tree.py): + # the tree, the event's base and head, and the components that ran. It + # counts only once the whole run succeeded. A run that tested nothing + # records nothing. + - name: Name the record of the change these tests passed + id: record + if: ${{ inputs.skip != 'true' && (inputs.provider == 'true' || inputs.cluster == 'true') }} + env: + TREE: ${{ inputs.tree }} + BASE: ${{ inputs.base }} + HEAD: ${{ inputs.head }} + RAN: provider=${{ inputs.provider }},cluster=${{ inputs.cluster }},mimo_audio=${{ inputs.mimo_audio }} + run: | + name=$(python3 scripts/ci-tested-tree.py name --tree "$TREE" --base "$BASE" --head "$HEAD" --components "$RAN") + mkdir -p "$RUNNER_TEMP/tested-change" + printf '%s\n' "$name" > "$RUNNER_TEMP/tested-change/record" + echo "name=$name" >> "$GITHUB_OUTPUT" + - name: Upload the record + if: ${{ inputs.skip != 'true' && (inputs.provider == 'true' || inputs.cluster == 'true') }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ steps.record.outputs.name }} + path: ${{ runner.temp }}/tested-change/record + if-no-files-found: error + retention-days: 30 + + # A push whose tree a pull request run already tested runs no test job. This + # one build-only job refreshes the branch's build caches instead (the loose + # tier makes it incremental), for the components the push changed. + refresh-caches: + name: Refresh build caches + if: ${{ github.event_name == 'push' && inputs.skip == 'true' && (inputs.changed_provider == 'true' || inputs.changed_cluster == 'true') }} + runs-on: ${{ fromJSON(inputs.routes)['refresh-caches'] }} + timeout-minutes: 60 + steps: + - name: Select today's .git cache + id: git-day + run: | + day=$(date -u +%F) + echo "day=$day" >> "$GITHUB_OUTPUT" + echo "month=${day%-*}" >> "$GITHUB_OUTPUT" + echo "actions/cache compressor: $(command -v zstd >/dev/null && echo zstd || echo gzip)" + - name: Restore the newest saved .git + id: git-cache + uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: git-v1-${{ runner.os }}-${{ steps.git-day.outputs.day }} + restore-keys: | + git-v1-${{ runner.os }}-${{ steps.git-day.outputs.month }}- + git-v1-${{ runner.os }}- + - name: Discard a damaged cached .git + run: | + if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git + fi + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + submodules: recursive + persist-credentials: false + sparse-checkout: ${{ env.CHECKOUT_SPARSE }} + sparse-checkout-cone-mode: false + - name: Save .git for later runs + if: env.SAVE_CACHES == 'true' && steps.git-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + with: + path: .git + key: ${{ steps.git-cache.outputs.cache-primary-key }} + - name: Build provider test products and save their caches + if: ${{ inputs.changed_provider == 'true' }} + uses: ./.github/actions/provider-ci-build + with: + lane: provider + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} + - name: Build cluster test products and save their caches + if: ${{ !cancelled() && inputs.changed_cluster == 'true' }} + uses: ./.github/actions/provider-ci-build + with: + lane: cluster + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} diff --git a/CHANGELOG.md b/CHANGELOG.md index eaf320c1ff..967b43b21f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,409 @@ or console deployment, feature activation, model promotion or hardware qualification. Sections marked historical retain the original candidate's qualification, opt-in and deployment limits rather than claiming activation. -## v0.10.6 — candidate (unpublished) +## v0.10.7 — candidate (unpublished) -Prepared on 2026-10-31; tagging and publication are separate steps. +Prepared on 2026-11-03; tagging and publication are separate steps. + +### Upgrade and rollout notes + +- Both Macs of a pair must update to 0.10.7. The Gemma 4 and MiMo-V2.6-Flash plans change (#1706, #1707, #1715), as does the Qwen tensor-parallel control wire (#1727), and a pair whose Macs run different builds refuses to pair: it fails closed until both Macs run the same release. +- A pair on 0.10.6 cannot update itself into 0.10.7: its cluster service predates the pair's coordinated update. On each pair, once: run `darkbloom update` on both Macs, then log out and back in on both (or restart them), as `docs/provider/two-mac-cluster.md` ("Updating Darkbloom on the pair") describes. From 0.10.7 on, the two Macs of a pair update together by themselves (#1702). If `darkbloom cluster` then says that a Qwen pair of two different Macs, which 0.10.6 saved with unequal tensor-parallel shares, is not offered for pairing, press `m` and choose the model again: it is planned with equal shares and registers (#1723). +- Gemma 4 and MiMo-V2.6-Flash tensor parallel are public (#1736): `ClusterPublicModels` declares `gemma-4-26b-qat-4bit` and `mimo-v2.6-flash-mopd` in pipeline and tensor parallel, as it does GLM-5.3-Flash and Qwen3.8-27B, and MiMo-V2.6-Flash's speculative pipeline too, so this release's cluster runtime facts carry their pair-serving grants and parity qualifications. Their tensor parallel is in this build (#1706, #1707, #1716), and a pair chooses it only on tensor parallel's own measured speed and only where it keeps every feature of the mode it would replace (#1715), so normal setups keep the pipeline for now. Speed on a real pair is not measured for either model's tensor parallel, and MiMo has no tensor-parallel qualification record yet. The entry "MiMo-V2.6-Flash and Gemma 4 26B QAT serve public cluster traffic" below says their tensor parallel serves once its code is in the build: in 0.10.7 it is. +- `darkbloom update --rollback` (#1729) puts back the release a Mac ran before its last update (0.10.6, after this update) and quarantines the one it leaves, without contacting a coordinator. It refuses on a Mac that serves in a pair: stop that Mac's cluster service first. The other Mac follows a rollback only to a release that has #1739, so a pair rolled back to 0.10.6 needs the rollback on each Mac. +- The operator's enabled-model filter wins over coordinator model changes (#1730): with `enabled_models` set, a coordinator `load_model` or `prefetch_model` outside it is refused (`model_not_selected`), and a provider no longer moves to a new build of a model by itself; `darkbloom switch` takes one. +- On one Mac, Gemma 4 replies keep the space before punctuation (#1693) and characters outside its vocabulary (#1703), with the same token IDs and cache keys, and a client `stop` sequence matches only the answer's `content`, not reasoning (#1650). +- The registration is the one 0.10.6 sent: the same fields and a `darkbloom_cluster_runtime_v2` block, carried while `PROD_CLUSTER_RUNTIME_ENABLED` is `true`. After the tag the platform snapshots its provider contracts from the tagged commit and sets `LatestProviderVersion` to `0.10.7`. +- MLX pins: `libs/mlx` and the nested `mlx` (`72dffa2d`) and `libs/mlx-swift` (`c633d221`) are unchanged from v0.10.6. `libs/mlx-swift-lm` moves from `7933a0fa` to `32f5c744`, its fork's `main` (SDK #370, #371, #375 to #377 and #379 to #384). It changes Swift files only, and the one Metal kernel it adds, an FP32-output variant of MiMo's decode down projection, compiles at run time (`MLXFast.metalKernel`), not into `mlx.metallib`, so the tag build's `metallib_hash` should equal v0.10.6's `98bab9d7…614be`. Complete SSD checkpoints stay per build: 0.10.7 does not restore those 0.10.6 wrote. +- The 39 entries below are the pending fragments rendered verbatim, in filename order. #1711 (a latent GPT-OSS cache-metadata fix), #1743 (two race fixes; one keeps `darkbloom cluster stop` from failing with "could not save the stop request") and the CI and test PRs #1665, #1691, #1733, #1737, #1741, #1747, #1749, #1750 and #1753 have no entry. + +### App Attest restart covers the first episode after an update + +- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At serve start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple call of a stored key that Apple attested, or an App Attest grant left by an unclean exit. All other conditions stay the same. +- A Mac whose previous provider was itself reporting `is_supported_false` has no such evidence, so it still waits for the coordinator to grant App Attest again. + +### App Attest recovers by itself after a self-update + +- A provider that launchd runs as its provider job now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. +- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. If the new process still reports unsupported, it does not restart again until the coordinator verifies the Mac again. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. Cluster members never restart for it. +- The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. +- The local provider log gets an `App Attest entitlement evidence` line at startup and at each `is_supported_false` answer: the start reason, the App Attest entitlements of the running process and of the code on disk, and the executable's modification time relative to the process start. It is not sent to the coordinator. + +### Cache restores finish sooner + +- Restoring a prefix-cache checkpoint decodes its older attention rows from the + default `balanced` checkpoint precision on the CPU. The decoder now checks each + row for values its native type cannot hold once per row instead of once per + eight values, with the same bytes and the same refusals. On Gemma 4 26B + follow-up requests served from the SSD cache, time to first token fell by about + 0.2 s per restore (about 25% over an 11-request conversation on an M3 Ultra), + and responses that save a checkpoint also end about 0.2 s sooner. Output is + unchanged. + +### Responses that save a cache checkpoint finish sooner + +- Saving a prefix-cache checkpoint encodes its older attention rows at the default + `balanced` checkpoint precision. That encoding now prepares its buffers and its + check once per segment instead of once per row and writes the same bytes. On a + Gemma 4 26B request that saves a checkpoint, the end of the response arrived + about 0.7 s sooner (1.7–2.0 s → 1.0–1.2 s on an M3 Ultra), with identical + output. Requests that save no checkpoint are unchanged. + +### Pair Macs set up with `darkbloom cluster` update themselves + +- A Mac set up with `darkbloom cluster` now updates itself, as a single Mac does: with `auto_update` on (the default) and without `DARKBLOOM_NO_UPDATE_CHECK`, its cluster service checks the coordinator's latest release every 30 minutes, at the pair's update slot, which both Macs derive from their pairing's cluster ID. +- Each Mac downloads, verifies and stages the release while the pair serves. Only once both Macs have it does the pair stop taking new requests; the Mac that serves the pair finishes its accepted requests (at most 120 seconds, never cancelling one), then both Macs install the release and restart their cluster services, and the cluster sets itself up again for the new release with no command run. +- A pair under constant traffic updates too: once it takes no new requests, the accepted ones finish. A pair still running a request at the bound takes requests again and tries at the next slot. A release one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. +- An installed release is promoted once its cluster service has stayed healthy for 10 minutes; three starts of its service that end on their own restore the previous release and quarantine the new one, as the watchdog does for a single Mac. +- Before a Mac restarts into an installed release, its cluster service runs the new `darkbloom --version` once (at most 30 seconds). A release that does not answer with its version is never restarted into: the Mac restores the previous release at once, quarantines the new one and starts its cluster service again, so a release that cannot start no longer leaves the Mac with nothing to roll it back. +- `darkbloom update` on a cluster Mac installs the release and then restarts the cluster service into it together with the other Mac, after the pair drained; logging out and back in is no longer needed. Run it on both Macs (or let the other Mac update at the next slot); the first Mac waits up to 15 minutes for the second, also when automatic updates are off. A Mac whose partner has automatic updates off downloads nothing at the slot. +- A pair that serves on the leader's local API, or a Mac that serves alone, is not drained for an update yet: it does not update while it serves, and a cluster set to serve locally (`darkbloom cluster local`) or a Mac serving alone downloads nothing at the slot. +- A cluster service started by an earlier release does none of this: to reach this release, run `darkbloom update` on both Macs, then log out and back in on both (or restart them) once. + +### Tensor parallel only where it keeps every feature + +- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. +- Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix and SSD reuse included, so its measured speed decides. MiMo's tensor parallel decodes in speculative rounds, so it keeps every feature of the speculative pipeline and its measured speed decides; only where the plain pipeline is the mode it would replace do that pipeline's batch lanes keep it. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop batch lanes up to 8 (it serves 1) that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". +- Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. +- Qwen and GLM plans are unchanged. + +### Simpler two-Mac cluster setup + +- `darkbloom cluster` setup says far less: four steps (Connect, Pair, Model, Start), a line per thing that happened, + and the next thing to do last. Every choice is a list (↑↓ and enter, as `darkbloom start` picks models; numbered in + plain transcripts); q or Esc cancels. +- The model list shows only the models approved for clusters (GLM-5.3-Flash, Qwen3.8 27B, MiMo-V2.6-Flash and + Gemma 4 26B QAT) that the two Macs can serve, each with its size and its split: tensor parallel or pipeline. The + serving lines name the split too. +- The Mac you set up on leads and keeps leading: every plan puts rank 0 on it, the cluster service's own re-plans + included, so a pair set up with 0.10.6 whose other Mac took over leading moves back at its next plan. +- macOS's password and Local Network prompts come at stated moments (sudo in the terminal over SSH); both Macs ask + about Darkbloom's Local Network access right after pairing, and the setup waits until Allow or q. +- Both Macs confirm the pairing code; the Mac that follows only shows the status. The serving line says whether the + pair earns through Darkbloom or serves locally only. +- `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. + +### Qwen pairs of two different Macs register with the coordinator + +- Affected: a pair of two different Macs set up with `darkbloom cluster` to serve through Darkbloom, with a Qwen model planned in tensor parallel. The planner gave the faster Mac the larger share of every layer (for example 2:1 on an M3 Ultra and an M5 Max), and the coordinator registration cannot name unequal shares yet. Both Macs still said `Registered with the coordinator as a cluster member`, then each Mac's part refused to register ("The saved roster registration is not valid for this Mac: invalidPlan"), the pair fell back to the leader's local API, and the coordinator never formed it or routed it a request. This hit Qwen3.8 27B, which pairs only in tensor parallel, and Qwen3.5 9B where tensor parallel was chosen. GLM-5.3-Flash, pipeline splits and two identical Macs were not affected. +- A pair served through Darkbloom is now planned with equal tensor-parallel shares, so it registers and is routed like a pair of identical Macs; on two different Macs the slower one sets the pace. A pair that serves you alone (`darkbloom cluster local`) keeps the faster unequal split. +- A setup saved with unequal shares (by 0.10.6, or a local cluster switched to Darkbloom with `p`) is not offered for pairing, and the leader says why before it stops either Mac's part: `Not offered for pairing: this Mac's check refused it: Unequal tensor-parallel shares serve local clusters only …`. If `darkbloom cluster` shows this once both Macs run this release, choose the model again there: it is planned with equal shares and registers. + +### Both Macs of a pair roll back together + +- When one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts of its cluster service, a failed start check, or `darkbloom update --rollback` while its cluster service was stopped), the other Mac now rolls back to the same earlier release, and the pair serves it together. Before, the pair stayed split until a newer release updated both Macs. +- The other Mac checks at its start and every minute while no update runs, also with automatic updates off. It finishes the accepted requests of its part first, as for an update, restores the release it kept from before its last update, quarantines the rolled-back release and restarts. Both Macs then skip that release, and the next newer release updates both. +- A Mac that keeps another earlier release, or none, or whose part serves on the leader's local API or alone, does not follow (yet) and says so once in `~/.darkbloom/cluster-setup/service.log`. While a pair runs on it, a Mac whose partner stops answering during the follow waits at most a minute, then changes nothing and tries again at the pair's next update slot. A Mac whose partner quarantined a release does not install that release either. +- Both Macs need this release or a later one, and the release a Mac rolls back to must have it too: the Mac that rolled back reports the rollback from the restored release. A rollback of this release itself is therefore not followed; rollbacks of later releases are. +- To roll back a pair by hand, stop one Mac's cluster service with `darkbloom cluster stop --service`, run `darkbloom update --rollback` there, and start it again with `darkbloom cluster`; the other Mac follows. + +### Two-Mac pairs recover after losing a rank during a stop + +- A two-Mac pair no longer stays unable to serve when it loses a rank while + its slot is stopping. Until the provider restarted, its leader refused every + later start, and `darkbloom cluster stop` left that Mac's part still + releasing. +- Fixed a deadlock in the pair's request engine. Stopping the pair slot + cancelled a request's stream while the engine was telling that request the + pair had lost a rank. The stream's cancellation waited for the engine, and the + engine waited for the cancellation to finish, so the slot never stopped. + Cancellation and stream termination now never wait for the engine. +- The leader also releases a committed start as soon as its session ends, + instead of after the old slot has fully stopped, so a slow stop can no longer + make it refuse later starts with "a committed start is already served". The + release receipt still waits, bounded, for the slot to retire, and a pair still + never serves two slots at once. + +### MiMo-V2.6-Flash and Gemma 4 26B QAT serve public cluster traffic + +- Two more models are approved for public traffic on two-Mac clusters, in pipeline and tensor parallel, as GLM-5.3-Flash and Qwen3.8 27B are: MiMo-V2.6-Flash (`mimo-v2.6-flash-mopd`) and Gemma 4 26B QAT (`gemma-4-26b-qat-4bit`). A release's cluster runtime facts carry their pair-serving grants and parity qualifications, so a pair of either model earns through Darkbloom on any Apple silicon pair, and `darkbloom cluster` lists them. +- Their tensor parallel serves once its code is in the build (Gemma 4 and MiMo tensor parallel PRs); until then they pair as a pipeline. MiMo-V2.6-Flash's speculative pipeline, its default split, is declared too. + +### A running cluster service answers after the Macs pair again + +- When the two Macs pair again while their cluster services run (`darkbloom cluster` or `darkbloom cluster pair`), each service starts its setup and control-lease listeners again with the new pairing within about 5 seconds. They used to keep the earlier pairing's key until the service restarted, so the other Mac's leases and its "Reading both Macs over the cable" step were refused (`refused (handshakeRejected)`). The service log says `this Mac's pairing changed (): answering the paired Mac with the new one`. +- A Mac left with no pairing stops answering over the cable. A pairing store that cannot be read leaves the listeners as they are. +- A Mac that paired again under a new Secure Enclave key of its own drops its earlier control state, as it already did when the other Mac's key changed. +- A cluster service started by an earlier release keeps the earlier behavior until it restarts (log out and back in, or `darkbloom cluster stop --service` and then `darkbloom cluster`). + +### Tensor parallel for Gemma 4 and MiMo only on measured speed + +- Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone does not choose it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. +- When the estimate says tensor parallel would be faster, the pair keeps the pipeline. The plan's "Tensor parallel or pipeline" line says the predicted gain and that it comes from the device index, and the model list says "tensor parallel: not measured yet". +- Normal setups do not load tensor parallel to measure it, so these pairs keep the pipeline for now. MiMo does not yet time its halves at load, so MiMo pairs reach tensor parallel only from requests the same build served in tensor parallel. +- Tensor parallel must also keep every feature of the mode it would replace (see "Tensor parallel only where it keeps every feature"). +- Qwen and GLM still choose tensor parallel wherever it fits. + +### Fresh MDM removal guidance + +- Keep `darkbloom status` and both `darkbloom doctor` authorization summaries from offering MDM removal when the coordinator decision is too old for removal readiness. An unexpired App Attest serving lease stays visible; removal advice asks for fresh readiness and keeps existing profiles installed. The `darkbloom unenroll` checks are unchanged. + +### Gemma 4 replies keep characters outside its vocabulary + +- A Gemma 4 reply that ended in characters its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost all of them: `all zipped up 🗜` came back as `all zipped up `, and a reply made only of such characters came back empty. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. +- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. `/detokenize` keeps it too. +- Token IDs, numeric logprobs, sampling and cache keys do not change, with one exception: a stop string that a trailing run completes now matches when the run completes, one token sooner, so `completion_tokens` can fall by one. +- A streamed reply's `logprobs` gains the entries of those tokens, which it used to drop. A byte token's `logprobs` text and `bytes` are U+FFFD or its ASCII character instead of empty, not the real byte. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it. + +### Gemma 4 plain decode commits by operation count + +- Plain decode steps of Gemma 4, the rows served without its assistant, commit a Metal command buffer every 100 operations instead of many times per step. Outputs are bitwise identical. Prefill and assistant rounds keep MLX's defaults. + +### Gemma 4 text keeps its spaces before punctuation + +- Gemma 4 replies, reasoning and tool arguments no longer lose the space before `.`, `,`, `?` and `!`, or repeat a quote. `git add .` came back as `git add.`, `bash ./run.sh` as `bash./run.sh`, `x != y` as `x!= y`, and, when streamed, `role = 'start'` as `role = ''start'`. +- Gemma 4's published `tokenizer_config.json` omits `clean_up_tokenization_spaces`, and the Swift tokenizer library reads a missing key as cleanup on, where Python Transformers reads it as off. The provider now resolves a missing key to off in memory for every model. An explicit Boolean is kept. +- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. Stop strings match the text as spelled: one with a space before punctuation can now match, and one that matched only the cleaned text (`add.` for `add .`) no longer does. + +### Faster Gemma 4 pipeline pairs + +- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 370 ms to about 31 ms; pair throughput is not yet measured. +- A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time. +- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. + +### Gemma 4 tensor parallel on two-Mac clusters + +- Gemma 4 26B (QAT 4-bit and 8-bit) can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels, both share every token over the encrypted link, and the pair returns the same tokens a single Mac would on the synthetic checks. Text only. +- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. +- In tensor parallel, Gemma 4 returns logprobs (`logprobs` / `top_logprobs`), and each Mac reserves memory for its own half of the model: about 8.0 GB of weights at QAT 4-bit (14.9 GB at 8-bit) plus its own KV, with a conservative 5.5 GiB activation reserve until a pair measures one. +- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each request reserves room for its own prompt's prefix (about 0.44 GB a Mac for a 32K-token prompt); kept prefixes use free memory only and are dropped first when memory runs short. +- Gemma 4 tensor-parallel pairs serve one request at a time unless `DARKBLOOM_CLUSTER_BATCH_LANES` names more. Speed on a real pair is not measured yet. + +### A latent stop race in GLM tensor parallel's one-token decode + +- No released pair is affected, and serving is unchanged: every v0.10.6 GLM-5.3-Flash tensor-parallel pair loads the model's NextN (MTP) layer and decodes every request in MTP rounds, which already end both Macs together when a request stops just before the model's end token. +- The one-token decode, which only a build without that layer runs, now does the same: both Macs end at the end token and return the text up to the stop (for example, a stop string that matched just before the answer ended). Before, the stopped Mac built one more step alone and waited in a collective the other Mac, already finished at that token, never joined, so the request would stall and fail on both Macs. + +### GPT-OSS plain decode commits by operation count + +- Plain decode steps of GPT-OSS commit a Metal command buffer every 100 operations instead of after almost every MoE layer. Outputs are bitwise identical. Prefill keeps MLX's defaults. + +### MiMo pipeline decode command buffers and expert routing + +- MiMo V2.6 Flash pairs encode decode steps, lane steps and speculative rounds + in Metal command buffers of up to 100 operations with no input-size bound, as + GLM and Qwen tensor parallel already do. Prefill keeps the rank's limits. + Tokens, logits and caches are byte-identical on synthetic stages. The speed + effect on the registered model has not been measured yet. +- A MiMo request's memory charge now prices every full-attention layer's decode + score rows at once, which the larger command buffers can keep alive together. + The LOAD quote is unchanged. Only requests whose prompt frames are shorter + than a stage's full-attention layers times the decode rows (32 tokens at most) + are charged slightly more. +- The planner's hardware prior now counts MiMo's routed experts at the 8 of 256 + a token uses: 10.77 GB read per decode step instead of 166.6 GB. The prior + prices only tensor parallel, so MiMo's pipeline plans are unchanged. + +### MiMo image-candidate pairs keep cluster prompt prefixes + +- A MiMo V2.6 Flash pair serving the private, local-only image candidate no + longer fails its requests while the cluster prefix cache is on (the + default). That candidate is the only MiMo load with contiguous caches. MiMo + still required the five metadata values that older MLX SDKs wrote for a + sliding-window cache, while the pinned SDK writes seven (adding the capacity + origin and a wrapped flag), so requests, text or image, failed at their + first prompt-prefix capture. Prefixes are now captured and restored. The + four text serving modes use paged histories with prefix reuse off and were + not affected. + +### MiMo V2.6 Flash tensor parallel on two-Mac clusters + +- MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. +- Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. +- The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Two 128 GB Macs, which cannot hold MiMo alone, can serve it this way. Qwen and GLM still choose tensor parallel wherever it fits. +- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 100 GiB per Mac at the longest request, the draft heads included). +- No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. + +### MiMo V2.6 Flash tensor parallel with speculative decoding + +- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's own trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. +- It is on by default: the installed provider starts both Macs' tensor-parallel workers with two drafts a round. +- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Each Mac's halves stay at full 32-bit precision inside a round too, exactly as in a one-token step. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. +- Each Mac holds the draft heads whole (about 2 GB more) and reserves their per-request state, and the plan counts both before it chooses tensor parallel. Two 128 GB Macs still fit, at about 100 GiB a Mac. +- Because MiMo's tensor parallel now keeps the speculative pipeline's rounds, feature parity no longer holds it back where that pipeline is the mode it would replace; its measured speed decides, and the plan credits the rounds no speed-up until they are measured. Where the plain pipeline is the mode it would replace, that pipeline's batch lanes still keep it. +- Not yet measured on a real pair: the speed-up, the heads' acceptance rate and qualification records. + +### The Models page shows what the network registered + +- Each model on the Models page now says whether this Mac's live registration carries it: "Registered with the network" (the network sends it requests), "Registered for Autopilot" (Autopilot can load it), or, for a selected or pool model, a warning "Not registered with the network yet". Before, the page showed only what was selected, downloaded or loaded, so a selected model the network did not know looked like it was serving. +- The provider writes the registered set to its state file (`registered_models`). +- A Mac with Autopilot that is busy at every check, or always under a lease, now reports a newly verified build after at most 10 minutes. The re-registration closes admission, lets accepted requests finish, then reconnects. Before, such a Mac could wait without end, and Autopilot could not use the build. + +### Pipeline decode command buffers for the remaining cluster models + +- Cluster pairs of the Qwen and Bonsai rows, Nemotron 3.5 Lightning, Gemma 4, + GPT-OSS 20B and GLM-5.3-Flash encode decode steps (pipeline and phase split), + lane steps and speculative rounds in Metal command buffers of up to 100 + operations with no input-size bound, as GLM and Qwen tensor parallel already + do. Prefill keeps the rank's limits. Tokens, logits and caches are + byte-identical on synthetic stages. The speed effect on registered models has + not been measured yet, and each family keeps the change only if a pair A/B + shows a gain. +- A request's memory charge on those pairs, other than GLM's, now prices every + attending layer's decode rows at once, which the larger command buffers can + keep alive together. The LOAD quotes are unchanged. Only requests whose prompt + frames are shorter than their decode rows (at most 80) are charged more, and + only on a rank that decodes. + +### The enabled-model filter wins over coordinator model changes + +- A model you deselect with `darkbloom switch` or delete with `darkbloom models remove` no longer comes back on its own. Before, when the coordinator moved a public model to a newer build, every Mac serving that model downloaded the newer build, served it in place of the build its operator chose and loaded it, even when `enabled_models` left it out. For example, with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, `gemma-4-26b-qat-4bit` returned within minutes and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. +- With `enabled_models` set, the provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside it (`model_not_selected`), and keeps serving the build you selected when its public model moves to a build you did not list. The log then says `desired_models: → is outside the enabled model filter; not converging`. +- **Your provider no longer moves to a new build of a model by itself.** To take one, run `darkbloom switch` and pick the model's public name; the picker shows its newest build under that name. Until you do, the newer build gets that model's requests first. +- `darkbloom switch` applies its selection as the filter at once, without a restart. +- Nothing changes with an empty `enabled_models` (serve every downloaded model), or for Autopilot's consented downloads and placements. + +### Child process exit waits + +- Report a finished child process without the former polling and run-loop delay. Bounded children (the paged-kernel preflight, update staging, runtime smoke and signature checks, `darkbloom doctor` and `verify` probes) are reported up to about 120 ms sooner each, and waiting for `launchctl`, `codesign`, `profiles`, `open` and `log` no longer runs the calling thread's run loop. Timeouts and the SIGTERM-then-SIGKILL escalation are unchanged. + +### Provider status App Attest lease + +- Keep `darkbloom status` and `darkbloom doctor` reporting App Attest authorization until the coordinator lease expires. They required a renewal within the last 10 seconds, so one delayed renewal showed `Trust: self_signed / online` although serving continued. `darkbloom unenroll` still requires a renewal within 10 seconds before offering MDM removal. + +### Roll a Mac back to its previous release + +- `darkbloom update --rollback` restores the release a Mac ran before its last update. When the updater installs a release, it keeps the signed release it replaces; the rollback puts that release back, also after the new one has served for 10 minutes and was promoted. +- It shows the installed and restored versions and asks `Roll back to vX? [y/N]` before changing anything (`--yes` skips the question). The running provider finishes its accepted requests (`--timeout`, `--force` as for `darkbloom update`), the kept release replaces the installed one in the watchdog's journaled swap under the update lease, and the provider restarts on it. It contacts no coordinator. +- The rolled-back release is quarantined on that Mac: the provider's 30-minute update check, the startup check and the watchdog do not reinstall it, and the next newer release installs normally, so automatic updates can stay on. `darkbloom update --override-quarantine` installs it again on request. +- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while a provider runs in the foreground (`darkbloom start --foreground`), while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. +- Only one earlier release is kept. A Mac rolls back to the release it ran before its last update, not further. + +### Qwen tensor-parallel decode control in the selection sum + +- A Qwen tensor-parallel pair's plain decode step now carries the next step's + plan and report in its own sealed selection sum, so the step pays one sealed + sum and one host read fewer than before. Tokens, logits and native state are + unchanged; assisted (MTP) rows, prompt steps and idle steps keep their own + exchange. +- Owner answers, cancellations and joins now apply one step later while plain + rows decode. A row decodes its next token once the owner answered the token + before it, so an answer that arrives while a step computes no longer leaves + the row idle for a step. Rank 0 still publishes a token only after the + owner's answer to the one before it. A token selected before a stop answer is + never published, so streamed text, usage and logprobs are unchanged. +- A clean stop the owner asks for (a stop string, for example) can cost one + more forward, which is discarded. On a one-lane pair every such stop after a + request's first token does (assisted rows excepted), and that request's + finish arrives one decode step later than before. +- Both ranks of a pair must run this build: the load agreement binds the new + control wire (`qwen-tp-independent-history-batch-v2-folded-control`). +- `darkbloom-cluster-tp-check qwen-decode` times the batch driver's decode on + two ranks over the loopback ring, with the control exchanged or folded, and + checks that both retire the same tokens. + +### Qwen tensor-parallel decode routes, row exactness and finiteness check + +- A Qwen3.8-27B tensor-parallel row now decodes the same bytes alone as beside + other rows and in verify windows on the registered weights. A one-row decode + step's fused SwiGLU computed its sigmoid with Metal's fast `exp`, while + cohort and window steps use MLX's precise `exp`. The two round a gate of + exactly bf16 -6.84375 differently, which could change later tokens. Dense + Qwen tensor-parallel output changes only where a one-row decode step meets + that gate value, and there it now equals the cohort path. Regenerate + tensor-parallel serving references recorded with earlier builds once. + Single-Mac output is unchanged. +- A non-finite logit on either rank of a Qwen tensor-parallel pair now fails + both ranks in the same selection step, before any token is published; + previously the other rank waited in the selection collective. The check moved + into the selection's sealed sum, so a decode step no longer pays a separate + finiteness read. Selected tokens are unchanged. +- Each rank logs its decode routes once per load, when it first serves + (`darkbloom-qwen-tp-decode-census-v1`): which projections take the + batch-invariant kernel and at which layout per row count, the attention and + residual-norm routes, and the arithmetic switches in force. +- `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback + ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows + and in verify windows at the registered per-rank widths, with random weights + that follow the registered artifact's value statistics or with the registered + checkpoint itself; `qwen-rows layers` names the first layer that differs. + +### Qwen tensor-parallel pairs serve up to 8 requests at once, sized to memory + +- `darkbloom cluster` now sets how many requests a Qwen tensor-parallel pair + serves at once: 8, 6, 4 or 2, the most that both Macs' memory holds now with + the full load reservation for that many. The pair serves them from its first + load. Before, it served one at a time: a local pair widened only after a + burst, through a reload the burst waited for, and a pair serving Darkbloom + traffic never widened. +- On two idle Macs, Qwen3.8-27B serves 8 at once from 64 GB a Mac without the + speculative assistant (4 at 48 GB, 2 at 32 or 36 GB), and 8 from 96 GB a Mac + with it (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either + way. When not even 2 fit, the pair serves one request at a time, as before. +- Memory safety is unchanged: both Macs reserve that many requests' full memory + when the model loads and admit each request alone. A local pair set up + narrower still widens when requests queue; a pair set up for 8 is never + reloaded for it. +- Existing setups keep serving one request at a time until they are planned + again, as after an update. A pair serving Darkbloom traffic keeps its width + beside its approval; no approval, registration or committed-start digest + changes. + +### Qwen tensor-parallel prompt wavefront + +- A Qwen tensor-parallel pair now prefills a text prompt faster, in steps of up + to eight consecutive 512-token frames built as one graph, layer by layer: + while one frame's sealed sum crosses the link, the next frame computes. Every frame + keeps its own shapes and kernels, so logits, KV, recurrent state, prefix + captures and tokens are unchanged. Steps run two frames while another lane + decodes and end at the prompt-cache capture point. Media prompts, assisted + (MTP) prompts, packed KV and routed-expert models keep one frame a step. +- The merged step's frames in flight are charged in LOAD, the placement quote + and each request's charge: a Qwen3.8-27B tensor-parallel rank needs about + 367 MB more at any width. +- `darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` and + `darkbloom-cluster-tp-check qwen-wavefront` measure the merged steps on one + rank and on two ranks over the loopback ring. + `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` restores one frame a step for + diagnosis; both ranks must agree. + +### Qwen3.8 27B tensor parallel reuses whole prompt prefixes + +- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk instead of at most 4,096 tokens, including prompts longer than 32,768 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. +- A prefix restored from memory returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries); one restored from the SSD tier's default `balanced` records is close but not identical, as before. Both Macs must hold a boundary; otherwise both start from zero. +- Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. +- Requests served by the assistant (MTP) lanes still reuse at most 4,096 prompt tokens, less than one Mac reuses for a long prompt; deepening them is a separate change. Speed on a real pair is not measured yet. + +### Stop sequences no longer match Gemma 4 or `` reasoning + +- A client `stop` sequence on Gemma 4 models such as `gemma-4-26b-qat-4bit`, + and on models that reason in `` blocks (Qwen 3.5, 3.6 and 3.8, + among others), now matches only the text returned as `content`. With + reasoning on, it used to match the reasoning too, so a sequence that + appeared while the model reasoned (for example `"."` or `"\n\n"`) ended the + request before any answer: `finish_reason` `stop`, reasoning only, empty + content. +- With tools declared, tool-call frames are not cut either, except a frame + whose arguments quote its own closing tag, or a bare `` frame + written without its wrapper. When a request has no tool handler (no declared + tools, or a media request on a family without native media tools), a literal + tool tag in an answer is text the client receives, and stops still apply to it. + Whitespace before the answer's first character (the blank line after + ``) cannot complete a stop sequence on its own. +- A stop sequence that names a marker no longer fires on it: ``, or + `` with tools declared. + +### Sandbox setup shows the add-on's own sizing plan + +- `darkbloom sandbox setup` now asks the Darkbloom Sandbox installer for the add-on's own plan before it asks you to confirm. After its own chip, macOS, session, network, power and sleep checks, setup runs the downloaded installer with `--plan` (add-on 1.1.1 and later). The installer verifies the release and sizes this Mac without installing anything. Setup then prints the plan's cores, memory and disk lines and how many Linux and macOS jobs this Mac can run at a time. Example: `Disk: 157 GiB free; 100 GiB stays free for you; Linux images 4 GiB + 30 GiB per Linux job; macOS images 46 GiB + 40 GiB per macOS job`. +- Disk follows the add-on's rules. A tenth of the disk (50 to 100 GiB) stays free. The first job of a platform also needs that platform's VM images (Linux 4 GiB, macOS 46 GiB, nothing once installed). Each Linux job takes 30 GiB and each macOS job 40 GiB. +- When no job fits, setup prints the plan's message and how much disk to free for one Linux job and for one macOS job. It then stops without installing. +- The installer is now downloaded before the question, so the plan is shown before you confirm. Nothing is installed before you answer `y`. +- With an older installer that cannot report a plan, setup prints `[INFO] Sizing` and estimates with the same rules. +- Setup's output is line-buffered: run over ssh or into a pipe, it shows the approval link as soon as the installer has it, not once setup ends. +- With add-on 1.1.2 and later, a Mac waiting for approval keeps waiting in the background, also across restarts, and enrolls by itself, and setup now says so. On the waitlist it says you can close the window, and after Ctrl-C it says that the Mac keeps waiting; both point at `darkbloom sandbox status`. With an earlier add-on, setup words both as before. + +### Sandbox setup offers the add-on's new plan on a Mac that is set up + +- Running `darkbloom sandbox setup` on a Mac that is set up now asks the Darkbloom Sandbox installer for the add-on's plan again (`--plan`, which changes nothing). When the plan's Linux and macOS job counts differ from the installed ones, setup shows the plan's CPU, memory and disk lines and asks, for example `This Mac now fits 1 Linux + 1 macOS (installed: 3 Linux + 0 macOS). If a job is running, the installer refuses and changes nothing. Apply? [Y/n]`. Yes reinstalls with the plan's counts; no prints the `--linux-slots`/`--macos-slots` command that applies it later. When the counts match, the output is exactly as before. +- With `--yes` or without a terminal, setup applies the plan only when it adds jobs and removes none; otherwise it prints `Not applied` and the command, and exits 0. +- While jobs run, setup skips the check and says to run it again once they finish. When the installer refuses because a job is running (exit 4), setup now says that a job is running, to run setup again when it finishes, and that it never passes the installer's `--force`, which would stop running jobs, which aren't paid. +- Explicit `--linux-slots`/`--macos-slots`, an installer without `--plan` and a failed download behave as before. A platform missing from the add-on's `status --json` counts as 0 slots. +- When the add-on's plan gives macOS no job for want of free disk space, setup adds one line: ``Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS frees only when it needs to (restarting, or removing Time Machine local snapshots: `tmutil listlocalsnapshots /`, frees it now). A macOS job needs about N GB more.`` N counts the disk the plan's Linux jobs take, so a Mac planned for 3 Linux jobs and no macOS job gets a real number. + +## v0.10.6 + +Published 2026-10-31 ([release](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.6)). ### Upgrade and rollout notes diff --git a/changelog.d/app-attest-first-episode.md b/changelog.d/app-attest-first-episode.md deleted file mode 100644 index e1802854a5..0000000000 --- a/changelog.d/app-attest-first-episode.md +++ /dev/null @@ -1,4 +0,0 @@ -### App Attest restart covers the first episode after an update - -- The `is_supported_false` restart now also works in the first process after an update from a version that did not record its App Attest authorizations. At serve start, when `app-attest-verified.json` is missing, the provider fills it once from the previous `daemon-state.json`, with evidence from the last 7 days: the last successful Apple call of a stored key that Apple attested, or an App Attest grant left by an unclean exit. All other conditions stay the same. -- A Mac whose previous provider was itself reporting `is_supported_false` has no such evidence, so it still waits for the coordinator to grant App Attest again. diff --git a/changelog.d/app-attest-unsupported-restart.md b/changelog.d/app-attest-unsupported-restart.md deleted file mode 100644 index 97ed5acd15..0000000000 --- a/changelog.d/app-attest-unsupported-restart.md +++ /dev/null @@ -1,6 +0,0 @@ -### App Attest recovers by itself after a self-update - -- A provider that launchd runs as its provider job now relaunches through launchd after a startup self-update, as it already did after a background update. Only a provider that launchd does not run, such as `darkbloom start --foreground` in a terminal, replaces itself in place. A background update or App Attest restart in such a provider no longer starts the LaunchAgent instead. -- When App Attest reports `is_supported_false` on a Mac that the coordinator verified for App Attest in the last 7 days, the provider restarts once through launchd. It waits until the state lasts 5 minutes and the provider is idle, and it checks Apple's answer again after the drain. If the new process still reports unsupported, it does not restart again until the coordinator verifies the Mac again. This restart and the stall restart share one limit: one automatic App Attest restart per 6 hours. Cluster members never restart for it. -- The provider keeps the time of its last App Attest authorization in `app-attest-verified.json` beside the daemon state file. -- The local provider log gets an `App Attest entitlement evidence` line at startup and at each `is_supported_false` answer: the start reason, the App Attest entitlements of the running process and of the code on disk, and the executable's modification time relative to the process start. It is not sent to the coordinator. diff --git a/changelog.d/checkpoint-row-decoder.md b/changelog.d/checkpoint-row-decoder.md deleted file mode 100644 index 96ee68c9b4..0000000000 --- a/changelog.d/checkpoint-row-decoder.md +++ /dev/null @@ -1,10 +0,0 @@ -### Cache restores finish sooner - -- Restoring a prefix-cache checkpoint decodes its older attention rows from the - default `balanced` checkpoint precision on the CPU. The decoder now checks each - row for values its native type cannot hold once per row instead of once per - eight values, with the same bytes and the same refusals. On Gemma 4 26B - follow-up requests served from the SSD cache, time to first token fell by about - 0.2 s per restore (about 25% over an 11-request conversation on an M3 Ultra), - and responses that save a checkpoint also end about 0.2 s sooner. Output is - unchanged. diff --git a/changelog.d/checkpoint-row-encoder.md b/changelog.d/checkpoint-row-encoder.md deleted file mode 100644 index 0779a093f3..0000000000 --- a/changelog.d/checkpoint-row-encoder.md +++ /dev/null @@ -1,8 +0,0 @@ -### Responses that save a cache checkpoint finish sooner - -- Saving a prefix-cache checkpoint encodes its older attention rows at the default - `balanced` checkpoint precision. That encoding now prepares its buffers and its - check once per segment instead of once per row and writes the same bytes. On a - Gemma 4 26B request that saves a checkpoint, the end of the response arrived - about 0.7 s sooner (1.7–2.0 s → 1.0–1.2 s on an M3 Ultra), with identical - output. Requests that save no checkpoint are unchanged. diff --git a/changelog.d/ci-darkbloom-watchdog.md b/changelog.d/ci-darkbloom-watchdog.md new file mode 100644 index 0000000000..e97fbcadc3 --- /dev/null +++ b/changelog.d/ci-darkbloom-watchdog.md @@ -0,0 +1,3 @@ +### CI rescues runs stranded on Darkbloom + +- A scheduled workflow, `darkbloom-watchdog.yml` (darkbloom-sandbox's GitHub-side watchdog, copied unchanged), cancels a run whose Darkbloom job waited `DARKBLOOM_WATCHDOG_MINUTES` with no runner and re-runs its route on the Blacksmith fallback, once per run. Its token can only cancel and re-run this repository's workflow runs and write a check run. diff --git a/changelog.d/ci-dev-master-workflows.md b/changelog.d/ci-dev-master-workflows.md new file mode 100644 index 0000000000..e673cba666 --- /dev/null +++ b/changelog.d/ci-dev-master-workflows.md @@ -0,0 +1,6 @@ +### CI has a dev workflow and a master workflow; dev runs only the tests + +- Two reusable workflows hold the CI jobs: `provider-plan.yml` (the component classifier, the tested-change lookup and the run's one Darkbloom route request) and `provider-tests.yml` (the provider shards, the cluster jobs and the `Provider Tests` gate). `ci-dev.yml` runs both for pull requests into any branch but `master` (`dev` and stacked branches) and for pushes to `dev`. `ci-master.yml` runs both for pull requests into `master` and pushes to `master`, with Release Integrity and Docs Lint beside them. `ci.yml` is gone. +- Pull requests into `dev` no longer run Release Integrity, Docs Lint, Commit Signatures or Docs Impact. Pull requests into `master` run all of them, as before; Release Integrity keeps its check name, which `master`'s ruleset requires. The `Provider Tests` gate runs the cluster plan audit and the CI plan self-tests on every run, `dev` included. +- The test jobs' checks are now named after the caller's job, for example `Tests / Provider Tests`. +- Release Integrity and Docs Lint read their Linux lanes from the plan's route request, with `blacksmith-4vcpu-ubuntu-2404` as the fallback. diff --git a/changelog.d/ci-git-swiftpm-cache.md b/changelog.d/ci-git-swiftpm-cache.md new file mode 100644 index 0000000000..453f30eb74 --- /dev/null +++ b/changelog.d/ci-git-swiftpm-cache.md @@ -0,0 +1,11 @@ +### CI caches .git and SwiftPM repositories; only master and dev pushes save caches + +- Every `ci.yml` job that checks out restores the newest saved `.git` first, so the checkout fetches only new objects and reuses submodule clones. A restored `.git` that `git fsck` rejects is deleted first; no step continues on error. The `.git` key names the UTC day, so each branch saves `.git` at most once a day. The full-history `docs` job keeps its own entries. +- The build lanes restore SwiftPM's repository clones, which a cold build otherwise downloads. +- Checkouts download less. Every job but Docs Lint skips the evidence tarballs under `docs/reports/evidence` and `landing/public/media` (408 MB of tarballs and landing videos), which no other job reads. Docs Lint and Docs Impact fetch history without file contents, about 37 MiB instead of about 1 GB, and fetch old file versions only when the provenance check reads them. +- Only pushes to `master` and `dev` save CI caches. A pull request restores its base branch's entries, then `master`'s, and saves none, so it no longer evicts them from the repository's 10 GB Actions cache. +- Provider builds on Darkbloom Macs use the CMake 3.31.12 already in the image's tool cache instead of downloading 80 MB each time; other runners still download and verify it. +- The MiMo audio gate, and the 1.87 GB codec its fixture needs, run only when the gate's inputs change (MiMo, audio and media provider code, the MiMo tests, the MLX pins, the fixture scripts or the gate's recipe) and on every `master` push. Pull requests never save the codec. +- Checkouts no longer keep the job token in `.git/config`, which the `.git` cache would otherwise store. +- Each job logs whether `actions/cache` compresses with zstd or gzip; entries saved with one are not restored by a runner using the other. +- Limitation: on a pull request, the provider summary job restores its base branch's newest compatible build and rebuilds the commit's changes instead of reusing its shards' build. diff --git a/changelog.d/ci-macos-darkbloom-route.md b/changelog.d/ci-macos-darkbloom-route.md new file mode 100644 index 0000000000..8e1fa03580 --- /dev/null +++ b/changelog.d/ci-macos-darkbloom-route.md @@ -0,0 +1,6 @@ +### CI's macOS jobs ask for Darkbloom Sandboxes again + +- The macOS jobs of `ci.yml` read the Darkbloom route again, as they did before they moved to Blacksmith only. Each provider shard (`test-provider-1` to `test-provider-3`), the shard summary (`test-provider-summary`), the SDK lane (`test-provider-sdk`), the cluster metadata checks (`test-cluster-checks`), each cluster runtime and GPU shard (`test-cluster-1` to `test-cluster-3`, `test-cluster-gpu-1`, `test-cluster-gpu-2`) and the cluster focused checks (`test-cluster-focused`) run on a Darkbloom Mac when the plane grants their lane, and on `blacksmith-12vcpu-macos-27` otherwise. +- A lane is requested only when its job runs: the provider lanes when provider inputs change, the SDK lane on pushes and SDK-lane changes, and the cluster lanes when cluster inputs change. +- The provider shard count, the cache-save rules and the `.git` and SwiftPM caches are unchanged. +- Limitation: a lane the plane's approval does not name keeps Blacksmith, as do all lanes while `DARKBLOOM_ROUTING` is not `on` and for pull requests from forks. diff --git a/changelog.d/ci-sandbox-lanes.md b/changelog.d/ci-sandbox-lanes.md new file mode 100644 index 0000000000..9db77da2cd --- /dev/null +++ b/changelog.d/ci-sandbox-lanes.md @@ -0,0 +1,12 @@ +### Provider CI: fewer Mac jobs per run, loose build-cache restores, macOS lane cap + +- Provider Unit Tests runs in 2 shards instead of 3. Each shard builds once and runs 3 test selections at the same time, each serially in its own process with its own `TMPDIR` and provider state files. The isolated processes and the native gates still run after them, alone. The processes start 15 s apart. A selection whose SwiftPM found the build database locked by another process's startup runs once more, but only when its log proves every test passed; both attempts' logs and reports are kept. The plan is unchanged; the audit counts 6 selections. +- Cluster Runtime Tests runs in 2 shards instead of 3. Shard 1 runs the `base` selection alone, then the share probe alone. Shard 2 runs two groups at the same time, each in plan order: the batch-session suite with the GLM paged-KV, invariance and census, TF32 and Gemma selections; and the Qwen GPU chain with `glm53-prefix-ssd`. A grouped selection that finds the build database locked runs once more, under the same rule. +- The Provider SDK Tests lane is removed: 226 of its 236 test seconds repeated the SDK's own Fork Tests. Its one other step, `MiMoV26NativeMediaDeadlineTests`, is left for the SDK's Fork Tests to run. Release qualification still builds and tests the provider, with the SDK compiled in, under SDK 27. +- CI tests each change once: a run whose change a successful run of the same workflow already tested, with every component this run selects, runs no test job, and its gate cites that run. A record binds to its tree, its base and head commits and the commit its run tested; the push of a pull request's merge commit finds the pull request's record through the merge's two parents. Such a push runs one build-only job that refreshes the branch's build caches. +- Pull requests and pushes run the same jobs. On `dev` both select components by their diff (a push against the branch's previous commit); pushes to `master` and pull requests into `master` select every component. Only pushes save caches. Cluster GPU Tests (report only) run whenever the cluster jobs run. +- Provider Unit Tests Summary is gone: each shard audits its own selections against `swift test list` and reports its own coverage, and the last shard checks that the plans cover the suite once. Cluster Metadata Checks run inside Cluster Focused Checks, which makes them part of the `Provider Tests` gate. +- A provider-only pull request now runs 2 Mac jobs instead of 4 (5 with an SDK input); a cluster pull request 7 instead of 11; the push of an already tested merge commit at most 1 build-only job instead of 12. +- The Swift build cache restores from a loose tier that ignores the CI recipe, so a workflow or CI script edit no longer makes every build cold, and then from a tier keyed only on the toolchain and the MLX pins, so a manifest change still restores the compiled MLX. A build that fails over a loose-tier entry builds once more from nothing. CI (master) restores only entries of its exact recipe. On Darkbloom hosts a push saves at most one build per lane and day. +- The MiMo metadata downloads are cached by their pinned SHA-256 and used only when their bytes match. +- The repository variable `DARKBLOOM_MACOS_LANES` caps the macOS jobs one run asks Darkbloom for; the rest use Blacksmith at once. diff --git a/changelog.d/cluster-auto-update.md b/changelog.d/cluster-auto-update.md deleted file mode 100644 index 96cfbf1c21..0000000000 --- a/changelog.d/cluster-auto-update.md +++ /dev/null @@ -1,10 +0,0 @@ -### Pair Macs set up with `darkbloom cluster` update themselves - -- A Mac set up with `darkbloom cluster` now updates itself, as a single Mac does: with `auto_update` on (the default) and without `DARKBLOOM_NO_UPDATE_CHECK`, its cluster service checks the coordinator's latest release every 30 minutes, at the pair's update slot, which both Macs derive from their pairing's cluster ID. -- Each Mac downloads, verifies and stages the release while the pair serves. Only once both Macs have it does the pair stop taking new requests; the Mac that serves the pair finishes its accepted requests (at most 120 seconds, never cancelling one), then both Macs install the release and restart their cluster services, and the cluster sets itself up again for the new release with no command run. -- A pair under constant traffic updates too: once it takes no new requests, the accepted ones finish. A pair still running a request at the bound takes requests again and tries at the next slot. A release one Mac cannot download or verify is installed on neither Mac; both try again at the next slot. -- An installed release is promoted once its cluster service has stayed healthy for 10 minutes; three starts of its service that end on their own restore the previous release and quarantine the new one, as the watchdog does for a single Mac. -- Before a Mac restarts into an installed release, its cluster service runs the new `darkbloom --version` once (at most 30 seconds). A release that does not answer with its version is never restarted into: the Mac restores the previous release at once, quarantines the new one and starts its cluster service again, so a release that cannot start no longer leaves the Mac with nothing to roll it back. -- `darkbloom update` on a cluster Mac installs the release and then restarts the cluster service into it together with the other Mac, after the pair drained; logging out and back in is no longer needed. Run it on both Macs (or let the other Mac update at the next slot); the first Mac waits up to 15 minutes for the second, also when automatic updates are off. A Mac whose partner has automatic updates off downloads nothing at the slot. -- A pair that serves on the leader's local API, or a Mac that serves alone, is not drained for an update yet: it does not update while it serves, and a cluster set to serve locally (`darkbloom cluster local`) or a Mac serving alone downloads nothing at the slot. -- A cluster service started by an earlier release does none of this: to reach this release, run `darkbloom update` on both Macs, then log out and back in on both (or restart them) once. diff --git a/changelog.d/cluster-feature-parity.md b/changelog.d/cluster-feature-parity.md deleted file mode 100644 index 5836a1a955..0000000000 --- a/changelog.d/cluster-feature-parity.md +++ /dev/null @@ -1,6 +0,0 @@ -### Tensor parallel only where it keeps every feature - -- On a two-Mac pair, Gemma 4 and MiMo V2.6 Flash use tensor parallel only where it keeps every feature and caching behavior of the mode it would replace: prompt-prefix and SSD cache reuse, speculative (MTP) rounds, batch lanes, media, penalties and logit bias, stop handling and logprobs. What tensor parallel adds, such as logprobs where the pipeline has none, never counts against it. Each mode's features come from the installed cluster worker's capability record. -- Gemma 4's tensor parallel keeps every feature of its pipeline, prompt-prefix and SSD reuse included, so its measured speed decides. MiMo's tensor parallel decodes in speculative rounds, so it keeps every feature of the speculative pipeline and its measured speed decides; only where the plain pipeline is the mode it would replace do that pipeline's batch lanes keep it. The plan's "Tensor parallel or pipeline" line says what tensor parallel would drop ("Pipeline: tensor parallel would drop batch lanes up to 8 (it serves 1) that the pipeline keeps; held back until it keeps them."), and the model list says "tensor parallel: drops a feature". -- Where only tensor parallel fits the two Macs, the plan refuses with that reason and saves no setup, instead of saving one with fewer features. The developer's forced mode (debug builds) still places tensor parallel, and the plan says exactly what it drops. -- Qwen and GLM plans are unchanged. diff --git a/changelog.d/cluster-onboarding-simple.md b/changelog.d/cluster-onboarding-simple.md deleted file mode 100644 index 73e3b45e2f..0000000000 --- a/changelog.d/cluster-onboarding-simple.md +++ /dev/null @@ -1,15 +0,0 @@ -### Simpler two-Mac cluster setup - -- `darkbloom cluster` setup says far less: four steps (Connect, Pair, Model, Start), a line per thing that happened, - and the next thing to do last. Every choice is a list (↑↓ and enter, as `darkbloom start` picks models; numbered in - plain transcripts); q or Esc cancels. -- The model list shows only the models approved for clusters (GLM-5.3-Flash, Qwen3.8 27B, MiMo-V2.6-Flash and - Gemma 4 26B QAT) that the two Macs can serve, each with its size and its split: tensor parallel or pipeline. The - serving lines name the split too. -- The Mac you set up on leads and keeps leading: every plan puts rank 0 on it, the cluster service's own re-plans - included, so a pair set up with 0.10.6 whose other Mac took over leading moves back at its next plan. -- macOS's password and Local Network prompts come at stated moments (sudo in the terminal over SSH); both Macs ask - about Darkbloom's Local Network access right after pairing, and the setup waits until Allow or q. -- Both Macs confirm the pairing code; the Mac that follows only shows the status. The serving line says whether the - pair earns through Darkbloom or serves locally only. -- `darkbloom doctor` includes the cluster's checks on a Mac paired for a cluster. diff --git a/changelog.d/cluster-pair-equal-tensor-shares.md b/changelog.d/cluster-pair-equal-tensor-shares.md deleted file mode 100644 index 4f0a1e6764..0000000000 --- a/changelog.d/cluster-pair-equal-tensor-shares.md +++ /dev/null @@ -1,5 +0,0 @@ -### Qwen pairs of two different Macs register with the coordinator - -- Affected: a pair of two different Macs set up with `darkbloom cluster` to serve through Darkbloom, with a Qwen model planned in tensor parallel. The planner gave the faster Mac the larger share of every layer (for example 2:1 on an M3 Ultra and an M5 Max), and the coordinator registration cannot name unequal shares yet. Both Macs still said `Registered with the coordinator as a cluster member`, then each Mac's part refused to register ("The saved roster registration is not valid for this Mac: invalidPlan"), the pair fell back to the leader's local API, and the coordinator never formed it or routed it a request. This hit Qwen3.8 27B, which pairs only in tensor parallel, and Qwen3.5 9B where tensor parallel was chosen. GLM-5.3-Flash, pipeline splits and two identical Macs were not affected. -- A pair served through Darkbloom is now planned with equal tensor-parallel shares, so it registers and is routed like a pair of identical Macs; on two different Macs the slower one sets the pace. A pair that serves you alone (`darkbloom cluster local`) keeps the faster unequal split. -- A setup saved with unequal shares (by 0.10.6, or a local cluster switched to Darkbloom with `p`) is not offered for pairing, and the leader says why before it stops either Mac's part: `Not offered for pairing: this Mac's check refused it: Unequal tensor-parallel shares serve local clusters only …`. If `darkbloom cluster` shows this once both Macs run this release, choose the model again there: it is planned with equal shares and registers. diff --git a/changelog.d/cluster-pair-follows-rollback.md b/changelog.d/cluster-pair-follows-rollback.md deleted file mode 100644 index 2a6cebd878..0000000000 --- a/changelog.d/cluster-pair-follows-rollback.md +++ /dev/null @@ -1,7 +0,0 @@ -### Both Macs of a pair roll back together - -- When one Mac of a `darkbloom cluster` pair rolls a release back (three failed starts of its cluster service, a failed start check, or `darkbloom update --rollback` while its cluster service was stopped), the other Mac now rolls back to the same earlier release, and the pair serves it together. Before, the pair stayed split until a newer release updated both Macs. -- The other Mac checks at its start and every minute while no update runs, also with automatic updates off. It finishes the accepted requests of its part first, as for an update, restores the release it kept from before its last update, quarantines the rolled-back release and restarts. Both Macs then skip that release, and the next newer release updates both. -- A Mac that keeps another earlier release, or none, or whose part serves on the leader's local API or alone, does not follow (yet) and says so once in `~/.darkbloom/cluster-setup/service.log`. While a pair runs on it, a Mac whose partner stops answering during the follow waits at most a minute, then changes nothing and tries again at the pair's next update slot. A Mac whose partner quarantined a release does not install that release either. -- Both Macs need this release or a later one, and the release a Mac rolls back to must have it too: the Mac that rolled back reports the rollback from the restored release. A rollback of this release itself is therefore not followed; rollbacks of later releases are. -- To roll back a pair by hand, stop one Mac's cluster service with `darkbloom cluster stop --service`, run `darkbloom update --rollback` there, and start it again with `darkbloom cluster`; the other Mac follows. diff --git a/changelog.d/cluster-pair-serving-epoch.md b/changelog.d/cluster-pair-serving-epoch.md deleted file mode 100644 index c267c91d93..0000000000 --- a/changelog.d/cluster-pair-serving-epoch.md +++ /dev/null @@ -1,16 +0,0 @@ -### Two-Mac pairs recover after losing a rank during a stop - -- A two-Mac pair no longer stays unable to serve when it loses a rank while - its slot is stopping. Until the provider restarted, its leader refused every - later start, and `darkbloom cluster stop` left that Mac's part still - releasing. -- Fixed a deadlock in the pair's request engine. Stopping the pair slot - cancelled a request's stream while the engine was telling that request the - pair had lost a rank. The stream's cancellation waited for the engine, and the - engine waited for the cancellation to finish, so the slot never stopped. - Cancellation and stream termination now never wait for the engine. -- The leader also releases a committed start as soon as its session ends, - instead of after the old slot has fully stopped, so a slow stop can no longer - make it refuse later starts with "a committed start is already served". The - release receipt still waits, bounded, for the slot to retire, and a pair still - never serves two slots at once. diff --git a/changelog.d/cluster-public-mimo-gemma.md b/changelog.d/cluster-public-mimo-gemma.md deleted file mode 100644 index af6f88c4e5..0000000000 --- a/changelog.d/cluster-public-mimo-gemma.md +++ /dev/null @@ -1,4 +0,0 @@ -### MiMo-V2.6-Flash and Gemma 4 26B QAT serve public cluster traffic - -- Two more models are approved for public traffic on two-Mac clusters, in pipeline and tensor parallel, as GLM-5.3-Flash and Qwen3.8 27B are: MiMo-V2.6-Flash (`mimo-v2.6-flash-mopd`) and Gemma 4 26B QAT (`gemma-4-26b-qat-4bit`). A release's cluster runtime facts carry their pair-serving grants and parity qualifications, so a pair of either model earns through Darkbloom on any Apple silicon pair, and `darkbloom cluster` lists them. -- Their tensor parallel serves once its code is in the build (Gemma 4 and MiMo tensor parallel PRs); until then they pair as a pipeline. MiMo-V2.6-Flash's speculative pipeline, its default split, is declared too. diff --git a/changelog.d/cluster-service-follows-repair.md b/changelog.d/cluster-service-follows-repair.md deleted file mode 100644 index d321ed5bd3..0000000000 --- a/changelog.d/cluster-service-follows-repair.md +++ /dev/null @@ -1,6 +0,0 @@ -### A running cluster service answers after the Macs pair again - -- When the two Macs pair again while their cluster services run (`darkbloom cluster` or `darkbloom cluster pair`), each service starts its setup and control-lease listeners again with the new pairing within about 5 seconds. They used to keep the earlier pairing's key until the service restarted, so the other Mac's leases and its "Reading both Macs over the cable" step were refused (`refused (handshakeRejected)`). The service log says `this Mac's pairing changed (): answering the paired Mac with the new one`. -- A Mac left with no pairing stops answering over the cable. A pairing store that cannot be read leaves the listeners as they are. -- A Mac that paired again under a new Secure Enclave key of its own drops its earlier control state, as it already did when the other Mac's key changed. -- A cluster service started by an earlier release keeps the earlier behavior until it restarts (log out and back in, or `darkbloom cluster stop --service` and then `darkbloom cluster`). diff --git a/changelog.d/fastest-plan-evidence.md b/changelog.d/fastest-plan-evidence.md deleted file mode 100644 index 83485417a1..0000000000 --- a/changelog.d/fastest-plan-evidence.md +++ /dev/null @@ -1,7 +0,0 @@ -### Tensor parallel for Gemma 4 and MiMo only on measured speed - -- Gemma 4 and MiMo V2.6 Flash pairs choose tensor parallel only once tensor parallel's own speed is measured on both Macs: each Mac's half timed by a tensor-parallel load (Gemma), or requests this Darkbloom build served in tensor parallel. An estimate from the Macs' device index alone does not choose it, because the index overstates what half a model saves on big Macs: on two M5 Ultra it predicts a short Gemma request 6% faster in tensor parallel, where the plans expect decode 6-8% slower. -- When the estimate says tensor parallel would be faster, the pair keeps the pipeline. The plan's "Tensor parallel or pipeline" line says the predicted gain and that it comes from the device index, and the model list says "tensor parallel: not measured yet". -- Normal setups do not load tensor parallel to measure it, so these pairs keep the pipeline for now. MiMo does not yet time its halves at load, so MiMo pairs reach tensor parallel only from requests the same build served in tensor parallel. -- Tensor parallel must also keep every feature of the mode it would replace (see "Tensor parallel only where it keeps every feature"). -- Qwen and GLM still choose tensor parallel wherever it fits. diff --git a/changelog.d/fresh-mdm-removal-guidance.md b/changelog.d/fresh-mdm-removal-guidance.md deleted file mode 100644 index e6b044c65c..0000000000 --- a/changelog.d/fresh-mdm-removal-guidance.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fresh MDM removal guidance - -- Keep `darkbloom status` and both `darkbloom doctor` authorization summaries from offering MDM removal when the coordinator decision is too old for removal readiness. An unexpired App Attest serving lease stays visible; removal advice asks for fresh readiness and keeps existing profiles installed. The `darkbloom unenroll` checks are unchanged. diff --git a/changelog.d/gemma-byte-fallback-flush.md b/changelog.d/gemma-byte-fallback-flush.md deleted file mode 100644 index 3f22c7588c..0000000000 --- a/changelog.d/gemma-byte-fallback-flush.md +++ /dev/null @@ -1,6 +0,0 @@ -### Gemma 4 replies keep characters outside its vocabulary - -- A Gemma 4 reply that ended in characters its vocabulary writes as byte tokens, such as many newer emoji, rare CJK and most Hangul syllables, lost all of them: `all zipped up 🗜` came back as `all zipped up `, and a reply made only of such characters came back empty. A long reply could also corrupt such a character when streaming restarted its decode inside its bytes. -- The Swift tokenizer library releases byte tokens only when a later token arrives. The provider's tokenizer bridge now releases a trailing run itself. `/detokenize` keeps it too. -- Token IDs, numeric logprobs, sampling and cache keys do not change, with one exception: a stop string that a trailing run completes now matches when the run completes, one token sooner, so `completion_tokens` can fall by one. -- A streamed reply's `logprobs` gains the entries of those tokens, which it used to drop. A byte token's `logprobs` text and `bytes` are U+FFFD or its ASCII character instead of empty, not the real byte. A reply cut inside a character by `max_tokens` now ends in U+FFFD instead of dropping it. diff --git a/changelog.d/gemma-decode-command-buffers.md b/changelog.d/gemma-decode-command-buffers.md deleted file mode 100644 index 49963036d1..0000000000 --- a/changelog.d/gemma-decode-command-buffers.md +++ /dev/null @@ -1,3 +0,0 @@ -### Gemma 4 plain decode commits by operation count - -- Plain decode steps of Gemma 4, the rows served without its assistant, commit a Metal command buffer every 100 operations instead of many times per step. Outputs are bitwise identical. Prefill and assistant rounds keep MLX's defaults. diff --git a/changelog.d/gemma-decode-keeps-spaces.md b/changelog.d/gemma-decode-keeps-spaces.md deleted file mode 100644 index 7b902c5121..0000000000 --- a/changelog.d/gemma-decode-keeps-spaces.md +++ /dev/null @@ -1,5 +0,0 @@ -### Gemma 4 text keeps its spaces before punctuation - -- Gemma 4 replies, reasoning and tool arguments no longer lose the space before `.`, `,`, `?` and `!`, or repeat a quote. `git add .` came back as `git add.`, `bash ./run.sh` as `bash./run.sh`, `x != y` as `x!= y`, and, when streamed, `role = 'start'` as `role = ''start'`. -- Gemma 4's published `tokenizer_config.json` omits `clean_up_tokenization_spaces`, and the Swift tokenizer library reads a missing key as cleanup on, where Python Transformers reads it as off. The provider now resolves a missing key to off in memory for every model. An explicit Boolean is kept. -- Token IDs, sampling, model state and cache keys do not change. Only the text decoded from the same tokens does. Stop strings match the text as spelled: one with a space before punctuation can now match, and one that matched only the cleaned text (`add.` for `add .`) no longer does. diff --git a/changelog.d/gemma-pipeline-speed.md b/changelog.d/gemma-pipeline-speed.md deleted file mode 100644 index 171b5279d8..0000000000 --- a/changelog.d/gemma-pipeline-speed.md +++ /dev/null @@ -1,5 +0,0 @@ -### Faster Gemma 4 pipeline pairs - -- Gemma 4 pipeline stages compute a prompt chunk's expert blocks in one shared dispatch per operation instead of one subgraph per prompt token, with the same bytes for every token (unchanged arithmetic receipt). Batch-decode rows share the same dispatch. On one synthetic expert layer this cut a 2,048-token chunk from about 370 ms to about 31 ms; pair throughput is not yet measured. -- A Gemma 4 pipeline pair whose setup prefills serially, coordinator-registered pairs included, now serves four requests at once. Each lane is admitted against live memory on both Macs. A pair planned with the one-chunk lookahead keeps serving one request at a time. -- The planner's hardware prior counts 8 of Gemma 4's 128 experts per token instead of every expert byte. diff --git a/changelog.d/gemma-tensor-parallel.md b/changelog.d/gemma-tensor-parallel.md deleted file mode 100644 index e2ecce6bfb..0000000000 --- a/changelog.d/gemma-tensor-parallel.md +++ /dev/null @@ -1,7 +0,0 @@ -### Gemma 4 tensor parallel on two-Mac clusters - -- Gemma 4 26B (QAT 4-bit and 8-bit) can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels, both share every token over the encrypted link, and the pair returns the same tokens a single Mac would on the synthetic checks. Text only. -- The planner chooses tensor parallel for Gemma 4 only where it predicts it faster than the pipeline, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Prompt-heavy requests keep the pipeline. Qwen and GLM still choose tensor parallel wherever it fits. -- In tensor parallel, Gemma 4 returns logprobs (`logprobs` / `top_logprobs`), and each Mac reserves memory for its own half of the model: about 8.0 GB of weights at QAT 4-bit (14.9 GB at 8-bit) plus its own KV, with a conservative 5.5 GiB activation reserve until a pair measures one. -- Gemma 4 tensor parallel keeps prompt prefixes as the pipeline does, in memory and in the encrypted SSD tier: a repeated or shared prompt prefix is restored only when both Macs hold it, with exactly the tokens of a request that prefilled the whole prompt, and it survives a restart of both Macs. Each request reserves room for its own prompt's prefix (about 0.44 GB a Mac for a 32K-token prompt); kept prefixes use free memory only and are dropped first when memory runs short. -- Gemma 4 tensor-parallel pairs serve one request at a time unless `DARKBLOOM_CLUSTER_BATCH_LANES` names more. Speed on a real pair is not measured yet. diff --git a/changelog.d/glm-tensor-parallel-stop-race.md b/changelog.d/glm-tensor-parallel-stop-race.md deleted file mode 100644 index e107a4a153..0000000000 --- a/changelog.d/glm-tensor-parallel-stop-race.md +++ /dev/null @@ -1,4 +0,0 @@ -### A latent stop race in GLM tensor parallel's one-token decode - -- No released pair is affected, and serving is unchanged: every v0.10.6 GLM-5.3-Flash tensor-parallel pair loads the model's NextN (MTP) layer and decodes every request in MTP rounds, which already end both Macs together when a request stops just before the model's end token. -- The one-token decode, which only a build without that layer runs, now does the same: both Macs end at the end token and return the text up to the stop (for example, a stop string that matched just before the answer ended). Before, the stopped Mac built one more step alone and waited in a collective the other Mac, already finished at that token, never joined, so the request would stall and fail on both Macs. diff --git a/changelog.d/gptoss-decode-command-buffers.md b/changelog.d/gptoss-decode-command-buffers.md deleted file mode 100644 index 986e75d062..0000000000 --- a/changelog.d/gptoss-decode-command-buffers.md +++ /dev/null @@ -1,3 +0,0 @@ -### GPT-OSS plain decode commits by operation count - -- Plain decode steps of GPT-OSS commit a Metal command buffer every 100 operations instead of after almost every MoE layer. Outputs are bitwise identical. Prefill keeps MLX's defaults. diff --git a/changelog.d/mimo-pipeline-decode-buffers.md b/changelog.d/mimo-pipeline-decode-buffers.md deleted file mode 100644 index 7f38c5d844..0000000000 --- a/changelog.d/mimo-pipeline-decode-buffers.md +++ /dev/null @@ -1,15 +0,0 @@ -### MiMo pipeline decode command buffers and expert routing - -- MiMo V2.6 Flash pairs encode decode steps, lane steps and speculative rounds - in Metal command buffers of up to 100 operations with no input-size bound, as - GLM and Qwen tensor parallel already do. Prefill keeps the rank's limits. - Tokens, logits and caches are byte-identical on synthetic stages. The speed - effect on the registered model has not been measured yet. -- A MiMo request's memory charge now prices every full-attention layer's decode - score rows at once, which the larger command buffers can keep alive together. - The LOAD quote is unchanged. Only requests whose prompt frames are shorter - than a stage's full-attention layers times the decode rows (32 tokens at most) - are charged slightly more. -- The planner's hardware prior now counts MiMo's routed experts at the 8 of 256 - a token uses: 10.77 GB read per decode step instead of 166.6 GB. The prior - prices only tensor parallel, so MiMo's pipeline plans are unchanged. diff --git a/changelog.d/mimo-rotating-cache-metadata.md b/changelog.d/mimo-rotating-cache-metadata.md deleted file mode 100644 index 8e62c2009e..0000000000 --- a/changelog.d/mimo-rotating-cache-metadata.md +++ /dev/null @@ -1,11 +0,0 @@ -### MiMo image-candidate pairs keep cluster prompt prefixes - -- A MiMo V2.6 Flash pair serving the private, local-only image candidate no - longer fails its requests while the cluster prefix cache is on (the - default). That candidate is the only MiMo load with contiguous caches. MiMo - still required the five metadata values that older MLX SDKs wrote for a - sliding-window cache, while the pinned SDK writes seven (adding the capacity - origin and a wrapped flag), so requests, text or image, failed at their - first prompt-prefix capture. Prefixes are now captured and restored. The - four text serving modes use paged histories with prefix reuse off and were - not affected. diff --git a/changelog.d/mimo-tensor-parallel.md b/changelog.d/mimo-tensor-parallel.md deleted file mode 100644 index 6b524874ca..0000000000 --- a/changelog.d/mimo-tensor-parallel.md +++ /dev/null @@ -1,7 +0,0 @@ -### MiMo V2.6 Flash tensor parallel on two-Mac clusters - -- MiMo V2.6 Flash text can run tensor parallel on a pair: each Mac holds half of every layer's heads and expert channels and half of the output head, both share every token over the encrypted link, and on the synthetic checks the two Macs agree bit for bit with a one-process simulation of both halves. The image candidate stays a pipeline. -- Each Mac's half of a layer's attention output and feed-forward is kept at full 32-bit precision until both halves are added, then rounded once, so a pair never rounds more than one Mac does. On the synthetic checks, the two halves of an expert's output add up bit for bit to the full output that one Mac rounds once. -- The planner chooses tensor parallel for MiMo only where it predicts it faster than the pipeline with speculative decoding, which MiMo's qualification records credit 1.37x, from tensor parallel's own speed measured on both Macs (see "Tensor parallel for Gemma 4 and MiMo only on measured speed"). Two 128 GB Macs, which cannot hold MiMo alone, can serve it this way. Qwen and GLM still choose tensor parallel wherever it fits. -- In tensor parallel, MiMo returns logprobs (`logprobs` / `top_logprobs`), serves one request at a time with speculative decoding (see "MiMo V2.6 Flash tensor parallel with speculative decoding"), and each Mac reserves memory for its own half: 84.0 GB of weights plus its own KV, work and buffers, with a conservative 5.5 GiB activation reserve until a pair measures one (about 100 GiB per Mac at the longest request, the draft heads included). -- No MiMo tensor-parallel qualification record exists yet, and speed on a real pair is not measured. diff --git a/changelog.d/mimo-tp-speculative.md b/changelog.d/mimo-tp-speculative.md deleted file mode 100644 index 6641eb2cd0..0000000000 --- a/changelog.d/mimo-tp-speculative.md +++ /dev/null @@ -1,8 +0,0 @@ -### MiMo V2.6 Flash tensor parallel with speculative decoding - -- A MiMo V2.6 Flash tensor-parallel pair decodes with MiMo's own trained draft heads: each round checks up to two drafted tokens in one pass through the pair, so every token a round keeps shares that pass's link and weight costs. -- It is on by default: the installed provider starts both Macs' tensor-parallel workers with two drafts a round. -- Output is identical to tensor parallel without drafting, token for token and bit for bit on the synthetic checks: greedy (with or without logprobs) and sampled. Each Mac's halves stay at full 32-bit precision inside a round too, exactly as in a one-token step. Every kind of stop works inside a round. Requests with penalties or a logit bias, and sampled requests that ask for logprobs, decode one token at a time, as in the speculative pipeline. -- Each Mac holds the draft heads whole (about 2 GB more) and reserves their per-request state, and the plan counts both before it chooses tensor parallel. Two 128 GB Macs still fit, at about 100 GiB a Mac. -- Because MiMo's tensor parallel now keeps the speculative pipeline's rounds, feature parity no longer holds it back where that pipeline is the mode it would replace; its measured speed decides, and the plan credits the rounds no speed-up until they are measured. Where the plain pipeline is the mode it would replace, that pipeline's batch lanes still keep it. -- Not yet measured on a real pair: the speed-up, the heads' acceptance rate and qualification records. diff --git a/changelog.d/models-page-network-registration.md b/changelog.d/models-page-network-registration.md deleted file mode 100644 index e38dff93e8..0000000000 --- a/changelog.d/models-page-network-registration.md +++ /dev/null @@ -1,5 +0,0 @@ -### The Models page shows what the network registered - -- Each model on the Models page now says whether this Mac's live registration carries it: "Registered with the network" (the network sends it requests), "Registered for Autopilot" (Autopilot can load it), or, for a selected or pool model, a warning "Not registered with the network yet". Before, the page showed only what was selected, downloaded or loaded, so a selected model the network did not know looked like it was serving. -- The provider writes the registered set to its state file (`registered_models`). -- A Mac with Autopilot that is busy at every check, or always under a lease, now reports a newly verified build after at most 10 minutes. The re-registration closes admission, lets accepted requests finish, then reconnects. Before, such a Mac could wait without end, and Autopilot could not use the build. diff --git a/changelog.d/pipeline-decode-buffers.md b/changelog.d/pipeline-decode-buffers.md deleted file mode 100644 index 05582151fa..0000000000 --- a/changelog.d/pipeline-decode-buffers.md +++ /dev/null @@ -1,15 +0,0 @@ -### Pipeline decode command buffers for the remaining cluster models - -- Cluster pairs of the Qwen and Bonsai rows, Nemotron 3.5 Lightning, Gemma 4, - GPT-OSS 20B and GLM-5.3-Flash encode decode steps (pipeline and phase split), - lane steps and speculative rounds in Metal command buffers of up to 100 - operations with no input-size bound, as GLM and Qwen tensor parallel already - do. Prefill keeps the rank's limits. Tokens, logits and caches are - byte-identical on synthetic stages. The speed effect on registered models has - not been measured yet, and each family keeps the change only if a pair A/B - shows a gain. -- A request's memory charge on those pairs, other than GLM's, now prices every - attending layer's decode rows at once, which the larger command buffers can - keep alive together. The LOAD quotes are unchanged. Only requests whose prompt - frames are shorter than their decode rows (at most 80) are charged more, and - only on a rank that decodes. diff --git a/changelog.d/provider-enabled-filter-wins.md b/changelog.d/provider-enabled-filter-wins.md deleted file mode 100644 index fcf1abe7b2..0000000000 --- a/changelog.d/provider-enabled-filter-wins.md +++ /dev/null @@ -1,7 +0,0 @@ -### The enabled-model filter wins over coordinator model changes - -- A model you deselect with `darkbloom switch` or delete with `darkbloom models remove` no longer comes back on its own. Before, when the coordinator moved a public model to a newer build, every Mac serving that model downloaded the newer build, served it in place of the build its operator chose and loaded it, even when `enabled_models` left it out. For example, with `gemma-4-26b` selected and `gemma-4-26b-qat-4bit` deselected, `gemma-4-26b-qat-4bit` returned within minutes and `darkbloom status` showed `Serving outside the enabled model filter: gemma-4-26b-qat-4bit`. -- With `enabled_models` set, the provider now refuses a coordinator `load_model` or `prefetch_model` for a model outside it (`model_not_selected`), and keeps serving the build you selected when its public model moves to a build you did not list. The log then says `desired_models: → is outside the enabled model filter; not converging`. -- **Your provider no longer moves to a new build of a model by itself.** To take one, run `darkbloom switch` and pick the model's public name; the picker shows its newest build under that name. Until you do, the newer build gets that model's requests first. -- `darkbloom switch` applies its selection as the filter at once, without a restart. -- Nothing changes with an empty `enabled_models` (serve every downloaded model), or for Autopilot's consented downloads and placements. diff --git a/changelog.d/provider-process-exit-wait.md b/changelog.d/provider-process-exit-wait.md deleted file mode 100644 index 5771412db8..0000000000 --- a/changelog.d/provider-process-exit-wait.md +++ /dev/null @@ -1,3 +0,0 @@ -### Child process exit waits - -- Report a finished child process without the former polling and run-loop delay. Bounded children (the paged-kernel preflight, update staging, runtime smoke and signature checks, `darkbloom doctor` and `verify` probes) are reported up to about 120 ms sooner each, and waiting for `launchctl`, `codesign`, `profiles`, `open` and `log` no longer runs the calling thread's run loop. Timeouts and the SIGTERM-then-SIGKILL escalation are unchanged. diff --git a/changelog.d/provider-status-app-attest-lease.md b/changelog.d/provider-status-app-attest-lease.md deleted file mode 100644 index 36f92ec11d..0000000000 --- a/changelog.d/provider-status-app-attest-lease.md +++ /dev/null @@ -1,3 +0,0 @@ -### Provider status App Attest lease - -- Keep `darkbloom status` and `darkbloom doctor` reporting App Attest authorization until the coordinator lease expires. They required a renewal within the last 10 seconds, so one delayed renewal showed `Trust: self_signed / online` although serving continued. `darkbloom unenroll` still requires a renewal within 10 seconds before offering MDM removal. diff --git a/changelog.d/provider-update-rollback.md b/changelog.d/provider-update-rollback.md deleted file mode 100644 index ffa75cc843..0000000000 --- a/changelog.d/provider-update-rollback.md +++ /dev/null @@ -1,7 +0,0 @@ -### Roll a Mac back to its previous release - -- `darkbloom update --rollback` restores the release a Mac ran before its last update. When the updater installs a release, it keeps the signed release it replaces; the rollback puts that release back, also after the new one has served for 10 minutes and was promoted. -- It shows the installed and restored versions and asks `Roll back to vX? [y/N]` before changing anything (`--yes` skips the question). The running provider finishes its accepted requests (`--timeout`, `--force` as for `darkbloom update`), the kept release replaces the installed one in the watchdog's journaled swap under the update lease, and the provider restarts on it. It contacts no coordinator. -- The rolled-back release is quarantined on that Mac: the provider's 30-minute update check, the startup check and the watchdog do not reinstall it, and the next newer release installs normally, so automatic updates can stay on. `darkbloom update --override-quarantine` installs it again on request. -- It refuses and changes nothing on a Mac that serves in a `darkbloom cluster` pair, while a provider runs in the foreground (`darkbloom start --foreground`), while another update or recovery runs, when no earlier release is kept or the kept one is already installed, when the installed bundle is not the release the updater recorded, and when the kept release fails its hash or signature check. -- Only one earlier release is kept. A Mac rolls back to the release it ran before its last update, not further. diff --git a/changelog.d/qwen27-tp-decode-control.md b/changelog.d/qwen27-tp-decode-control.md deleted file mode 100644 index 28d8a95e36..0000000000 --- a/changelog.d/qwen27-tp-decode-control.md +++ /dev/null @@ -1,22 +0,0 @@ -### Qwen tensor-parallel decode control in the selection sum - -- A Qwen tensor-parallel pair's plain decode step now carries the next step's - plan and report in its own sealed selection sum, so the step pays one sealed - sum and one host read fewer than before. Tokens, logits and native state are - unchanged; assisted (MTP) rows, prompt steps and idle steps keep their own - exchange. -- Owner answers, cancellations and joins now apply one step later while plain - rows decode. A row decodes its next token once the owner answered the token - before it, so an answer that arrives while a step computes no longer leaves - the row idle for a step. Rank 0 still publishes a token only after the - owner's answer to the one before it. A token selected before a stop answer is - never published, so streamed text, usage and logprobs are unchanged. -- A clean stop the owner asks for (a stop string, for example) can cost one - more forward, which is discarded. On a one-lane pair every such stop after a - request's first token does (assisted rows excepted), and that request's - finish arrives one decode step later than before. -- Both ranks of a pair must run this build: the load agreement binds the new - control wire (`qwen-tp-independent-history-batch-v2-folded-control`). -- `darkbloom-cluster-tp-check qwen-decode` times the batch driver's decode on - two ranks over the loopback ring, with the control exchanged or folded, and - checks that both retire the same tokens. diff --git a/changelog.d/qwen27-tp-decode-loop.md b/changelog.d/qwen27-tp-decode-loop.md deleted file mode 100644 index 8afa8a9b3b..0000000000 --- a/changelog.d/qwen27-tp-decode-loop.md +++ /dev/null @@ -1,25 +0,0 @@ -### Qwen tensor-parallel decode routes, row exactness and finiteness check - -- A Qwen3.8-27B tensor-parallel row now decodes the same bytes alone as beside - other rows and in verify windows on the registered weights. A one-row decode - step's fused SwiGLU computed its sigmoid with Metal's fast `exp`, while - cohort and window steps use MLX's precise `exp`. The two round a gate of - exactly bf16 -6.84375 differently, which could change later tokens. Dense - Qwen tensor-parallel output changes only where a one-row decode step meets - that gate value, and there it now equals the cohort path. Regenerate - tensor-parallel serving references recorded with earlier builds once. - Single-Mac output is unchanged. -- A non-finite logit on either rank of a Qwen tensor-parallel pair now fails - both ranks in the same selection step, before any token is published; - previously the other rank waited in the selection collective. The check moved - into the selection's sealed sum, so a decode step no longer pays a separate - finiteness read. Selected tokens are unchanged. -- Each rank logs its decode routes once per load, when it first serves - (`darkbloom-qwen-tp-decode-census-v1`): which projections take the - batch-invariant kernel and at which layout per row count, the attention and - residual-norm routes, and the arithmetic switches in force. -- `darkbloom-cluster-tp-check qwen-rows` checks, on one Mac over the loopback - ring, that a Qwen3.8-27B row decodes the same bytes alone, beside other rows - and in verify windows at the registered per-rank widths, with random weights - that follow the registered artifact's value statistics or with the registered - checkpoint itself; `qwen-rows layers` names the first layer that differs. diff --git a/changelog.d/qwen27-tp-default-lanes.md b/changelog.d/qwen27-tp-default-lanes.md deleted file mode 100644 index beaec56878..0000000000 --- a/changelog.d/qwen27-tp-default-lanes.md +++ /dev/null @@ -1,20 +0,0 @@ -### Qwen tensor-parallel pairs serve up to 8 requests at once, sized to memory - -- `darkbloom cluster` now sets how many requests a Qwen tensor-parallel pair - serves at once: 8, 6, 4 or 2, the most that both Macs' memory holds now with - the full load reservation for that many. The pair serves them from its first - load. Before, it served one at a time: a local pair widened only after a - burst, through a reload the burst waited for, and a pair serving Darkbloom - traffic never widened. -- On two idle Macs, Qwen3.8-27B serves 8 at once from 64 GB a Mac without the - speculative assistant (4 at 48 GB, 2 at 32 or 36 GB), and 8 from 96 GB a Mac - with it (local clusters only); smaller Macs serve fewer. Two M5 Ultras serve 8 either - way. When not even 2 fit, the pair serves one request at a time, as before. -- Memory safety is unchanged: both Macs reserve that many requests' full memory - when the model loads and admit each request alone. A local pair set up - narrower still widens when requests queue; a pair set up for 8 is never - reloaded for it. -- Existing setups keep serving one request at a time until they are planned - again, as after an update. A pair serving Darkbloom traffic keeps its width - beside its approval; no approval, registration or committed-start digest - changes. diff --git a/changelog.d/qwen27-tp-prefill.md b/changelog.d/qwen27-tp-prefill.md deleted file mode 100644 index 2f113dafb5..0000000000 --- a/changelog.d/qwen27-tp-prefill.md +++ /dev/null @@ -1,17 +0,0 @@ -### Qwen tensor-parallel prompt wavefront - -- A Qwen tensor-parallel pair now prefills a text prompt faster, in steps of up - to eight consecutive 512-token frames built as one graph, layer by layer: - while one frame's sealed sum crosses the link, the next frame computes. Every frame - keeps its own shapes and kernels, so logits, KV, recurrent state, prefix - captures and tokens are unchanged. Steps run two frames while another lane - decodes and end at the prompt-cache capture point. Media prompts, assisted - (MTP) prompts, packed KV and routed-expert models keep one frame a step. -- The merged step's frames in flight are charged in LOAD, the placement quote - and each request's charge: a Qwen3.8-27B tensor-parallel rank needs about - 367 MB more at any width. -- `darkbloom-cluster-tp-check qwen-prefill --wavefronts 1,8` and - `darkbloom-cluster-tp-check qwen-wavefront` measure the merged steps on one - rank and on two ranks over the loopback ring. - `DARKBLOOM_QWEN_TP_PROMPT_WAVEFRONT=0` restores one frame a step for - diagnosis; both ranks must agree. diff --git a/changelog.d/qwen27-tp-prefix-depth.md b/changelog.d/qwen27-tp-prefix-depth.md deleted file mode 100644 index 81b1598c15..0000000000 --- a/changelog.d/qwen27-tp-prefix-depth.md +++ /dev/null @@ -1,6 +0,0 @@ -### Qwen3.8 27B tensor parallel reuses whole prompt prefixes - -- A Qwen tensor-parallel pair now reuses a repeated prompt's prefix to its last whole 512-token chunk instead of at most 4,096 tokens, including prompts longer than 32,768 tokens: a repeated 33K-token prompt restores 32,768 tokens on both Macs, as one Mac does. It also keeps the boundaries the next turn of a conversation and prompts that share a long system prompt need, so in each of these cases it reuses at least what one Mac reuses, to the nearest 512 tokens. -- A prefix restored from memory returns exactly the tokens of a request that prefilled the whole prompt (checked bit for bit on synthetic pairs at 8K, 16K and 32K boundaries); one restored from the SSD tier's default `balanced` records is close but not identical, as before. Both Macs must hold a boundary; otherwise both start from zero. -- Each request reserves room for its own prompt's prefix (about 1.8 GB a Mac for a 32K-token prompt on the 27B), and a pair loads with one such prefix per lane: about 1.1 GB a Mac more than before at one lane. Every pair size that ran the 27B in tensor parallel still does. Kept prefixes use free memory only (half of what is left after loading) and are dropped first when memory runs short. Prefixes kept on SSD by an earlier build are not reused. -- Requests served by the assistant (MTP) lanes still reuse at most 4,096 prompt tokens, less than one Mac reuses for a long prompt; deepening them is a separate change. Speed on a real pair is not measured yet. diff --git a/changelog.d/reasoning-stop-outside-reasoning.md b/changelog.d/reasoning-stop-outside-reasoning.md deleted file mode 100644 index ce6d54f182..0000000000 --- a/changelog.d/reasoning-stop-outside-reasoning.md +++ /dev/null @@ -1,18 +0,0 @@ -### Stop sequences no longer match Gemma 4 or `` reasoning - -- A client `stop` sequence on Gemma 4 models such as `gemma-4-26b-qat-4bit`, - and on models that reason in `` blocks (Qwen 3.5, 3.6 and 3.8, - among others), now matches only the text returned as `content`. With - reasoning on, it used to match the reasoning too, so a sequence that - appeared while the model reasoned (for example `"."` or `"\n\n"`) ended the - request before any answer: `finish_reason` `stop`, reasoning only, empty - content. -- With tools declared, tool-call frames are not cut either, except a frame - whose arguments quote its own closing tag, or a bare `` frame - written without its wrapper. When a request has no tool handler (no declared - tools, or a media request on a family without native media tools), a literal - tool tag in an answer is text the client receives, and stops still apply to it. - Whitespace before the answer's first character (the blank line after - ``) cannot complete a stop sequence on its own. -- A stop sequence that names a marker no longer fires on it: ``, or - `` with tools declared. diff --git a/changelog.d/sandbox-setup-plan.md b/changelog.d/sandbox-setup-plan.md deleted file mode 100644 index 20821ad746..0000000000 --- a/changelog.d/sandbox-setup-plan.md +++ /dev/null @@ -1,9 +0,0 @@ -### Sandbox setup shows the add-on's own sizing plan - -- `darkbloom sandbox setup` now asks the Darkbloom Sandbox installer for the add-on's own plan before it asks you to confirm. After its own chip, macOS, session, network, power and sleep checks, setup runs the downloaded installer with `--plan` (add-on 1.1.1 and later). The installer verifies the release and sizes this Mac without installing anything. Setup then prints the plan's cores, memory and disk lines and how many Linux and macOS jobs this Mac can run at a time. Example: `Disk: 157 GiB free; 100 GiB stays free for you; Linux images 4 GiB + 30 GiB per Linux job; macOS images 46 GiB + 40 GiB per macOS job`. -- Disk follows the add-on's rules. A tenth of the disk (50 to 100 GiB) stays free. The first job of a platform also needs that platform's VM images (Linux 4 GiB, macOS 46 GiB, nothing once installed). Each Linux job takes 30 GiB and each macOS job 40 GiB. -- When no job fits, setup prints the plan's message and how much disk to free for one Linux job and for one macOS job. It then stops without installing. -- The installer is now downloaded before the question, so the plan is shown before you confirm. Nothing is installed before you answer `y`. -- With an older installer that cannot report a plan, setup prints `[INFO] Sizing` and estimates with the same rules. -- Setup's output is line-buffered: run over ssh or into a pipe, it shows the approval link as soon as the installer has it, not once setup ends. -- With add-on 1.1.2 and later, a Mac waiting for approval keeps waiting in the background, also across restarts, and enrolls by itself, and setup now says so. On the waitlist it says you can close the window, and after Ctrl-C it says that the Mac keeps waiting; both point at `darkbloom sandbox status`. With an earlier add-on, setup words both as before. diff --git a/docs/developer/build.md b/docs/developer/build.md index 0bb6d88d4e..6e18a940bf 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -167,7 +167,11 @@ and linking on that SDK. Ordinary development retains the package's Swift 6.3 minimum; release evidence must use the selected release toolchain. Pinned Python 3.12.10 and checksum-verified CMake 3.31.12 provide missing build -tools. `scripts/prepare-metal-toolchain.py` requires a working compiler probe, +tools. `scripts/install-release-cmake.sh` uses the CMake 3.31.12 that Darkbloom macOS +images unpack from the same checksum-verified archive into +`$RUNNER_TOOL_CACHE/cmake/3.31.12/universal`, when its `universal.complete` +marker exists and the binary reports that exact version; elsewhere it +downloads and verifies the 80 MB archive. `scripts/prepare-metal-toolchain.py` requires a working compiler probe, not merely a completed component download. It clears stale discovery state, waits boundedly for registration, and uses Apple's component export/import fallback. The specific transient asset-catalog download error gets at most @@ -189,11 +193,11 @@ On the `dev` branch a plain `swift build` is a DevNet build: `prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a production binary from the `dev` branch. -CI enforces both defaults. The Release Integrity job runs +CI enforces the master default. CI (master)'s Release Integrity job runs `scripts/provider-build-default.py`: a pull request into master, or a push to -master, fails unless the default is `prod`; one into or to `dev` fails unless -it is `dev`. Every release of master runs the same check and stops before the -build if the default is not `prod`. +master, fails unless the default is `prod`. Every release of master runs the +same check and stops before the build if the default is not `prod`. CI (dev) +has no Release Integrity, so no CI job checks `dev`'s default. Use the `dev` branch to run a provider from source against the DevNet coordinator. A push to `dev` that changes the provider publishes the DevNet @@ -243,6 +247,57 @@ the selected product without treating an old build-directory layout as a resource authority. Keep its archive/path checks and source-matched staging; see [resource and release tooling checks](test.md#focused-tooling-checks). +## CI Workflows + +Two workflows run CI. Both run the same plan, `.github/workflows/provider-plan.yml` +(the component classifier, the tree lookup and the run's one route request), +then the same tests, `.github/workflows/provider-tests.yml` (the provider +shards, the cluster jobs and the `Provider Tests` gate). Pull requests and +pushes run the same jobs; only pushes save caches. + +CI tests each change once (`scripts/ci-tested-tree.py`). The gate of a passing +run that tested something uploads an empty artifact named +`ci-tested----p<0|1>c<0|1>m<0|1>`: the tree it tested, the +event's base and head commits (`push` and the pushed commit for a push), and +the components that ran (provider, cluster, MiMo audio). Before testing, a run +looks for a record of its own change that covers every component it selected: + +- a pull request: its own tree, base and head; +- a push of commit S: S's tree with S's two parents as base and head (the pull + request that S merges, tested against S's first parent), or an earlier run of + the same push. + +The record counts only when the run that uploaded it completed successfully, +ran the same workflow file of this repository (not a fork) for the matching +event, and tested the record's head commit. Then the run starts no test job +and the gate passes, citing that run. A pull request is tested on its test +merge commit, so the push of its merge commit, when the base branch did not +move meanwhile, has the same tree and is not tested again. A squash or rebase +merge has one parent and is tested again. Any doubt (no record, a failed or +foreign run, an API error) runs the tests. Such a push runs one build-only job +instead, Refresh build caches, for the components it changed, so the branch +caches stay fresh. + +Pull requests and pushes into `dev` select the components their diff touches. +Pushes to `master` and pull requests into `master` select every component, so a +`master` record always covers the whole suite. + +The gate also checks the CI plans on every run, skipped or not: the cluster +plan's audit (`scripts/cluster-test-plan.py audit`) and the self-tests of the +shard plans, the component classifier, the tested-change lookup, the route and +the workflow pins. `dev` has no Release Integrity, so these run there too. + +| Workflow | Runs for | Jobs | +|---|---|---| +| `ci-dev.yml` (CI (dev)) | pull requests into any branch but `master` (`dev` and stacked branches), pushes to `dev` | the tests only | +| `ci-master.yml` (CI (master)) | pull requests into `master`, pushes to `master` | the tests, `Release Integrity` and `Docs Lint` | + +Release Integrity and Docs Lint are CI (master)'s own jobs, so their checks keep +their plain names (`master`'s ruleset requires `Release Integrity`). The test +jobs' checks carry the caller's job name: `Tests / Provider Tests`. The +contribution gates in `docs-impact.yml` (Commit Signatures, Docs Impact) run +only for pull requests into `master`. + ## CI Runner Routing `.github/workflows/darkbloom-route.yml` chooses where read-only CI jobs run: a @@ -254,14 +309,33 @@ lane, `format('-{0}', matrix.shard)`. | Workflow | Routed jobs | Fallback | |---|---|---| -| `ci.yml` | `release-integrity`, `docs` | `blacksmith-4vcpu-ubuntu-2404` | -| `ci.yml` | `test-provider` (lanes `test-provider-1` to `test-provider-3`, one per shard), `test-provider-summary`, `test-provider-sdk`, `test-cluster-checks`, `test-cluster` (lanes `test-cluster-1` to `test-cluster-3`), `test-cluster-gpu` (lanes `test-cluster-gpu-1` and `test-cluster-gpu-2`), `test-cluster-focused` | `blacksmith-12vcpu-macos-27` | +| `provider-tests.yml` (lanes requested by `provider-plan.yml`) | `test-provider` (lanes `test-provider-1` and `test-provider-2`, one per shard), `test-cluster` (lanes `test-cluster-1` and `test-cluster-2`), `test-cluster-gpu` (lanes `test-cluster-gpu-1` and `test-cluster-gpu-2`), `test-cluster-focused`, `refresh-caches` (pushes of a tested tree) | `blacksmith-12vcpu-macos-27` | +| `ci-master.yml` (lanes requested by `provider-plan.yml`) | `release-integrity`, `docs` | `blacksmith-4vcpu-ubuntu-2404` | | `docs-impact.yml` | `commit-signatures`, `docs-impact` | `blacksmith-4vcpu-ubuntu-2404` | | `landing.yml`, `desktop.yml`, `nightly-linear-package.yml` | `check`, `frontend`, `test` | `blacksmith-4vcpu-ubuntu-2404` | | `provider-release-cache.yml` | `warm`, pull requests only | `blacksmith-12vcpu-macos-27` | +`.github/workflows/darkbloom-watchdog.yml` is darkbloom-sandbox's GitHub-side +watchdog (`public/darkbloom-actions/.github/workflows/watchdog.yml` at +31236c54), copied unchanged: update it by copying a newer one, never by +editing. Every 10 minutes it finds a run of this repository whose job with a +Darkbloom label has waited queued with no runner for +`DARKBLOOM_WATCHDOG_MINUTES` while no Darkbloom job of the run moved, marks +it with a `Darkbloom watchdog` check run, cancels it and re-runs its route job +(`Select Runners`, here `plan / route / Select Runners`) and the jobs that +need it; the new route keeps every fallback. A run is rescued once; stranded +again, it is only cancelled. Its token has `actions: write` and +`checks: write` on this repository and nothing else. Only CI and the other +routed workflows carry Darkbloom labels, so release and signing runs are never +touched. `DARKBLOOM_WATCHDOG=off` turns it off. + Routing is off unless the repository variable `DARKBLOOM_ROUTING` is exactly -`on`. While it is off, and for pull requests from forks, every job keeps its +`on`. The repository variable `DARKBLOOM_MACOS_LANES`, when set to a number +from 0 to 99, caps the macOS jobs one run asks for: the route keeps the lanes +in the caller's order while they fit, and the others keep their fallback +without asking (any other value asks for no macOS lane). `provider-tests.yml` +lists its lanes critical path first: `test-cluster-1` (the cluster `base` +selection), then the provider shards. While it is off, and for pull requests from forks, every job keeps its fallback and the plane is not contacted. When it is on, the route job sends one `POST /v1/ci/routes` to `DARKBLOOM_SANDBOX_URL` (default `https://api-sandbox.darkbloom.dev`) for the jobs that will run, retrying at @@ -294,8 +368,12 @@ which pushed branches it admits. Other branches get `branch_not_admitted` and keep their fallback, so a push saves caches on Darkbloom only from an admitted branch and only in routed lanes ([CI Caching](#ci-caching)). Release, signing, publication, model registration, review automation and -`master` or dispatched cache warming keep literal Blacksmith labels. The -component classifier and the `Provider Tests` gate run on `ubuntu-24.04`. +`master` or dispatched cache warming keep literal Blacksmith labels. In CI, +every job that builds or tests reads its lane of the plan's one route request +(the plane routes a run attempt once); the plan's own bookkeeping (the tree +lookup, the component choice) and the `Provider Tests` gate run on +`ubuntu-24.04`. The machine shape of each profile comes from the repository's +approval, not from the request: one macOS shape and one Linux shape. Jobs on Darkbloom Sandboxes use GitHub's Actions cache, not Blacksmith's colocated cache, so their first runs start without cached build products. @@ -304,6 +382,110 @@ decision is fixed for the run: **Re-run failed jobs** reuses it, so turn routing off and use **Re-run all jobs** to move a run back to Blacksmith. See the [routing checks](test.md#focused-tooling-checks). +## CI Caching + +`.github/workflows/provider-tests.yml`, `.github/workflows/ci-master.yml` and +`.github/actions/provider-ci-build/action.yml` restore caches in every run. +Only pushes to `master` and `dev` save them, when +the exact key missed: the workflow's `SAVE_CACHES` is +`github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/dev')`, +and `provider-tests.yml` passes it to the composite action as `save-caches` +(CI (master)'s own jobs save only on `master` pushes). An entry saved +by a pull request is scoped to its merge ref, so only that pull request could +restore it, and it evicted its base branch's entries from the repository's +10 GB quota. A pull request restores its base branch's newest compatible entry, +then `master`'s. Blacksmith runners keep their own colocated cache, so an entry +saved there never reaches a Darkbloom Sandbox, and the reverse: a push warms +the caches of the runners it ran on. + +| Cache | Path | Key; restore prefixes | Saved by, on pushes to `master` and `dev` | +|---|---|---|---| +| Git objects | `.git` | `git-v1--`; `git-v1---`, then `git-v1--` | every job that checks out | +| Full-history Git objects | `.git` | the same under `git-full-v1-`, so shallow jobs never restore it | `docs` | +| SwiftPM repositories | `~/Library/Caches/org.swift.swiftpm/repositories` | `spm-repos-v1----`; `spm-repos-v1----` | each build lane | +| Swift test build | each lane's `.build` directory | `swift-key` (`swift-prefix` and the commit), or on a Darkbloom host `swift-prefix` and `day-`; `swift-prefix`, then `swift-loose-prefix`, then `swift-mlx-prefix`, from `scripts/provider-ci-cache.py` | each build lane | +| Metal library | `$RUNNER_TEMP/metallib-cache` | `metallib-key`, exact only | each build lane | +| MiMo metadata downloads | `$RUNNER_TEMP/mimo-metadata-cache`, one file per pinned SHA-256 | `mimo-metadata-v1-`, exact only | each provider shard | +| MiMo audio codec | `$RUNNER_TEMP/mimo-audio-source` | `mimo-audio-source-v2-`, exact only; fetched only when the audio gate runs ([test guide](test.md)) | the last provider shard | +| Cluster metadata build | `$RUNNER_TEMP/cluster-native-metadata` | toolchain, submodule pins, manifests and paths, then the commit | `test-cluster-focused` | + +The Swift test build has three nested restore tiers. `swift-prefix` binds the +toolchain, the dependency manifests and pins, the checkout path and the CI +recipe (the workflows and scripts in `RECIPE_PATHS`). `swift-loose-prefix` +leaves out the recipe, which changes often and rarely changes an object, so an +edit to a workflow or a CI script no longer makes every build cold. +`swift-mlx-prefix` keeps only the toolchain, the checkout path and the MLX +gitlinks (`libs/mlx`, `libs/mlx-swift`, `libs/mlx-swift-lm`), so a change to +`Package.swift` or another pin still restores the compiled MLX. Source timestamps are +restored only for unchanged files, so SwiftPM rebuilds what changed. If a build +restored from the loose tier fails, `scripts/provider-ci-cold-retry.sh` deletes +the restored builds and the step builds once more from nothing; a failure over +an entry of the job's own recipe fails the step at once. CI (master) restores +only the first tier (`strict-cache`), so a build that may be released never +reuses objects of another recipe or dependency set. A Darkbloom host keeps +the entries it saved (10 GiB per repository), so there a push saves at most one +build per lane and UTC day; other runners key the build by commit. + +Every checkout uses the same five steps. The job computes the UTC day +(`date -u +%F`) and restores `.git`. A step that cannot fail then deletes the +restored `.git` unless `git rev-parse --verify HEAD` and +`git fsck --connectivity-only` accept it. One ordinary `actions/checkout` +follows: it fetches only the objects `.git` lacks and reuses the submodule +repositories under `.git/modules`, and its failure fails the job. No step uses +`continue-on-error`. A `.git` that passes fsck but still breaks the checkout +fails the job; change the key version, such as `git-v1`, to start over. The +`.git` key names the day, not the commit, so a branch saves `.git` once a day: +later runs that day restore the exact key and save nothing. Checkouts set +`persist-credentials: false`, so the saved `.git/config` holds no job token. + +Checkouts download only what their job reads. Every checkout but Docs Lint's +skips the `.gz` tarballs under `docs/reports/evidence` and `landing/public/media` +(`CHECKOUT_SPARSE`, 408 MB of evidence tarballs and landing videos): a sparse +checkout fetches commits and trees without file contents (`blob:none`), then +only the files it checks out. The reports and the rest of the evidence stay: a +provider test hashes `docs/reports/2026-10-31-public-cluster-models.md`, and +`scripts/provider-ci-cache.py` hashes every tracked `Package.swift`, including +one under `docs/reports/evidence`. Docs Lint +checks link targets on disk, so it checks out every file, but fetches history +with `filter: blob:none`; the provenance check then fetches the old document +versions it reads (about 29 MiB for its 12 checks). Docs Impact +(`.github/workflows/docs-impact.yml`) needs commits, trees and the docs, so it +uses both settings. + +```mermaid +flowchart LR + W[UTC day] --> R["Restore .git
(today, else newest)"] + R --> V{"git fsck
accepts .git?"} + V -- no --> D[Delete .git] --> K + V -- yes --> K[actions/checkout] + K --> G{"master or dev push,
no exact hit?"} + G -- yes --> S[Save .git] + G -- no --> B + S --> B["Restore SwiftPM, build
and Metal caches; build; test"] + B --> M{"master or dev push,
no exact hit?"} + M -- yes --> T[Save each cache] + classDef save fill:#d4f7dc,stroke:#1a7f37,color:#0b2e13 + classDef fail fill:#ffe1e1,stroke:#cf222e,color:#3d0a0a + class S,T save + class D fail +``` + +- Swift build prefixes contain no pull-request data; the commit is only the + key's suffix. A pull request that changes a CI recipe file, a manifest, a + lockfile or a submodule pin has a new `swift-prefix`; on `dev` it restores + a looser tier and rebuilds what changed, on `master` it builds cold. +- `actions/cache` stores a path outside the workspace relative to the + workspace, so the SwiftPM key includes ``, a hash of `$HOME` and the + workspace path. The cluster key reads only each submodule's state, pin and + path from `git submodule status`, because its `git describe` text depends on + the refs a restored `.git` holds. +- `actions/cache` compresses with zstd when `zstd` is on `PATH` and with gzip + otherwise, and the method is part of each entry's version: a runner without + zstd never restores an entry saved with it. Each job logs + `actions/cache compressor: zstd` or `gzip` before its first cache step. +- Concurrent jobs of one push save the same key; one wins, and the others log a + `409 Conflict` warning. + ## Dev Build Identity A dev release build (`DARKBLOOM_RELEASE_ENVIRONMENT=dev`) has its own install diff --git a/docs/developer/historical-references.md b/docs/developer/historical-references.md index e472641b4c..7b999827d0 100644 --- a/docs/developer/historical-references.md +++ b/docs/developer/historical-references.md @@ -14,7 +14,7 @@ Use a browser or a local Git checkout containing complete document history and the referenced source commits. A shallow clone may need `git fetch --unshallow origin`; check first with `git rev-parse --is-shallow-repository`. CI's Docs Lint job checks out full -history (`.github/workflows/ci.yml`, `docs`). +history (`.github/workflows/ci-master.yml`, `docs`). ## Steps diff --git a/docs/developer/test.md b/docs/developer/test.md index 1d786f9a03..4e73abffaf 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -112,43 +112,74 @@ snapshots. Preserve its watchdog, cleanup and state isolation when using a focus selector. Use `scripts/run-nested-suite.sh` for documented nested Swift Testing cases and `scripts/run-exclusive-native-gpu-test.sh` for exclusive native work. -CI runs the provider suite in three shards (`Provider Unit Tests (shard K)`), one -Mac each. `PROVIDER_TEST_SHARD=K/N` selects a shard in `scripts/run-provider-tests.sh`, -and `scripts/provider-test-shards.py` chooses its suites: +CI runs the provider suite in two shards (`Provider Unit Tests (shard K)`), one +Mac each, and each shard builds once and runs three selections at the same +time. `PROVIDER_TEST_SHARD=K/N` and `PROVIDER_TEST_PROCESSES=P` make +`scripts/run-provider-tests.sh` run selections `(K-1)*P+1` to `K*P` of `N*P`, +each in its own `--no-parallel` process with its own `TMPDIR` and provider +state files; `scripts/provider-test-shards.py` chooses each selection's suites. +The processes start `PROVIDER_TEST_START_GAP` seconds apart (default 15). +SwiftPM in one process can find the build database locked by another's +startup (`unable to attach DB: ... database is locked`); it then runs the +tests and exits 1. Such a selection runs once more, but only when its log +proves that every test passed (`scripts/swift_test_lock_retry.py`: a passing +Swift Testing summary, XCTest summaries with 0 failures, no failed test or +issue). The first attempt's log and xUnit report stay beside the second's as +`attempt-1-shard-.log` and `.xml`, and both upload. +Without `PROVIDER_TEST_PROCESSES` (the release qualification lane), a shard +runs one selection, as before: | Class | Process | Suites | |---|---|---| -| Parallel | Shard 1, one process with Swift Testing's default parallelism | The test targets whose dependency closure has no MLX, Metal or cluster runtime (`PARALLEL_MODULES`) | -| Serial | One `--no-parallel` process per shard | All other suites. Shards 1 to N-1 take suites by measured seconds (`scripts/provider-test-shard-weights.json`). The last shard runs every suite that no other shard selects, so a new suite always runs | +| Parallel | After selection 1, in its process slot, with Swift Testing's default parallelism | The test targets whose dependency closure has no MLX, Metal or cluster runtime (`PARALLEL_MODULES`) | +| Serial | One `--no-parallel` process per selection | All other suites. Selections 1 to N-1 take suites by measured seconds (`scripts/provider-test-shard-weights.json`). The last selection runs every suite that no other selection picks, so a new suite always runs | -Shard 2 also runs Prompt Parity (`scripts/verify-prompt-parity.sh` with +Shard 1 (the shard of selection 2) also runs Prompt Parity (`scripts/verify-prompt-parity.sh` with `PROMPT_PARITY_SKIP_BUILD=1`, and `scripts/verify-nemotron-prompt-parity.sh`) against its own build; a parity failure fails that shard and the `Provider Tests` gate. The last shard also runs the isolated processes and the -native MiMo, desktop and installer gates. `Provider Unit Tests Summary` lists the suite with -`swift test list`, fails unless each shard executed exactly its selection and -the shards together executed the full list, checks that each Prompt Parity run -executed every listed test of its suite, merges the shards' coverage -profiles and uploads measured seconds per suite (`provider-test-shard-weights`). -When the shards drift apart, replace the weights file with that artifact. A +native MiMo, desktop and installer gates, after its selections finish, one at +a time. Each shard then lists the suite with `swift test list` from its own +build and fails unless each of its selections executed exactly its plan +(`provider-test-shards.py audit-job`); shard 1 also checks that each Prompt +Parity run executed every listed test of its suite, and the last shard checks +that the plans of all selections list every test once. With every shard +required to pass, that is the full-suite audit; no Mac job exists only for it. +Each shard reports the coverage of its own processes. When the shards drift +apart, download the `provider-unit-shard-*` artifacts and run +`python3 scripts/provider-test-shards.py weights ` (it ignores a retried selection's `attempt-1-shard-*.xml`) to +refresh the weights file. A suite moves from the parallel class to the serial class when it fails or flakes in parallel; when in doubt, a suite stays serial. -The jobs that use the `provider-ci-build` action and Cluster Metadata Checks -restore their build cache by the exact key first, then by the key prefix. A -push to `dev`, `main` or `master` saves its build. A pull request saves its build only when it restored nothing. -Its later pushes then restore that entry or the base branch's entry and add no -new entry, so they do not evict the base branch's entries. CI has no separate -push-only Swift cache job. - -The SDK has independent test products under `libs/mlx-swift-lm`. CI validates -native memory ownership, cancellation, media decoding, paged KV and resource -packaging there as well as provider behavior. `Provider SDK Tests` is not part -of the `Provider Tests` gate: a pull request runs it only when an SDK-lane input -changes (`SDK` in `scripts/ci-component-paths.py`: the `libs/mlx-swift-lm` and -`libs/mlx-swift` pins, the build recipe and the nested-suite runners), and every -push to `dev` or `master` runs it, where a failure notifies without blocking. Preserve all retained lane gates; -do not treat the repository split as permission to skip native regressions. +The jobs that use the `provider-ci-build` action and the cluster metadata runners +restore their build cache by the exact key first, then by the key prefix; the +action then tries the loose prefix, which ignores the CI recipe, and builds +once more from nothing if that build fails. Only +a push to `dev` or `master` saves a build; a pull request restores its base +branch's entry and saves nothing ([CI caching](build.md#ci-caching)). A push +whose tree a pull request run already tested runs no test job; one build-only +job (Refresh build caches) saves the components the push changed. + +The last provider shard runs the MiMo audio gate (`testNativeAudioRelease`), +whose fixture needs the 1.87 GB pinned audio codec, only when the gate's +inputs change (`MIMO_AUDIO` in `scripts/ci-component-paths.py`: the MiMo, +audio and media provider code, the MiMo tests, the MLX pins, the audio and +provider fixture scripts and the gate's recipe), on a pull request and on a +push alike. A change outside those inputs neither downloads the codec nor runs +the gate. + +The SDK has independent test products under `libs/mlx-swift-lm`: native memory +ownership, cancellation, media decoding, paged KV and resource packaging. They +run in the SDK's own CI (Fork Tests in Layr-Labs/mlx-swift-lm), not here. +d-inference CI had a Provider SDK Tests lane that ran them again, under the +provider's SDK 27 toolchain; it was removed on 2026-11-04 because 226 of its +236 test seconds repeated Fork Tests (the test inventory of PR #1785). Its one +other step, `MiMoV26NativeMediaDeadlineTests`, +is skipped in Fork Tests until the SDK sets `MIMO_V26_SERIAL_NATIVE_TESTS=1`, +`MIMO_V26_NATIVE_MEDIA_DEADLINE_TESTS=1` and `MIMO_V26_SERIAL_LOAD_FIXTURES` for it. +The provider's release qualification still builds the provider, with the SDK +compiled in, and runs its tests under SDK 27. ### Download completion ownership @@ -1205,16 +1236,15 @@ Cluster logic that needs no model or GPU is covered by check runners compiled with isolated fixture runners: each `provider-swift/Tests/Cluster*Checks/run.sh`, `libs/darkbloom-cluster/Tests/*Checks/run.sh` and `libs/darkbloom-cluster-worker/Tests/*Checks/run.sh` prints its pass count and -exits non-zero on a failure. The CI job `test-cluster-checks` (Cluster Metadata -Checks, `.github/workflows/ci.yml`) runs these runners when the classifier -selects `cluster` (see below): `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, +exits non-zero on a failure. The CI job `test-cluster-focused` (Cluster Focused +Checks, `.github/workflows/provider-tests.yml`) runs these metadata runners first when +the classifier selects `cluster` (see below): `libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh`, `libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, `libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py`, `libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh`, `libs/darkbloom-cluster/Tests/NemotronStageChecks/run.sh` and -`provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning`. The -job `test-cluster-focused` (Cluster Focused Checks) runs every other runner -under `libs/darkbloom-cluster/Tests`. The provisioning runner runs the +`provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning`, then +every other runner under `libs/darkbloom-cluster/Tests`. The provisioning runner runs the provisioning checks only. Its download cache-policy check reads how many written pages stay in the file cache, which the host's kernel and disk decide: on the hosted CI VM 0.75 of the pages written with @@ -1227,23 +1257,33 @@ what changed. The worker package's tests (built for macOS 26.2) need the GPU and exclusive device access. A loopback or fixture pass never counts as a two-Mac hardware pass. -The cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, Cluster GPU -Tests and Cluster Focused Checks) run when the classifier selects `cluster` -(`CLUSTER` in `scripts/ci-component-paths.py`): the cluster packages, the MLX +The cluster jobs (Cluster Runtime Tests, Cluster GPU Tests and Cluster +Focused Checks) run when the classifier selects `cluster`, on a pull request +and on a push alike (`CLUSTER` in `scripts/ci-component-paths.py`): the cluster packages, the MLX pins, the provider's Cluster, Distributed and NativePair sources, the provider-side cluster runners (`provider-swift/Tests/Cluster*Checks`), the other provider files the cluster runners compile, the cluster plan and the -shared build recipe. A push that runs the provider lanes also runs them. The +shared build recipe. The `Provider Tests` gate accepts a skipped cluster job only when `cluster` was not -selected. A provider-only pull request runs 4 Macs (3 provider shards and the -summary), or 5 when an SDK-lane input changes. A cluster pull request adds 7 -Macs (metadata checks, 3 runtime shards, 2 GPU shards and focused checks). +selected. A provider-only change runs 2 Macs (the 2 provider shards). A cluster +change adds 5 +Macs (2 runtime shards, the focused checks with the metadata runners, and the +2 GPU shards). A change whose tree a successful run of the same workflow +already tested runs no test job at all (`scripts/ci-tested-tree.py`). CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the provider's macOS CI runners (see [CI runner routing](build.md#ci-runner-routing)), in selections that `scripts/cluster-test-plan.py` defines. Each selection runs in a process of its own through `scripts/run-nested-suite.sh`, which fails when -the selection runs no test or skips a test. Every process starts with +the selection runs no test or skips a test. Runtime shard 1 runs `base`, the +longest selection, alone, then the share probe alone. The probe times each +rank's share against a 1.5 s budget, so it never runs on a Mac right after +the concurrent GPU groups. Shard 2 runs two groups at the same time, each in +plan order with its own `TMPDIR` (the CPU batch-session suite with the GLM +paged-KV, invariance and census, TF32 and Gemma selections; the Qwen GPU chain +with `glm53-prefix-ssd`). A grouped selection that finds SwiftPM's build database locked, and whose log +proves every test passed, runs once more, as in the provider shards; the job +log prints both attempts' logs. Every process starts with `MLX_QMV_BATCH_INVARIANT=1`, as every cluster process does. | Selection | Job | Tests | @@ -1253,7 +1293,7 @@ the selection runs no test or skips a test. Every process starts with | Opt-in | Cluster GPU Tests (non-blocking) | The switched tests that fail on the CI runners' GPU, the long-running tests and the benchmarks. The job reports their results and does not fail the workflow | | Needs a model | None | The tests that need a model directory, an artifact or its metadata (`REQUIRES_MODEL`). CI has no model | -`python3 scripts/test-cluster-test-plan.py` (Release Integrity) checks that the +`python3 scripts/test-cluster-test-plan.py` (the `Provider Tests` gate and Release Integrity) checks that the plan names each gated test in the sources once, and each runner under `libs/darkbloom-cluster/Tests` once. When you add an environment gate to a runtime test, add the test to a selection or to `REQUIRES_MODEL`. @@ -1738,6 +1778,7 @@ python3 scripts/test-provider-release-pipeline.py python3 scripts/test-provider-release-artifact.py python3 scripts/test-provider-release-cache.py python3 scripts/test-darkbloom-route.py +python3 scripts/test-ci-tested-tree.py python3 scripts/test-provider-signing-validation.py python3 scripts/test-prepare-metal-toolchain.py python3 scripts/test-stage-swiftpm-resource-bundles.py @@ -2160,7 +2201,7 @@ failed test responses, terminal restoration and plain output. Set `ONBOARDING_TRANSCRIPTS` to a private output directory to retain screen text. The harness compiles only the onboarding flow, terminal and scripted operations; it does not configure a network port, start a service or load a model. CI runs -it in the `Cluster Metadata Checks` job (step `Run cluster onboarding checks`). +it in the `Cluster Focused Checks` job (step `Run cluster onboarding checks`). Its rows include the end of the setup after the cluster registers with the coordinator: the screen waits for both parts to serve again before it says Done (`leaderWaitsForThePartsAfterTheRegistration`). diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index 8346a2fdaa..218d7cc028 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -27,135 +27,81 @@ runs the resolve, build, qualification, signing, R2 staging and publication chain for one environment. To find the newest dev release, read `https://api.dev.darkbloom.dev/v1/releases/latest`. -`ProviderCore.version` is prepared as `0.10.6`, a patch release over `v0.10.5` -and the first production release with two-Mac clusters. `darkbloom cluster` -sets up two Macs joined by one Thunderbolt 5 cable (macOS 26.2 or later, RDMA -over Thunderbolt) to serve one model together, GLM-5.3-Flash and Qwen3.8-27B in -tensor parallel, and `darkbloom cluster local` serves a pair without a -coordinator. Every release lane computes the build's -[cluster runtime facts](#cluster-runtime-facts), from which a coordinator with -darkbloom-platform#643 derives the build's cluster approvals, pair-serving -grants and public qualifications. A registered pair's cluster service is no -longer restarted by its own part's heartbeats (#1690), pair members register the -models their pair-serving grant admits (#1686), a single Qwen3.8-27B request in -tensor parallel decodes about 6% faster on two M5 Ultra (#1680) and model -downloads show one progress line (#1683). Single-Mac serving needs no -coordinator change and no provider-version floor, though three answers to -coordinator requests and the local API change. See the -[`v0.10.6` changelog entry](../../CHANGELOG.md) for the full scope. - -Before tagging `v0.10.6`: +`ProviderCore.version` is prepared as `0.10.7`, a patch release over `v0.10.6`. +The two Macs of a pair set up with `darkbloom cluster` update together by +themselves (#1702), and `darkbloom update --rollback` puts back a Mac's previous +release (#1729), which the other Mac of a pair follows (#1739). Gemma 4 and +MiMo-V2.6-Flash gain tensor parallel on a pair (#1706, #1707, #1716), chosen +only on its own measured speed and only where it keeps every feature of the mode +it would replace (#1715), and `ClusterPublicModels` declares both public in +pipeline and tensor parallel (#1736). The operator's enabled-model filter wins +over coordinator model changes (#1730). Both Macs of a pair must run 0.10.7: a +pair of mixed builds refuses to pair, and a pair on 0.10.6 updates by hand once +([updating Darkbloom on the pair](../provider/two-mac-cluster.md#updating-darkbloom-on-the-pair)). +See the [`v0.10.7` changelog entry](../../CHANGELOG.md) for the full scope. + +Before tagging `v0.10.7`: - Confirm that the tagged commit pins `libs/mlx` and the nested `mlx` to - `72dffa2d` and `libs/mlx-swift` to `c633d221`, as v0.10.5 did, and - `libs/mlx-swift-lm` to `7933a0fa`, its fork's `main`. Only the SDK pin moves - (from `2beb401f`, through #1680 and #1684): SDK #373 changes - `AffineQuantizedVectors.swift` alone. -- The tag build's `metallib_hash` should equal v0.10.5's - `98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be`: the MLX - core is unchanged, and the dev-branch release of this preparation's base, - `0.10.5-dev.branch.18` from `a0413a8a`, registered that hash on DevNet. A - different hash needs an explanation, such as a changed Metal toolchain. -- The tag is the first production run of the release steps that came with the - cluster: the build and signing of the [cluster helpers](#cluster-helpers) and - the cluster runtime facts. The dev-branch lane runs the same reusable - workflow; its run - [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) - passed both, and DevNet's coordinator accepted its block. That proves neither - the derived approvals nor pairing; step 5 below checks both in production. -- Before step 3 below, check that the production catalog lists `glm-5.3-flash` - and `EigenLabs/Qwen3.8-27B-4bit-mtp`, because the facts step leaves out a - model the environment's catalog lacks. Check that the coordinator's catalog - has room within its bounds of 64 approvals, 64 pair-serving grants and 256 - parity qualifications, which newer releases fill first, each release whole: - 0.10.6 adds at most 24 approvals and 24 grants (`s1` and `s2` for each of at - most 12 models) and 8 parity qualifications (4 each for GLM-5.3-Flash and - Qwen3.8-27B). See [cluster runtime facts](#cluster-runtime-facts). -- The tagged commit is this preparation's squash commit on `master`, and - `changelog.d/` must hold only its `README.md` there. On the `master` checkout - you tag: - - ```bash - git log -1 --format=%s # must print: Prepare provider 0.10.6 (#) - make changelog-check # must print: changelog: 0 valid fragment(s) - ``` - - A fragment at the tag reached `master` without an entry in this release's - changelog. + `72dffa2d` and `libs/mlx-swift` to `c633d221`, as v0.10.6 did, and + `libs/mlx-swift-lm` to `32f5c744`, its fork's `main`. Only the SDK pin moves + (from `7933a0fa`): SDK #370, #371, #375 to #377 and #379 to #384 change Swift + files only, and the one Metal kernel they add compiles at run time + (`MLXFast.metalKernel`), not into `mlx.metallib`. +- The tag build's `metallib_hash` should equal v0.10.6's + `98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be`, because + the MLX core is unchanged. A different hash needs an explanation, such as a + changed Metal toolchain. +- `PROD_CLUSTER_RUNTIME_ENABLED` is `true` since v0.10.6, so this tag registers + a cluster runtime facts block. On the exact tag tree, re-run the release's + facts step read-only against production's catalog, as for 0.10.6: + `scripts/provider-cluster-runtime-facts.sh darkbloom prod `, + with an unsigned app staged the way the build job stages it, must exit 0. + The facts step leaves out a model the catalog lacks, so check the rows of + `gemma-4-26b-qat-4bit` and `mimo-v2.6-flash-mopd` as well as + `glm-5.3-flash` and `EigenLabs/Qwen3.8-27B-4bit-mtp`. +- Check the coordinator's catalog room + ([cluster runtime facts](#cluster-runtime-facts)): v0.10.6's block holds 24 + approvals, and this release adds 2 per model of its block, within the bound + of 64. The next release with a block can leave v0.10.6's approvals out, which + ends public serving for pairs still on 0.10.6; a pair on 0.10.7 or later + updates itself first. +- The tagged commit is on `master` and verified, holds `ProviderCore.version` + `0.10.7`, keeps the plain-build default `prod` + (`scripts/provider-build-default.py --branch master`), and its `changelog.d/` + holds only `README.md` (`make changelog-check` prints + `changelog: 0 valid fragment(s)`; a fragment there reached `master` without + an entry in this release's changelog). Roll out in this order; each step is a separate approval: -1. No DevNet proof: this release goes to production without one. DevNet's - coordinator accepted the block of `0.10.5-dev.branch.18` but derived no - approvals, so production is the first coordinator to derive them, and step 5 - checks them. -2. Production platform: deploy a `darkbloom-platform` coordinator with - [darkbloom-platform#643](https://github.com/Layr-Labs/darkbloom-platform/pull/643). - #643's code reaches the platform's `master` only with its `dev` to `master` - merge; its twin, - [darkbloom-platform#644](https://github.com/Layr-Labs/darkbloom-platform/pull/644), - carries only migration 58 (the `releases.cluster_runtime` column), which no - code on `master` reads. Production runs one combined coordinator, not - DevNet's split Provider Edge and Conductor. Apply migration 58 and set, in - the same deploy: - - `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` (approvals - derived from releases, the only approval source: - `EIGENINFERENCE_CLUSTER_PAIRS`, the operator's approval table, stays - unset); - - `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` (the - production coordinator listens on plain HTTP behind Caddy on the same - host, which reaches it over loopback, so without this setting no member - connection attaches to pair control); - - `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` (public traffic for qualified - clusters). - - App Attest serving must be on for every account: - `EIGENINFERENCE_APP_ATTEST_SERVING=true`, - `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT=production` and - `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT=100`. A member holds either the - legacy MDM path or an App Attest serving authorization, so a member on - macOS 27 without MDM pairs only through App Attest. -3. Confirm from production's `/health` `build_commit` that it runs the platform - revision of step 2. Check the catalog as above, and re-run the release's - facts step read-only against it: - `scripts/provider-cluster-runtime-facts.sh darkbloom prod `, - with an unsigned app staged from this preparation's source the way the build - job stages it (`scripts/provider-signing-validation.py stage`). It reads the - catalog and the CDN, sends nothing, and must exit 0: a catalog row that the - worker cannot describe stops the release after signing once the variable is - set. Then set the repository variable `PROD_CLUSTER_RUNTIME_ENABLED=true`. - Never before step 2: a coordinator without #643 refuses a registration that - carries `cluster_runtime`, and the release then fails after signing. Set it - before the tag: a release registered without the block never gains one, - because a re-registration must repeat the stored block (409 - `cluster_runtime_conflict`). -4. Merge into `master`, each squash-merged after its approval: first the - two-Mac clustering pull request, then this preparation. The clustering pull - request carries #1690 and #1692 from `dev`, with `master` merged in so plain - builds keep `master`'s `prod` default, and the fixes found while preparing - this release, such as the release facts fix (a catalog model ID that the - worker describes as another registered model is left out). After its squash, - restack this preparation with `scripts/restack-after-squash.py` - ([pull-request stacks](../developer/pull-requests.md)). Let SDK 27 release - preparation pass on `master`. This step does not depend on steps 1 to 3 and - may come first. -5. Tag `v0.10.6` on this preparation's squash commit once the checks above pass - ([step 4](#4-tag-and-push-production-source)). After registration, check the - coordinator log for `release cluster approvals omitted` and - `GET /v1/cluster/approvals` for the derived `release/0.10.6//s<1|2>` - approvals. Then a production pair, the owner's two Macs with App Attest, - must form a session under one of them. Record the run and the session. +1. Production platform: the coordinator deploys first + ([darkbloom-platform#679](https://github.com/Layr-Labs/darkbloom-platform/pull/679), + merged as `f9c1b2d6a3`). + 0.10.7's registration needs nothing new from it: the payload has 0.10.6's + fields, and the block keeps the `darkbloom_cluster_runtime_v2` schema. Its + new parity qualifications use generation modes the coordinator already + knows, MiMo-V2.6-Flash's speculative pipeline (`pipeline_mtp_v1`) included. + Confirm that production's `/health` `build_commit` is `f9c1b2d6a3`. +2. Merge into `master`, each squash-merged after its approval: first the `dev` + to `master` release snapshot (#1754), then this preparation, which is + cherry-picked onto `master` after #1754's squash. Its tree must not bring + back a rendered fragment. Let SDK 27 release preparation pass on `master`. +3. Re-run the facts dry run on the tag tree and check the catalog room, as + above. +4. Tag `v0.10.7` on this preparation's squash commit + ([step 4](#4-tag-and-push-production-source)). After registration, check + that `GET /v1/cluster/approvals` lists the derived + `release/0.10.7//s<1|2>` approvals and that the coordinator log has no + `release cluster approvals omitted`. +5. Each pair on 0.10.6 updates by hand once: `darkbloom update` on both Macs, + then log out and back in on both. Single Macs, and pairs from 0.10.7 on, + update by themselves. 6. The platform snapshots its provider contracts from the tagged commit (`python3 scripts/provider-contracts.py snapshot `), sets - `LatestProviderVersion` to `0.10.6` in the coordinator's `server.go` in the - same change and adds the revision row to its provider-contract reference. Of - the 34 snapshotted inputs, only `contracts/provider/ProviderCore.swift` - changes from v0.10.5. `LatestProviderVersion` is a fallback and does not gate - publication. - -Without steps 2 and 3 the tag still publishes with an unchanged registration, -but 0.10.6 then never derives cluster approvals, and a production pair serves -only on its leading Mac's local API. + `LatestProviderVersion` to `0.10.7` in the coordinator's `server.go` in the + same change and adds the revision row to its provider-contract reference. + `LatestProviderVersion` is a fallback and does not gate publication. 0.10.2's remaining enablement steps do not wait for this tag and still apply; each is a separate approval: @@ -173,31 +119,25 @@ approvals. This preparation tags, deploys and enables nothing; merging it into `master` publishes nothing, because the staging lane runs only while `STAGING_ENABLED` is `true`. -Platform evidence, inspected on 2026-10-31 (recheck before tagging): +Platform evidence, inspected on 2026-11-03 (recheck before tagging): | Claim | Source | |---|---| -| Platform `master` (`2847f27d`) pins the provider contracts at d-inference `8effff7f` (v0.10.4) and keeps `LatestProviderVersion` at `0.10.4`; darkbloom-platform#639 (open) pins v0.10.5's `d3bbcd06`. The 34 inputs equal this preparation's except `ProviderCore.swift` | [`contracts/provider/manifest.json` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/contracts/provider/manifest.json) and [at #639's `422ca1d4`](https://github.com/Layr-Labs/darkbloom-platform/blob/422ca1d428849c775daa950691a185154f117c18/contracts/provider/manifest.json) (`source_revision`) | +| The coordinator knows the generation mode `pipeline_mtp_v1` and puts it in the `pipeline_speculative` family, at #679's merge commit (`f9c1b2d6a3`), unchanged from platform `master` before it (`482ca9db`) | [`cluster_generation_mode.go` at `f9c1b2d6a3`](https://github.com/Layr-Labs/darkbloom-platform/blob/f9c1b2d6a3c590bcbf03f11b8ccbdbe383a54449/coordinator/protocol/cluster_generation_mode.go) (`ClusterPlanModeFamily`) | +| At #679's merge commit (`f9c1b2d6a3`), the platform still pins the provider contracts at d-inference `8effff7f` (v0.10.4) and keeps `LatestProviderVersion` at `0.10.4`; step 6 moves both | [`contracts/provider/manifest.json` at `f9c1b2d6a3`](https://github.com/Layr-Labs/darkbloom-platform/blob/f9c1b2d6a3c590bcbf03f11b8ccbdbe383a54449/contracts/provider/manifest.json) (`source_revision`); [`server.go` at `f9c1b2d6a3`](https://github.com/Layr-Labs/darkbloom-platform/blob/f9c1b2d6a3c590bcbf03f11b8ccbdbe383a54449/coordinator/api/server.go) (`LatestProviderVersion`) | | `LatestProviderVersion` must equal the snapshotted `ProviderCore.version` | [`provider_version_sync_test.go` at `5ba280d8`](https://github.com/Layr-Labs/darkbloom-platform/blob/5ba280d89aa5e9bd4fbf05e0dfa848059cd3b585/coordinator/tests/api/provider_version_sync_test.go) (`TestLatestProviderVersionMatchesProviderCore`) | -| #643 is merged into platform `dev` (`df61dd6f`), not `master`; #644 (open) carries only its migration to `master`. Only `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` derives entries from releases, and public routing needs an approval source | [`cluster_pair_config.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/api/cluster_pair_config.go) (`ClusterPairConfig`) | -| Migration 58 adds `releases.cluster_runtime`, and a re-registration must repeat the stored block (409 `cluster_runtime_conflict`) | [`00058_release_cluster_runtime.sql` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/schema/migrations/00058_release_cluster_runtime.sql); [`releases.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/releases.go) (`SetRelease`) | -| A coordinator without #643 refuses a registration body that carries `cluster_runtime` | [`release_handlers.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/api/releases/release_handlers.go) (`DisallowUnknownFields`) | -| Of the platform's deploy configuration, only DevNet's overlay sets `EIGENINFERENCE_CLUSTER_PAIRS`, `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES` and `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING`, and it also sets `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1` | [`env-overrides` (DevNet) at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/deploy/gcp/dev/env-overrides) | -| A member connection attaches to pair control only after its own TLS handshake or through a listed TLS proxy. The production coordinator listens on plain HTTP behind Caddy, and in the split deployment only the trusted-proxy path attaches a member | [`configuration.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/configuration.md) ("Trusted TLS proxy trade-off") | -| A pair member holds the legacy MDM path or an App Attest serving authorization; App Attest serving reads `EIGENINFERENCE_APP_ATTEST_SERVING`, `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT` and `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT` | [`cluster-control-protocol.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/cluster-control-protocol.md) ("Member trust"); [`config.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/appattest/service/config.go) (`ConfigFromEnvironment`) | -| DevNet runs `df61dd6f` and accepted the block of `0.10.5-dev.branch.18` (registered 04:33Z), yet its `GET /v1/cluster/approvals` listed only 26 operator approvals, with no `release/` entry, at 04:44Z, 04:57Z, 05:04Z and 05:09Z | DevNet `/health` and `/v1/cluster/approvals`; run [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) (`CLUSTER_RUNTIME_SEND: true`) | - -The production coordinator was not inspected for this preparation; step 3 + +The production coordinator was not inspected for this preparation; step 1 checks its `/health`. -`v0.10.5` was [published on 2026-10-30](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5) +`v0.10.6` was [published on 2026-10-31](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.6) +from `84ddfdba6bb704bf1c68f97c7060289079380ceb`, `v0.10.5` was +[published on 2026-10-30](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5) from `d3bbcd064ea290fbeb500e5c51c7870e3695741c`, `v0.10.4` was [published on 2026-10-28](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.4) from `8effff7f7067fec70b2e3b58de0a4ba47ea3986c`, `v0.10.3` was [published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.3) -from `3ddd11ce8d7204cc5aadefd2050376c583da4ff8`, `v0.10.2` was -[published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.2) -from `f9d1af3d0d3e1838974a5cfdff0a08142977b45e`. Publication does not establish +from `3ddd11ce8d7204cc5aadefd2050376c583da4ff8`. Publication does not establish that every optional feature or environment has been activated. ## Prerequisites diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 32f2995788..7444b7dd3d 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1402,6 +1402,21 @@ darkbloom sandbox uninstall [--yes] images and one Linux job: 1 Linux job, no macOS job. When no job fits, the verdict gives the plan's message and the GiB to free for one Linux job and for one macOS job, and setup stops before installing. + + When the add-on's plan gives macOS no job and its `macos_limit` names disk, + setup prints one more line under the verdict + (`SandboxSizingPlan.freeSpaceNote`): the plan's free space is what `df -h ~` + shows as Avail; Finder also counts purgeable space, which macOS frees only + when it needs to (restarting, or removing Time Machine local snapshots, which + `tmutil listlocalsnapshots /` lists, frees it now); then + `A macOS job needs about N GB more`. N is `diskShortfall` for a macOS job + beside the plan's slots: the floor, the disk the plan's slots take (each + platform's images with its first slot, one job's disk per slot) and a macOS + job with its images, less the free space, in GiB rounded up, which the CLI + writes as GB like its memory figures. With 210 GiB free and 3 Linux jobs + planned, a lone macOS job would fit above the floor, but beside the Linux + jobs it needs about 70 GB more. When no job fits, N equals the verdict's GiB + for one macOS job. The fallback estimate gets no such line. 4. **Confirm.** Explains that inference pauses while a job runs, that each job pays its price minus a 10% fee into the Darkbloom balance, the VM images and the one browser approval, then asks `[y/N]`. `--yes` skips it; without a @@ -1434,7 +1449,24 @@ Rerunning `setup` decides from the add-on's answer | No add-on, or `not_installed` | A first setup: check, plan, explain, confirm, install | | `waiting_for_approval`, `waitlisted`, `enrolling` | Runs the installer again to continue, without the check or the question | | `stopped`, `error`, no answer within 10 s, a failed status, an add-on older than `status --json` | Runs the installer again to repair or update the add-on | -| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state and changes nothing; with `--linux-slots` or `--macos-slots` it runs the installer to apply them | +| `ready`, `running`, `paused`, `downloading_images`, `updating`, an unknown state | Reports the state, then checks the plan again (below); with `--linux-slots` or `--macos-slots` it runs the installer to apply them, without the plan | + +On a Mac that is set up, after the report, setup downloads the installer and +runs its plan as for a first setup, which changes nothing, and compares the +plan's `linux_slots` and `macos_slots` with the installed `slots.linux.total` +and `slots.macos.total` (`SandboxSlotChange`): + +| Case | `setup` | +|---|---| +| Same counts, no plan (an installer without `--plan`, a failed plan), a plan without a job, no `slots` in the status, or a failed download | Today's report exactly: the state, then `To change how many jobs run at a time: darkbloom sandbox setup --linux-slots --macos-slots `, without the free-space line; a failed download adds why it could not check | +| `jobs_running` above `0` | No plan: the add-on's installer refuses a slot change while jobs run (exit `4`; the CLI never passes `--force`), and their disk would shrink the plan. Setup says to run it again once they finish | +| Different counts, at a terminal | The plan's CPU, memory and disk lines and the free-space line when it applies, then `This Mac now fits Linux + macOS (installed: Linux + macOS). If a job is running, the installer refuses and changes nothing. Apply? [Y/n]`. Yes or an empty answer runs the installer with the plan's counts as `--linux-slots` and `--macos-slots`; no prints the command that applies it | +| Different counts, `--yes` or no terminal | The same lines, then `This Mac now fits …` without the question. Applies the plan only when it adds slots and removes none; otherwise prints `Not applied` and the command that applies it, and exits `0` | + +A platform missing from `slots` counts as `0`: the add-on configures and +reports only platforms with a slot. When the installer finds that a job +started since the status, it refuses with exit `4` and changes nothing; setup +prints the exit `4` advice below and exits `4`. ### Installer progress events @@ -1495,7 +1527,7 @@ every tenth. | `0` | The summary: state, jobs at a time (automatic and the limit, or your choice), next commands | | `2` | This Mac cannot host Darkbloom Sandbox as it is (the failed stage says why) | | `3` | Not enrolled: the code was denied or expired, or the waitlist request ended; run `setup` to start again | -| `4` | Jobs are running; run `setup` again once they finish, `pause` meanwhile | +| `4` | A job is running, so the installer changed nothing (it refuses rather than waits); run `setup` again when it finishes, `pause` meanwhile. Setup never passes the installer's `--force`, which would stop running jobs, and stopped jobs aren't paid | | `130` | Stopped; an enrollment waiting for approval goes on, and a rerun follows it. While the Mac waits in the background (`background: true`, not yet enrolled): it keeps waiting, also across restarts, and enrolls by itself; `sandbox status` shows where it is | | other | Setup did not finish; it is safe to rerun | diff --git a/docs/provider/sandboxes.md b/docs/provider/sandboxes.md index 2f9e96daa9..58d031c578 100644 --- a/docs/provider/sandboxes.md +++ b/docs/provider/sandboxes.md @@ -1,6 +1,6 @@ # Host Darkbloom Sandbox CI jobs -> Last updated: 2026-11-02 +> Last updated: 2026-11-03 How to let this Mac run Darkbloom Sandbox jobs, approved GitHub Actions jobs in Linux and macOS virtual machines, beside the inference provider: set it up, @@ -82,11 +82,29 @@ Uninstalling ends running jobs, which are not paid: pause first and uninstall once they finish. Running `setup` again at any time is safe: it reports the state, continues an unfinished setup or repairs the add-on. +On a Mac that is set up, `setup` also asks the installer for the add-on's plan +again. When the plan fits other job counts, for example after you freed disk, +setup shows them beside the installed ones and asks `[Y/n]`. Yes reinstalls +with the plan's counts and restarts the add-on. The installer does not wait +for jobs: if one is running, it refuses and changes nothing, and setup says to +run it again when the job finishes. With `--yes` or without a terminal, setup +applies the plan only when it adds jobs and removes none; otherwise it prints +the command that applies it. When the counts match, setup reports as before. +While jobs run, setup skips the check. The +[CLI reference](./cli-reference.md#setup) has the details. + ## Troubleshooting - **`Free up N GiB of disk for one Linux job`.** No job fits in the free disk. The disk rules are under [Prerequisites](#prerequisites). Free the space it names, then run setup again. +- **`no macOS jobs (limited by free disk space)`, while Finder shows more + free.** The plan counts what `df -h ~` shows as Avail. Finder also counts + purgeable space, which macOS frees only when it needs to. Restart, or remove + Time Machine local snapshots (`tmutil listlocalsnapshots /` lists them), to + free it now. Setup's line `A macOS job needs about N GB more` says how much + more free space a macOS job needs beside the planned Linux jobs. Then run + setup again: it offers the new plan. - **`On the waitlist`.** Darkbloom has not approved your account yet. With add-on 1.1.2 and later you can close the window: the Mac keeps waiting, also across restarts, and enrolls by itself once your account is approved; @@ -99,8 +117,12 @@ state, continues an unfinished setup or repairs the add-on. not paid. Follow the `↳ fix:` line. - **`This Mac was not enrolled`** (exit status 3). The code was denied or expired, or the waitlist request ended. Run setup again for a new code. -- **`Jobs are running on this Mac`** (exit status 4). An add-on update or a - slot change waits for running jobs; run setup again once they finish. +- **`A job is running on this Mac`** (exit status 4). The installer refuses + to replace the add-on or change its slots while a job runs, and changes + nothing; it does not wait. Run setup again when the job finishes; + `darkbloom sandbox pause` keeps new ones from starting. Setup never passes + the installer's `--force`, which would stop running jobs, and stopped jobs + aren't paid. - **`This version of the add-on …`.** The add-on predates the command; it updates itself, or `darkbloom sandbox setup` updates it now. - **`Sandboxes: installed; the add-on did not answer within 2s`.** `darkbloom diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift index 37319a171c..a80001f748 100644 --- a/provider-swift/Sources/ProviderCore/ProviderCore.swift +++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift @@ -5,5 +5,5 @@ public enum ProviderCore { /// Release identity consumed by CLI output, registration and packaging. /// scripts/check-release-version.sh verifies this provider-owned identity /// against the requested release tag and reported binary version. - public static let version = "0.10.6" + public static let version = "0.10.7" } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift index d662a80fa9..05d76d019a 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxEligibility.swift @@ -220,10 +220,10 @@ extension SandboxSizingPlan { var jobMemory: Int64 { max(0, memoryBytes - memoryKeptBytes - providerMemoryBytes) } var canRunJobs: Bool { linux.slots + macOS.slots > 0 } - /// Free disk one job of `platform` needs beyond what is free now, its - /// images included; 0 when it fits. + /// Free disk one more job of `platform` needs, beside the plan's slots, + /// beyond what is free now; 0 when it fits. func diskShortfall(_ platform: Platform) -> Int64 { - max(0, floorBytes + platform.firstSlotBytes - freeBytes) + max(0, floorBytes + linux.plannedBytes + macOS.plannedBytes + platform.nextSlotBytes - freeBytes) } /// The CPU, memory and disk lines, in the `doctor` style. When no job @@ -265,6 +265,18 @@ extension SandboxSizingPlan { return lines } + /// Why Finder shows more free space than the add-on's plan, when it gives + /// macOS no job for want of free disk space (its own `limit`), and the + /// free space one macOS job needs beside the plan's Linux slots. + var freeSpaceNote: String? { + guard macOS.slots == 0, macOS.limit?.contains("disk") == true else { return nil } + let short = diskShortfall(macOS) + return "Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS " + + "frees only when it needs to (restarting, or removing Time Machine local snapshots: " + + "`tmutil listlocalsnapshots /`, frees it now)." + + (short > 0 ? " A macOS job needs about \(gibUp(short)) GB more." : "") + } + /// The plan's message, how much disk to free for one job of each /// platform, and whether the owner's counts are why. private var shortfall: [String] { @@ -293,6 +305,8 @@ extension SandboxSizingPlan.Platform { /// The first slot brings the platform's images. var firstSlotBytes: Int64 { imagesBytes + slotBytes } var nextSlotBytes: Int64 { slots == 0 ? firstSlotBytes : slotBytes } + /// Disk its planned slots take: the images with the first, one job's disk each. + var plannedBytes: Int64 { slots == 0 ? 0 : imagesBytes + Int64(slots) * slotBytes } } private func gb(_ bytes: Int64) -> Int64 { bytes / SandboxEligibility.gib } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift index 0762808bef..135a89ce32 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupCommand.swift @@ -15,7 +15,9 @@ extension Sandbox { it in your browser. Running it again reports the current state, continues an unfinished setup, repairs or updates \ - the add-on, or applies new slot counts. + the add-on, or applies new slot counts. On a Mac that is set up, it asks the installer's plan \ + again and offers the add-on's slot counts when they differ from the installed ones; with --yes \ + or without a terminal it applies them only when they add slots and remove none. """) @Flag(name: .shortAndLong, help: "Don't ask for confirmation.") @@ -77,7 +79,8 @@ extension Sandbox { /// What `setup` does, given the add-on's current answer. enum SandboxSetupPlan: Equatable, Sendable { - /// Set up already; report it and change nothing. + /// Set up already; report it, then offer the add-on's plan when its slot + /// counts differ. case alreadySetUp(SandboxAddonStatus) /// Run the installer over the existing install, for this reason. case rerun(String) @@ -137,23 +140,94 @@ struct SandboxSetupFlow { let changingSlots = options.linuxSlots != nil || options.macOSSlots != nil switch SandboxSetupPlan.decide(existing, changingSlots: changingSlots) { case .alreadySetUp(let status): - print("Darkbloom Sandbox is already set up on this Mac.") - print("") - SandboxStatusView.lines(status, color: color).forEach { print($0) } - print("") - print("To change how many jobs run at a time: \(cli) sandbox setup --linux-slots --macos-slots ") + try await reportAndRecheckSizing(status) case .rerun(let reason): print(reason) - try await withInstaller { try await install($0, script: $1) } + try await withInstaller { try await install($0, script: $1, options: options) } case .fresh: let eligibility = try await checkMac() try await withInstaller { installer, script in guard try await sizeAndConfirm(eligibility, installer: installer, script: script) else { return } - try await install(installer, script: script) + try await install(installer, script: script, options: options) } } } + // MARK: - Already set up + + private static let changeCountsHint = "To change how many jobs run at a time: \(Sandbox.cli) sandbox setup " + + "--linux-slots --macos-slots " + + /// Reports the install, then asks the installer's `--plan` how many jobs + /// this Mac fits now and offers what differs. Changes nothing unless the + /// owner agrees, or, without a prompt, the plan only adds slots. Skipped + /// while jobs run: the installer changes slots only while none does, and + /// their disk would shrink the plan. + private func reportAndRecheckSizing(_ status: SandboxAddonStatus) async throws { + print("Darkbloom Sandbox is already set up on this Mac.") + print("") + SandboxStatusView.lines(status, color: color).forEach { print($0) } + print("") + guard status.jobsRunning == 0 else { + print(Self.changeCountsHint) + print("Jobs are running, so setup did not check whether this Mac now fits other slot counts. Run " + + "`\(cli) sandbox setup` again once they finish; `\(cli) sandbox pause` keeps new ones from starting.") + return + } + try await withInstaller(ifUnavailable: { failure in + print(Self.changeCountsHint) + print("Could not check whether this Mac now fits other slot counts: \(failure)") + }) { installer, script in + let plan = try await withTransientNote("Checking how many jobs this Mac fits now…") { + try await requestAddonPlan(installer, script: script) + } + // The same counts (or no plan to compare) keep today's report exactly. + guard let plan, let change = SandboxSlotChange(installed: status, plan: plan) else { + print(Self.changeCountsHint) + return + } + guard offer(change, plan: plan) else { return } + print("") + try await install(installer, script: script, options: change.applying(to: options)) + } + } + + /// Shows the add-on's plan against the installed counts; true to apply it. + /// With a prompt the default is yes. Without one (`--yes`, or no + /// terminal) it applies only a change that adds slots and removes none. + private func offer(_ change: SandboxSlotChange, plan: SandboxSizingPlan) -> Bool { + print("The add-on's plan for this Mac now:") + printChecks(plan.checks) + if let note = plan.freeSpaceNote { print(" " + note) } + print("") + guard !confirmed, interactiveInput else { + print(change.headline) + guard change.onlyAdds else { + print("Not applied: it removes slots, and without a prompt setup applies only a plan that adds " + + "slots. To apply it: \(change.command)") + return false + } + print("Applying it: it only adds slots.") + return true + } + // The installer stops the agent only between jobs: it refuses (exit 4), it does not wait. + guard SandboxTerminal.confirm(change.headline + " If a job is running, the installer refuses and changes " + + "nothing. Apply?", defaultYes: true) else { + print("Nothing changed. To apply it later: \(change.command)") + return false + } + return true + } + + /// Runs `body` with `note` on the running line of a terminal, erased + /// afterwards; elsewhere prints nothing. + private func withTransientNote(_ note: String, _ body: () async throws -> T) async rethrows -> T { + guard terminal else { return try await body() } + SandboxTerminal.write(note) + defer { SandboxTerminal.write("\r\u{1B}[2K") } + return try await body() + } + // MARK: - Check and confirm /// Prints the checks setup makes itself; throws, before anything is @@ -176,8 +250,9 @@ struct SandboxSetupFlow { /// trade-off, then asks. False when the owner declines; throws when no job /// fits. private func sizeAndConfirm(_ eligibility: SandboxEligibility, installer: URL, script: Data) async throws -> Bool { + let reportedPlan = try await requestAddonPlan(installer, script: script) let plan: SandboxSizingPlan - if let reportedPlan = try await requestAddonPlan(installer, script: script) { + if let reportedPlan { plan = reportedPlan } else { printChecks([SandboxEligibility.Check( @@ -190,6 +265,8 @@ struct SandboxSetupFlow { let verdict = plan.verdict print(DoctorTerminalStyle.verdict(verdict[0], level: plan.canRunJobs ? .pass : .fail, color: color)) verdict.dropFirst().forEach { print($0) } + // The add-on's plan only: the fallback estimate's report stays as it was. + if let note = reportedPlan?.freeSpaceNote { print(" " + note) } guard plan.canRunJobs else { throw ExitCode.failure } print("") Self.tradeOff.forEach { print($0) } @@ -251,8 +328,10 @@ struct SandboxSetupFlow { // MARK: - Install /// Downloads the installer into a new owner-only directory for `body`, - /// then removes it. - private func withInstaller(_ body: (_ installer: URL, _ script: Data) async throws -> Void) async throws { + /// then removes it. A failed download goes to `ifUnavailable` when given, + /// else fails setup. + private func withInstaller(ifUnavailable: ((SandboxInstaller.Failure) -> Void)? = nil, + _ body: (_ installer: URL, _ script: Data) async throws -> Void) async throws { guard let url = SandboxInstaller.scriptURL(server: options.server) else { throw ValidationError("--server must be an https URL, such as \(Sandbox.defaultServer)") } @@ -260,6 +339,7 @@ struct SandboxSetupFlow { do { script = try await SandboxInstaller.download(url) } catch let failure as SandboxInstaller.Failure { + if let ifUnavailable { return ifUnavailable(failure) } printError("\(failure) Check this Mac's connection, then run `\(cli) sandbox setup` again.") throw ExitCode.failure } @@ -268,7 +348,7 @@ struct SandboxSetupFlow { try await body(installer, script) } - private func install(_ installer: URL, script: Data) async throws { + private func install(_ installer: URL, script: Data, options: SandboxSetupOptions) async throws { let jsonProgress = SandboxInstaller.supportsJSONProgress(script) let arguments = [installer.path] + SandboxInstaller.arguments(options, jsonProgress: jsonProgress) let directory = installer.deletingLastPathComponent() @@ -310,8 +390,10 @@ struct SandboxSetupFlow { case 2: return "This Mac cannot host Darkbloom Sandbox as it is; see why above." case 3: return "This Mac was not enrolled: the code was denied or expired, or the waitlist request ended. " + "Run \(rerun) to start again." - case 4: return "Jobs are running on this Mac. Run \(rerun) again once they finish; " - + "`\(Sandbox.cli) sandbox pause` keeps new ones from starting." + // The installer refuses rather than waits; its --force would stop the jobs unpaid. + case 4: return "A job is running on this Mac, so the installer changed nothing. Run \(rerun) again when it " + + "finishes; `\(Sandbox.cli) sandbox pause` keeps new jobs from starting. Setup never passes the " + + "installer's --force: it would stop running jobs, and stopped jobs aren't paid." default: return "Setup did not finish. When the problem above is fixed, run \(rerun) again; it is safe to rerun." } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift index c846849965..03468a4f2c 100644 --- a/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSetupProgress.swift @@ -454,11 +454,12 @@ enum SandboxTerminal { fflush(stdout) } - /// Asks a yes/no question; anything but y or yes is no. - static func confirm(_ question: String, readInput: () -> String? = { readLine() }, + /// Asks a yes/no question; anything but y or yes is no. With + /// `defaultYes`, an empty answer is yes too. + static func confirm(_ question: String, defaultYes: Bool = false, readInput: () -> String? = { readLine() }, emit: (String) -> Void = { write($0) }) -> Bool { - emit("\(question) [y/N]: ") + emit("\(question) \(defaultYes ? "[Y/n]" : "[y/N]"): ") let answer = readInput()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" - return ["y", "yes"].contains(answer) + return ["y", "yes"].contains(answer) || (defaultYes && answer.isEmpty) } } diff --git a/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift b/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift new file mode 100644 index 0000000000..320a9ed4fa --- /dev/null +++ b/provider-swift/Sources/darkbloom/Sandbox/SandboxSlotChange.swift @@ -0,0 +1,42 @@ +import Foundation + +/// The add-on's plan for an installed Mac against the slots it runs now +/// (`status --json`): what rerunning `setup` offers to apply. The counts are +/// the add-on's; the CLI only compares them. +struct SandboxSlotChange: Equatable, Sendable { + var installedLinux: Int + var installedMacOS: Int + var plannedLinux: Int + var plannedMacOS: Int +} + +extension SandboxSlotChange { + /// Nil when the status names no slots to compare, the plan fits no job, + /// or it matches the installed counts. + init?(installed status: SandboxAddonStatus, plan: SandboxSizingPlan) { + guard status.linux != nil || status.macOS != nil, plan.canRunJobs else { return nil } + self.init(installedLinux: status.linux?.total ?? 0, installedMacOS: status.macOS?.total ?? 0, + plannedLinux: plan.linux.slots, plannedMacOS: plan.macOS.slots) + guard installedLinux != plannedLinux || installedMacOS != plannedMacOS else { return nil } + } + + /// Adds slots and removes none: what setup applies without a prompt. + var onlyAdds: Bool { plannedLinux >= installedLinux && plannedMacOS >= installedMacOS } + + /// The owner's options with the plan's counts, as explicit slot options. + func applying(to options: SandboxSetupOptions) -> SandboxSetupOptions { + var options = options + (options.linuxSlots, options.macOSSlots) = (plannedLinux, plannedMacOS) + return options + } + + /// The command that applies it. + var command: String { + "\(Sandbox.cli) sandbox setup --linux-slots \(plannedLinux) --macos-slots \(plannedMacOS)" + } + + var headline: String { + "This Mac now fits \(plannedLinux) Linux + \(plannedMacOS) macOS " + + "(installed: \(installedLinux) Linux + \(installedMacOS) macOS)." + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift index 5d5a9aa8f8..8a86f0521c 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxSetupTests.swift @@ -233,6 +233,44 @@ struct SandboxSetupTests { #expect(full.checks.map(\.level) == [.pass, .pass, .fail]) } + /// The free-space note, with what one macOS job needs beside the plan's Linux slots. + private static func freeSpaceNote(macOSNeeds more: Int?) -> String { + "Free space here is what `df -h ~` shows as Avail; Finder also counts purgeable space, which macOS frees " + + "only when it needs to (restarting, or removing Time Machine local snapshots: " + + "`tmutil listlocalsnapshots /`, frees it now)." + + (more.map { " A macOS job needs about \($0) GB more." } ?? "") + } + + @Test("the free-space note appears only when the add-on gives macOS no job for want of disk") + func freeSpaceNoteScope() throws { + func plan(linux: Int = 1, macOS: Int = 0, limit: String = "free disk space", + freeGiB: Int64 = 157) throws -> SandboxSizingPlan { + let line = FakeSandboxInstaller.plan(linux: linux, macOS: macOS, freeGiB: freeGiB) + .replacingOccurrences(of: #""macos_limit":"free disk space""#, with: #""macos_limit":"\#(limit)""#) + return try #require(SandboxSizingPlan(line: line)) + } + // 100 GiB floor + 1 Linux job with its images (34) + macOS images and job (86) - 157 free. + #expect(try plan().freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 63)) + #expect(try plan(freeGiB: 200).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 20)) + // No job: one macOS job's disk alone, as the verdict's own line says. + #expect(try plan(linux: 0, freeGiB: 120).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 66)) + // A plan whose numbers fit a macOS job anyway says no number. + #expect(try plan(freeGiB: 400).freeSpaceNote == Self.freeSpaceNote(macOSNeeds: nil)) + for limit in ["cores", "memory", "your choice", "macOS's limit of 2 VMs, yours included"] { + #expect(try plan(limit: limit).freeSpaceNote == nil, "\(limit)") + } + #expect(try plan(macOS: 1).freeSpaceNote == nil) + } + + @Test("the feedback's Mac: 3 Linux slots and no macOS one for want of disk; the note counts the Linux slots") + func freeSpaceNoteWithThreeLinuxSlots() throws { + // 110 GiB above the floor: a lone macOS job (86) would fit, but the 3 Linux jobs and their images take 94. + let plan = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan( + message: "3 Linux slots", linux: 3, freeGiB: 210))) + #expect(plan.diskShortfall(plan.macOS) == 70 << 30) + #expect(plan.freeSpaceNote == Self.freeSpaceNote(macOSNeeds: 70)) + } + /// Each event as the renderer gets it. private static func render(_ lines: [String], interactive: Bool = false, finish outcome: SandboxSetupRenderer.Outcome = .succeeded) -> String { @@ -422,8 +460,7 @@ struct SandboxSetupTests { } #expect(advice(2) == "This Mac cannot host Darkbloom Sandbox as it is; see why above.") #expect(advice(3).hasPrefix("This Mac was not enrolled: the code was denied or expired")) - #expect(advice(4) == "Jobs are running on this Mac. Run `darkbloom sandbox setup` again once they finish; " - + "`darkbloom sandbox pause` keeps new ones from starting.") + #expect(advice(4) == Self.jobRunningAdvice) #expect(advice(130) == "Setup stopped. An enrollment waiting for approval goes on; run " + "`darkbloom sandbox setup` again to follow it.") #expect(advice(2, signal: SIGINT) == advice(130)) @@ -500,10 +537,6 @@ struct SandboxSetupTests { try await SandboxSetupFlow(options: first, confirmed: true, addon: .live(), interactiveInput: false, terminal: false, color: false, probe: { _ in .mac(cores: 16, memoryGiB: 128) }).run() - print("== SECOND") - try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), - confirmed: false, addon: .live(), interactiveInput: false, - terminal: false, color: false).run() print("== PLAN") print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("plan-arguments"), encoding: .utf8), terminator: "") @@ -511,9 +544,14 @@ struct SandboxSetupTests { print(try String(contentsOf: sandbox.sandboxAddonRoot.appendingPathComponent("installer-arguments"), encoding: .utf8), terminator: "") print("requests \(CoordinatorStub.requests.map { $0.url?.absoluteString ?? "" })") + print("== SECOND") + try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: false, + terminal: false, color: false).run() + print("== END") } let output = decodedText(result.standardOutputContent) - let first = try #require(outputSection(output, from: "== FIRST", to: "== SECOND")) + let first = try #require(outputSection(output, from: "== FIRST", to: "== PLAN")) // The sizing lines are the plan's (157 GiB free), not this Mac's probe (800 GiB). #expect(first.hasPrefix(""" Darkbloom Sandbox setup @@ -533,6 +571,7 @@ struct SandboxSetupTests { Eligible. At a time, this Mac can run: 1 Linux job (your choice) no macOS jobs (limited by free disk space) + \(Self.freeSpaceNote(macOSNeeds: 63)) What changes @@ -546,17 +585,236 @@ struct SandboxSetupTests { Next """)) - let second = try #require(outputSection(output, from: "== SECOND", to: "== PLAN")) - #expect(second.hasPrefix("Darkbloom Sandbox is already set up on this Mac.\n\n" - + "Darkbloom Sandbox 1.0.1: downloading images (Linux 42%)\n")) - #expect(second.hasSuffix( - "\nTo change how many jobs run at a time: darkbloom sandbox setup --linux-slots --macos-slots \n")) // The owner's slot counts reach the plan and the install; one download serves both. let plan = try #require(outputSection(output, from: "== PLAN", to: "== INSTALL")) #expect(plan == "--plan\n--json-progress\n--linux-slots\n1\n") let install = try #require(outputSection(output, from: "== INSTALL", to: "requests")) #expect(install == "--json-progress\n--yes\n--no-browser\n--linux-slots\n1\n") - #expect(output.hasSuffix("requests [\"https://sandbox.invalid/install.sh\"]\n")) + #expect(output.contains("requests [\"https://sandbox.invalid/install.sh\"]\n== SECOND")) + // The rerun reports and asks the plan again (1 Linux, no macOS, against 1 + 1 installed); + // without a prompt it does not remove a slot. + let second = try #require(outputSection(output, from: "== SECOND", to: "== END")) + #expect(second.hasPrefix("Darkbloom Sandbox is already set up on this Mac.\n\n" + + "Darkbloom Sandbox 1.0.1: downloading images (Linux 42%)\n")) + #expect(second.hasSuffix(""" + macOS images 46 GiB + 40 GiB per macOS job + \(Self.freeSpaceNote(macOSNeeds: 63)) + + This Mac now fits 1 Linux + 0 macOS (installed: 1 Linux + 1 macOS). + Not applied: it removes slots, and without a prompt setup applies only a plan that adds slots. To apply \ + it: darkbloom sandbox setup --linux-slots 1 --macos-slots 0 + + """)) + } + + // MARK: - Rerun on a Mac that is set up + + @Test("a slot change compares the plan with the installed totals; none without totals or without a job") + func slotChange() throws { + let plan = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan(macOS: 1, freeGiB: 240))) + let change = try #require(SandboxSlotChange(installed: SandboxFixtures.status( + SandboxFixtures.ready(linux: 3, macOS: 0)), plan: plan)) + #expect(change == SandboxSlotChange(installedLinux: 3, installedMacOS: 0, plannedLinux: 1, plannedMacOS: 1)) + #expect(!change.onlyAdds) + #expect(change.applying(to: SandboxSetupOptions(noBrowser: true)) + == SandboxSetupOptions(noBrowser: true, linuxSlots: 1, macOSSlots: 1)) + #expect(SandboxSlotChange(installedLinux: 1, installedMacOS: 0, plannedLinux: 1, plannedMacOS: 1).onlyAdds) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.ready), plan: plan) == nil) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.minimal), plan: plan) == nil) + let none = try #require(SandboxSizingPlan(line: FakeSandboxInstaller.plan(linux: 0, freeGiB: 120))) + #expect(SandboxSlotChange(installed: SandboxFixtures.status(SandboxFixtures.ready), plan: none) == nil) + // An empty answer is yes only where yes is the default. + #expect(SandboxTerminal.confirm("Apply?", defaultYes: true, readInput: { "" }, emit: { _ in })) + #expect(!SandboxTerminal.confirm("Apply?", readInput: { "" }, emit: { _ in })) + #expect(!SandboxTerminal.confirm("Apply?", defaultYes: true, readInput: { "n" }, emit: { _ in })) + } + + /// Runs setup on a Mac with the add-on installed (`status`) against an + /// installer whose plan prints `plan` (none: an installer without plan + /// mode), answering `answer` at a prompt when given; an install prints + /// `installerEvents` and exits with `installerExit`, which setup keeps. + /// Prints the output, then `== PLAN` and `== INSTALL` with the arguments + /// each run got. + private static func rerun(status: String, plan: String?, answer: String? = nil, confirmed: Bool = false, + linuxSlots: Int? = nil, macOSSlots: Int? = nil, + installerEvents: [String] = FakeSandboxInstaller.events, + installerExit: Int32 = 0) async throws -> String { + let expected: ExitTest.Condition = installerExit == 0 ? .success : .exitCode(installerExit) + let result = try await #require(processExitsWith: expected, observing: [\.standardOutputContent]) { + [status = status as String, plan = plan as String?, answer = answer as String?, + confirmed = confirmed as Bool, linuxSlots = linuxSlots as Int?, macOSSlots = macOSSlots as Int?, + installerEvents = installerEvents as [String], installerExit = installerExit as Int32] in + let options = SandboxSetupOptions(server: "https://sandbox.invalid", linuxSlots: linuxSlots, + macOSSlots: macOSSlots) + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + try FakeSandboxAddon.install(.current(status: status), at: sandbox.sandboxAddonRoot) + CoordinatorStub.install(["/install.sh": .init(status: 200, body: Data(FakeSandboxInstaller.script( + events: installerEvents, plan: plan.map { [$0] }, addonStatus: SandboxFixtures.ready(linux: 1, macOS: 1), + exitStatus: installerExit).utf8))]) + if let answer { try replaceStandardInput(with: answer) } + print("== EXPECTED") + SandboxStatusView.lines(SandboxFixtures.status(status)).forEach { print($0) } + print("== OUTPUT") + await exitWithCommandStatus { + defer { + for (marker, file) in [("== PLAN", "plan-arguments"), ("== INSTALL", "installer-arguments")] { + print(marker) + let url = sandbox.sandboxAddonRoot.appendingPathComponent(file) + print((try? String(contentsOf: url, encoding: .utf8)) ?? "none\n", terminator: "") + } + print("== END") + sandbox.remove() + } + try await SandboxSetupFlow(options: options, confirmed: confirmed, addon: .live(), + interactiveInput: answer != nil, terminal: false, color: false).run() + } + } + return decodedText(result.standardOutputContent) + } + + private static let changeHint = "To change how many jobs run at a time: darkbloom sandbox setup " + + "--linux-slots --macos-slots \n" + + /// Today's report for `output`'s Mac: the state, then the slot options. + private static func alreadySetUp(_ output: String) throws -> String { + let status = try #require(outputSection(output, from: "== EXPECTED", to: "== OUTPUT")) + return "Darkbloom Sandbox is already set up on this Mac.\n\n" + status + "\n" + changeHint + } + + @Test("rerun with the plan the Mac runs: today's report, after the plan, changing nothing") + func rerunSamePlan() async throws { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 1, macOS: 1), + plan: FakeSandboxInstaller.plan(message: "1 Linux slot and 1 macOS slot", + macOS: 1, freeGiB: 300)) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== PLAN\n--plan\n--json-progress\n== INSTALL\nnone\n== END\n")) + } + + @Test("rerun with the same plan, macOS short of disk: exactly today's report, without the free-space note") + func rerunSamePlanShortOfDisk() async throws { + // The feedback's Mac before it freed space: 3 Linux slots, macOS short of disk, as installed. + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), + plan: FakeSandboxInstaller.plan(message: "3 Linux slots", linux: 3, + freeGiB: 210)) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== PLAN\n--plan\n--json-progress\n== INSTALL\nnone\n== END\n")) + } + + /// The feedback's Mac: 3 Linux slots installed; with more free space the plan fits 1 Linux and 1 macOS. + private static let macOSFits = FakeSandboxInstaller.plan(message: "1 Linux slot and 1 macOS slot", macOS: 1, + freeGiB: 240) + + @Test("rerun when the plan now fits macOS: it offers the plan; yes applies its counts, no changes nothing") + func rerunOffersPlan() async throws { + let offer = """ + The add-on's plan for this Mac now: + [PASS] CPU: 16 cores; you keep 4 + [PASS] Memory: 128 GB; you keep 32 GB, inference keeps 32 GB + [PASS] Disk: 240 GiB free; 100 GiB stays free for you; Linux images 4 GiB + 30 GiB per Linux job; \ + macOS images 46 GiB + 40 GiB per macOS job + + + """ + "This Mac now fits 1 Linux + 1 macOS (installed: 3 Linux + 0 macOS). If a job is running, the " + + "installer refuses and changes nothing. Apply? [Y/n]: " + for answer in ["\n", "y\n"] { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + answer: answer) + let shown = try #require(outputSection(output, from: "== OUTPUT", to: "== PLAN")) + let report = try Self.alreadySetUp(output).replacingOccurrences(of: Self.changeHint, with: "") + #expect(shown.hasPrefix(report + offer + "\n"), "\(answer)") + #expect(shown.contains("Darkbloom Sandbox is set up on this Mac: ready")) + #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + let declined = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + answer: "n\n") + #expect(declined.contains(offer + "Nothing changed. To apply it later: darkbloom sandbox setup " + + "--linux-slots 1 --macos-slots 1\n== PLAN")) + #expect(declined.hasSuffix("== INSTALL\nnone\n== END\n")) + } + + @Test("rerun without a prompt (--yes or no terminal): only a plan that adds slots and removes none is applied") + func rerunUnattended() async throws { + for confirmed in [true, false] { + // 3 Linux + 0 macOS to 1 + 1 removes Linux slots: suggested, not applied. + let removes = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, + confirmed: confirmed) + #expect(removes.contains("Not applied: it removes slots, and without a prompt setup applies only a plan " + + "that adds slots. To apply it: darkbloom sandbox setup --linux-slots 1 --macos-slots 1\n== PLAN")) + #expect(!removes.contains("[Y/n]")) + #expect(removes.hasSuffix("== INSTALL\nnone\n== END\n")) + // 1 Linux + 0 macOS to 1 + 1 only adds: applied. + let adds = try await Self.rerun(status: SandboxFixtures.ready(linux: 1, macOS: 0), plan: Self.macOSFits, + confirmed: confirmed) + #expect(adds.contains("\nThis Mac now fits 1 Linux + 1 macOS (installed: 1 Linux + 0 macOS).\n" + + "Applying it: it only adds slots.\n\n")) + #expect(adds.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + } + + /// Setup's words for the installer's exit status 4. + private static let jobRunningAdvice = "A job is running on this Mac, so the installer changed nothing. Run " + + "`darkbloom sandbox setup` again when it finishes; `darkbloom sandbox pause` keeps new jobs from starting. " + + "Setup never passes the installer's --force: it would stop running jobs, and stopped jobs aren't paid." + + @Test("applying the plan after a job started: the installer refuses (exit 4), setup says so and exits 4") + func rerunRefusedWhileAJobRuns() async throws { + // add-on 1.1.1's refusal (`InstallError.jobsRunning`) at its install stage. + let refusal = "jobs are running on this Mac; rerun when they finish (the agent also updates itself " + + "between jobs), or pass --force to stop them" + let output = try await Self.rerun( + status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, answer: "y\n", + installerEvents: [FakeSandboxInstaller.stage("installing", "started", "Installing"), + FakeSandboxInstaller.stage("installing", "failed", refusal, #""exit_code":4"#)], + installerExit: 4) + #expect(output.contains("\n\n" + Self.jobRunningAdvice + "\n== PLAN")) + #expect(!output.contains("Darkbloom Sandbox is set up on this Mac")) + // The plan's counts, and no --force: the running job is not stopped. + #expect(output.hasSuffix("== INSTALL\n--json-progress\n--yes\n--linux-slots\n1\n--macos-slots\n1\n== END\n")) + } + + @Test("rerun while jobs run: today's report, no plan, and when to run it again") + func rerunWhileJobsRun() async throws { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0, jobsRunning: 1), + plan: Self.macOSFits) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output) + + "Jobs are running, so setup did not check whether this Mac now fits other slot counts. Run " + + "`darkbloom sandbox setup` again once they finish; `darkbloom sandbox pause` keeps new ones from starting.\n") + #expect(output.hasSuffix("== PLAN\nnone\n== INSTALL\nnone\n== END\n")) + } + + @Test("rerun with explicit slot counts applies them without a plan, as before") + func rerunExplicitCounts() async throws { + let output = try await Self.rerun( + status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: Self.macOSFits, linuxSlots: 2, macOSSlots: 0) + let shown = try #require(outputSection(output, from: "== OUTPUT", to: "== PLAN")) + #expect(shown.hasPrefix("Applying the new slot counts.\n")) + #expect(output.hasSuffix("== PLAN\nnone\n== INSTALL\n--json-progress\n--yes\n--linux-slots\n2\n" + + "--macos-slots\n0\n== END\n")) + } + + @Test("rerun with an installer without plan mode, or one that fails it: today's report") + func rerunWithoutPlan() async throws { + for plan in [nil, "not a plan"] as [String?] { + let output = try await Self.rerun(status: SandboxFixtures.ready(linux: 3, macOS: 0), plan: plan) + #expect(try outputSection(output, from: "== OUTPUT", to: "== PLAN") == Self.alreadySetUp(output)) + #expect(output.hasSuffix("== INSTALL\nnone\n== END\n")) + } + } + + @Test("rerun when the installer cannot be downloaded: today's report and why it could not check") + func rerunOffline() async throws { + let result = try await #require(processExitsWith: .success, observing: [\.standardOutputContent]) { + let sandbox = try CLICommandSandbox.enter(autoRestart: false) + defer { sandbox.remove() } + try FakeSandboxAddon.install(.current(status: SandboxFixtures.ready(linux: 3, macOS: 0)), + at: sandbox.sandboxAddonRoot) + try await SandboxSetupFlow(options: SandboxSetupOptions(server: "https://sandbox.invalid"), + confirmed: false, addon: .live(), interactiveInput: false, + terminal: false, color: false).run() + } + #expect(decodedText(result.standardOutputContent).hasSuffix(Self.changeHint + + "Could not check whether this Mac now fits other slot counts: Could not download the Darkbloom Sandbox " + + "installer from https://sandbox.invalid/install.sh: HTTP 404.\n")) } @Test("when the plan fits no job, setup prints why and how much disk to free, and installs nothing") @@ -584,6 +842,7 @@ struct SandboxSetupTests { Not eligible: No slot fits. Free up 14 GiB of disk for one Linux job, or 66 GiB of disk for one macOS job. + \(Self.freeSpaceNote(macOSNeeds: 66)) planned true installed false diff --git a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift index 9c02785936..450b53eb52 100644 --- a/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift +++ b/provider-swift/Tests/DarkbloomCLITests/SandboxTestSupport.swift @@ -56,6 +56,16 @@ enum SandboxFixtures { static let minimal = #"{"schema":1,"state":"ready"}"# + /// `ready` with these slot counts (all free unless jobs run) and running jobs. + static func ready(linux: Int, macOS: Int, jobsRunning: Int = 0) -> String { + ready.replacingOccurrences( + of: #""jobs_running":0"#, with: #""jobs_running":\#(jobsRunning)"# + ).replacingOccurrences( + of: #""slots":{"linux":{"free":1,"total":1},"macos":{"free":1,"total":1}}"#, + with: #""slots":{"linux":{"free":\#(max(0, linux - jobsRunning)),"total":\#(linux)},"# + + #""macos":{"free":\#(macOS),"total":\#(macOS)}}"#) + } + static func status(_ json: String) -> SandboxAddonStatus { guard let status = SandboxAddonStatus(json: json) else { fatalError("fixture does not decode: \(json)") } return status diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index b6dcab5918..a454346e7d 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -10,15 +10,17 @@ import subprocess -COMPONENTS = ("provider", "sdk", "cluster") +COMPONENTS = ("provider", "cluster", "mimo_audio") COMMON = ( "Makefile", "mise.toml", ".gitmodules", ".github/workflows/component-changes.yml", - ".github/workflows/darkbloom-route.yml", + ".github/workflows/darkbloom-route.yml", ".github/workflows/ci-dev.yml", ".github/workflows/ci-master.yml", + ".github/workflows/provider-plan.yml", "scripts/ci-tested-tree.py", "scripts/test-ci-tested-tree.py", "scripts/ci-component-paths.py", "scripts/test-ci-component-paths.py", ) PROVIDER = ( "provider-swift/**", "libs/**", "fixtures/**", - ".github/workflows/ci.yml", ".github/actions/provider-ci-build/**", + ".github/workflows/provider-tests.yml", ".github/actions/provider-ci-build/**", + "scripts/provider-ci-cold-retry.sh", "scripts/provider-ci-cache.py", "scripts/provider_ci_cache/**", "scripts/provider-release-cache.py", "scripts/provider_release_cache/**", "scripts/provider-release-swift.sh", "scripts/prepare-provider-release-toolchain.sh", @@ -29,7 +31,9 @@ "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", "scripts/cluster-test-plan.py", "scripts/cluster-stage-content-inventory.py", - "scripts/prepare-mimo-*-fixtures.py", "scripts/verify-*-prompt-parity.sh", + "scripts/swift_test_lock_retry.py", + "scripts/prepare-mimo-*-fixtures.py", "scripts/verified_download_cache.py", + "scripts/verify-*-prompt-parity.sh", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", "scripts/verify-prompt-parity.sh", "scripts/test-qwen4-packaged-resources.py", "scripts/test-profile-inventory-auth.py", "scripts/test-desktop-api.py", "scripts/install.sh", @@ -37,27 +41,12 @@ ) -# Inputs of the Provider SDK Tests lane: the SDK and MLX pins it builds, its -# build recipe and its runner scripts. Its suites also run in the SDK fork's CI. -SDK = ( - "libs/mlx-swift-lm", "libs/mlx-swift-lm/**", "libs/mlx-swift", "libs/mlx-swift/**", - ".github/workflows/ci.yml", ".github/actions/provider-ci-build/**", - "scripts/provider-ci-cache.py", "scripts/provider_ci_cache/**", - "scripts/provider-release-cache.py", "scripts/provider_release_cache/**", - "scripts/provider-release-swift.sh", "scripts/prepare-provider-release-toolchain.sh", - "scripts/install-release-cmake.sh", "scripts/prepare-metal-toolchain.py", - "scripts/fetch-metallib.sh", "scripts/stage-test-metallib.sh", - "scripts/run-nested-suite.sh", "scripts/run-paged-kernel-tests.sh", - "scripts/run-exclusive-native-gpu-test.sh", "scripts/prepare-mimo-provider-fixtures.py", -) - - -# Inputs of the cluster jobs (Cluster Metadata Checks, Cluster Runtime Tests, +# Inputs of the cluster jobs (Cluster Runtime Tests, # Cluster GPU Tests, Cluster Focused Checks): the cluster packages and the MLX # pins they build, the provider sources their runner scripts compile (every # Cluster, Distributed and NativePair source, and the files the runners name), # the cluster plan and the shared build recipe. Every cluster input is also a -# provider input. A push that selects the provider lanes also selects these. +# provider input. CLUSTER = ( "libs/darkbloom-cluster/**", "libs/darkbloom-cluster-worker/**", "libs/mlx", "libs/mlx/**", "libs/mlx-swift", "libs/mlx-swift/**", "libs/mlx-swift-lm", "libs/mlx-swift-lm/**", @@ -72,13 +61,31 @@ # provider unit tests of cluster code run in the provider lane. "provider-swift/Tests/Cluster*Checks/**", "provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/cluster_registration_vector.json", - ".github/workflows/ci.yml", ".github/actions/provider-ci-build/**", + ".github/workflows/provider-tests.yml", ".github/actions/provider-ci-build/**", + "scripts/provider-ci-cold-retry.sh", "scripts/provider-ci-cache.py", "scripts/provider_ci_cache/**", "scripts/provider-release-cache.py", "scripts/provider_release_cache/**", "scripts/provider-release-swift.sh", "scripts/prepare-provider-release-toolchain.sh", "scripts/install-release-cmake.sh", "scripts/prepare-metal-toolchain.py", "scripts/fetch-metallib.sh", "scripts/stage-test-metallib.sh", "scripts/run-nested-suite.sh", "scripts/cluster-test-plan.py", "scripts/cluster-stage-content-inventory.py", + "scripts/swift_test_lock_retry.py", +) + + + +# Inputs of the MiMo audio gate in the last provider shard, which needs the +# 1.87 GB pinned audio codec: the MiMo, audio and media provider code, the MiMo +# tests, the MLX pins, the fixture scripts (the audio one runs the provider +# fixture generator with --audio-source) and the gate's recipe. Every one is +# also a provider input. +MIMO_AUDIO = ( + "provider-swift/Package.swift", "provider-swift/Package.resolved", + "provider-swift/Sources/*MiMo*", "provider-swift/Sources/*Audio*", "provider-swift/Sources/*Media*", + "provider-swift/Tests/ProviderCoreTests/MiMo/*", + "libs/mlx", "libs/mlx/**", "libs/mlx-swift", "libs/mlx-swift/**", "libs/mlx-swift-lm", "libs/mlx-swift-lm/**", + ".github/workflows/provider-tests.yml", "scripts/prepare-mimo-audio-fixtures.py", + "scripts/prepare-mimo-provider-fixtures.py", "scripts/run-nested-suite.sh", ) @@ -96,8 +103,8 @@ def classify(paths): if matches(path, COMMON): return dict.fromkeys(COMPONENTS, True) selected["provider"] |= matches(path, PROVIDER) - selected["sdk"] |= matches(path, SDK) selected["cluster"] |= matches(path, CLUSTER) + selected["mimo_audio"] |= matches(path, MIMO_AUDIO) return selected @@ -111,8 +118,21 @@ def revision(value): return git("rev-parse", "--verify", value + "^{commit}").decode().strip() +RELEASE_BRANCHES = ("master", "main") + + +def full_run(event_name, event): + """Master is the release line: its pushes and the pull requests into it test every component.""" + if event_name == "push": + return event.get("ref") in tuple(f"refs/heads/{branch}" for branch in RELEASE_BRANCHES) + if event_name == "pull_request": + return event["pull_request"]["base"].get("ref") in RELEASE_BRANCHES + return False + + def changed_paths(event_name, event): - if event_name == "workflow_dispatch": + """The changed paths, or None when every component runs.""" + if event_name == "workflow_dispatch" or full_run(event_name, event): return None if event_name == "pull_request": base = revision(event["pull_request"]["base"]["sha"]) @@ -139,13 +159,10 @@ def main(): args = parser.parse_args() event = json.loads(Path(args.event_path).read_text()) paths = changed_paths(args.event_name, event) - # Default-branch pushes retain full coverage after validating the diff. - full = paths is None or (args.event_name == "push" and event.get("ref") in - ("refs/heads/master", "refs/heads/main")) - selected = dict.fromkeys(COMPONENTS, True) if full else classify(paths) - # Pushes keep the cluster jobs wherever they run the provider lanes. - if args.event_name == "push": - selected["cluster"] = selected["cluster"] or selected["provider"] + # Pull requests and pushes select alike: a push diffs against the + # branch's previous commit (`before`); without one, everything runs. + # Master pushes and pull requests into master select everything. + selected = dict.fromkeys(COMPONENTS, True) if paths is None else classify(paths) output = "".join(f"{name}={str(enabled).lower()}\n" for name, enabled in selected.items()) if args.output: with open(args.output, "a") as destination: diff --git a/scripts/ci-tested-tree.py b/scripts/ci-tested-tree.py new file mode 100755 index 0000000000..a318673e47 --- /dev/null +++ b/scripts/ci-tested-tree.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Find a successful CI run of this workflow that already tested the same change. + +CI tests each change once. A passing run's gate uploads an empty record, an +artifact named + + ci-tested----p<0|1>c<0|1>m<0|1> + + is the tree the run tested. A pull request run names the base and head +commits GitHub merged for its test (`github.event.pull_request.base.sha`, +`.head.sha`); a push run names `push` and its commit. The p, c and m flags +say which components ran: provider, cluster, MiMo audio. + +Before testing, a run looks for a record that binds to its own change and +covers every component it would run: + +- a pull request: `--` of its own event; +- a push of commit S: `--` (the pull + request whose head S merges, tested against S's first parent), and + `-push-` (an earlier run of this push). + +It accepts a record only from a completed, successful run of the same +workflow file in this repository (not a fork), of the matching event, whose +head commit is the record's head. Any doubt runs the tests: no record, an +expired or foreign one, a failed or unfinished run, or an API error. + +A same-repository pull request runs its own workflow file, so a record is as +trustworthy as the reviewed workflow at that head; the binding keeps a +record of one change from standing in for another. + +Usage: ci-tested-tree.py lookup --repository OWNER/REPO --workflow-ref REF + --event NAME --sha SHA --tree TREE [--base SHA --head SHA] + --components provider=B,cluster=B,mimo_audio=B --run-id ID + [--output GITHUB_OUTPUT] + ci-tested-tree.py name --tree TREE --base SHA|push --head SHA + --components ... +Reads GITHUB_TOKEN (actions: read, contents: read) from the environment. +""" + +import argparse +import itertools +import json +import os +import re +import sys +import urllib.request + +API = "https://api.github.com" +COMPONENTS = ("provider", "cluster", "mimo_audio") +FLAGS = dict(zip(COMPONENTS, "pcm")) +SHA = re.compile(r"[0-9a-f]{40}") + + +def github_get(path): + request = urllib.request.Request(API + path, headers={ + "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", + "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}", "User-Agent": "ci-tested-tree/2"}) + with urllib.request.urlopen(request, timeout=20) as response: + return json.load(response) + + +def sha(value, what): + if not isinstance(value, str) or not SHA.fullmatch(value): + raise ValueError(f"Expected a full {what} SHA, got {value!r}") + return value + + +def components(text): + """`provider=true,cluster=false,mimo_audio=false` -> {name: bool}, every name once.""" + pairs = dict(item.split("=", 1) for item in text.split(",") if item) + if set(pairs) != set(COMPONENTS) or not set(pairs.values()) <= {"true", "false"}: + raise ValueError(f"Expected each of {COMPONENTS} as true or false, got {text!r}") + return {name: pairs[name] == "true" for name in COMPONENTS} + + +def flags(selected): + return "".join(f"{FLAGS[name]}{int(selected[name])}" for name in COMPONENTS) + + +def record_name(tree, base, head, selected): + return f"ci-tested-{sha(tree, 'tree')}-{base if base == 'push' else sha(base, 'base')}-{sha(head, 'head')}-{flags(selected)}" + + +def supersets(selected): + """Every component set that covers `selected`, `selected` itself first.""" + choices = [[True] if selected[name] else [False, True] for name in COMPONENTS] + return [dict(zip(COMPONENTS, values)) for values in itertools.product(*choices)] + + +def workflow_path(workflow_ref, repository): + """`.github/workflows/` from github.workflow_ref, or ValueError.""" + match = re.fullmatch(re.escape(repository) + r"/(\.github/workflows/[A-Za-z0-9._-]+\.ya?ml)@.+", workflow_ref) + if not match: + raise ValueError(f"Unexpected workflow ref: {workflow_ref!r}") + return match.group(1) + + +def candidates(repository, event, commit, tree, base, head, get): + """[(base, head, event of the recording run)] that may stand in for this run.""" + if event == "pull_request": + return [(sha(base, "base"), sha(head, "head"), "pull_request")] + if event != "push": + raise ValueError(f"Unsupported event: {event!r}") + found = get(f"/repos/{repository}/git/commits/{commit}") + if found.get("tree", {}).get("sha") != tree: + raise ValueError("The pushed commit's tree is not the tree under test") + parents = [parent.get("sha") for parent in found.get("parents", [])] + result = [("push", commit, "push")] + if len(parents) == 2 and all(isinstance(parent, str) and SHA.fullmatch(parent) for parent in parents): + result.insert(0, (parents[0], parents[1], "pull_request")) + return result + + +def tested_run(repository, path, event, commit, tree, base, head, selected, run_id, get=github_get): + """The URL of a successful run that recorded this change with a superset, or None.""" + sha(tree, "tree") + sha(commit, "commit") + for record_base, record_head, record_event in candidates(repository, event, commit, tree, base, head, get): + for covering in supersets(selected): + name = record_name(tree, record_base, record_head, covering) + listing = get(f"/repos/{repository}/actions/artifacts?name={name}&per_page=100") + for artifact in listing.get("artifacts", []): + source = artifact.get("workflow_run") or {} + if artifact.get("name") != name or artifact.get("expired"): + continue + if not isinstance(source.get("id"), int) or source["id"] == run_id: + continue + run = get(f"/repos/{repository}/actions/runs/{source['id']}") + if (run.get("status") == "completed" and run.get("conclusion") == "success" + and run.get("path") == path and run.get("event") == record_event + and run.get("head_sha") == record_head + and (run.get("repository") or {}).get("full_name") == repository + and (run.get("head_repository") or {}).get("full_name") == repository): + return run.get("html_url") or f"https://github.com/{repository}/actions/runs/{source['id']}" + return None + + +def decide(repository, workflow_ref, event, commit, tree, base, head, selected, run_id, get=github_get): + """Return (skip, run_url, note). Every failure runs the tests.""" + if not any(selected.values()): + return False, "", "No component is selected; there is nothing to test or skip." + try: + url = tested_run(repository, workflow_path(workflow_ref, repository), event, commit, tree, + base, head, selected, run_id, get) + except Exception as error: # noqa: BLE001 - any doubt means test + return False, "", f"Tree lookup failed ({type(error).__name__}: {error}); testing." + if url: + return True, url, f"This change ({tree}, {flags(selected)}) already passed in {url}; this run skips its tests." + return False, "", f"No successful run of this workflow tested this change ({tree}, {flags(selected)}); testing." + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + lookup = commands.add_parser("lookup") + for option in ("--repository", "--workflow-ref", "--event", "--sha", "--tree", "--components"): + lookup.add_argument(option, required=True) + lookup.add_argument("--base", default="") + lookup.add_argument("--head", default="") + lookup.add_argument("--run-id", type=int, required=True) + lookup.add_argument("--output", default=os.environ.get("GITHUB_OUTPUT")) + name = commands.add_parser("name") + for option in ("--tree", "--base", "--head", "--components"): + name.add_argument(option, required=True) + args = parser.parse_args() + if args.command == "name": + print(record_name(args.tree, args.base, args.head, components(args.components))) + return 0 + try: + selected = components(args.components) + except ValueError as error: + print(f"Tree lookup failed ({error}); testing.") + selected = None + if selected is None: + skip, url = False, "" + else: + skip, url, note = decide(args.repository, args.workflow_ref, args.event, args.sha, args.tree, + args.base, args.head, selected, args.run_id) + print(note) + lines = f"skip={str(skip).lower()}\ntested_run={url}\n" + if args.output: + with open(args.output, "a") as output: + output.write(lines) + else: + sys.stdout.write(lines) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py index 5230ad80e4..66ac781854 100755 --- a/scripts/cluster-test-plan.py +++ b/scripts/cluster-test-plan.py @@ -16,11 +16,14 @@ the model-free runner scripts). Subcommands: - run LANE SHARD run the selections of one shard, each in its own process + run LANE SHARD run the selections of one shard, each in its own process: + the shard's groups at the same time, then the others alone audit check the plan against the sources and the workflow """ import argparse +import importlib.util +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field import os from pathlib import Path @@ -34,7 +37,7 @@ ROOT = Path(__file__).resolve().parent.parent PACKAGE = ROOT / "libs/darkbloom-cluster" RUNTIME_TESTS = PACKAGE / "Tests/DarkbloomClusterRuntimeTests" -WORKFLOW = ROOT / ".github/workflows/ci.yml" +WORKFLOW = ROOT / ".github/workflows/provider-tests.yml" NESTED_SUITE = ROOT / "scripts/run-nested-suite.sh" MODULE = "DarkbloomClusterRuntimeTests" LANES = ("blocking", "nonblocking", "focused") @@ -55,6 +58,10 @@ class Selection: suites: tuple | None = None # Focused: a runner script under libs/darkbloom-cluster/Tests. runner: str | None = None + # The shard runs its groups at the same time, each group's selections one + # after another in plan order; the selections with no group then run one + # at a time, alone on the Mac. + group: int | None = None @property def base(self): @@ -100,10 +107,16 @@ def base(self): ) SELECTIONS = ( - # Its CPU path is the longest suite, so it has a shard of its own. - Selection("base-batch-session", "blocking", 1, suites=("QwenTensorParallelBatchSessionTests",)), - Selection("base", "blocking", 2), - Selection("qwen-tp-batch-gpu", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1"}, tests=( + # Blocking shard 1 runs `base`, the longest selection, alone, then the + # share probe alone. The probe times its share against a 1.5 s budget, so + # it never runs on a Mac just after the concurrent GPU groups (run + # 41973436945 failed it there). Shard 2 runs group 1 (the CPU + # batch-session suite, then the GLM paged-KV, invariance and census, TF32 + # and Gemma selections) beside group 2 (the Qwen GPU chain and + # glm53-prefix-ssd). + Selection("base-batch-session", "blocking", 2, suites=("QwenTensorParallelBatchSessionTests",), group=1), + Selection("base", "blocking", 1), + Selection("qwen-tp-batch-gpu", "blocking", 2, {"QWEN_TP_BATCH_GPU": "1"}, tests=( "bothTilesGiveTheSameBytes", "actualHybridShardsPreserveAttentionConvAndSSMRows", "nineBRatioDenseShardsBatchExactly", @@ -115,16 +128,16 @@ def base(self): "mergedStepTemporariesStayWithinTheirCharge", "mergedFramesKeepEveryBit", "executorRunsThePlannedMergedStep", - )), - Selection("qwen-tp-batch-gpu-paged", "blocking", 3, {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( + ), group=2), + Selection("qwen-tp-batch-gpu-paged", "blocking", 2, {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( "cohortSurvivorKeepsOnlyItsOwnRows", "routedExpertCapacityOneAndTwoKeepExactPagedLogitsAndHistory", "capacityOneAndTwoKeepExactPagedLogitsAndHistory", "pagesGrowMidDecodeWithoutChangingAByte", "promptLayerSubmissionKeepsEveryBit", - )), - Selection("qwen-tp-mtp-gpu", "blocking", 3, {"QWEN_TP_MTP_GPU": "1"}, tests=QWEN_TP_MTP_GPU_TESTS), - Selection("qwen-tp-aqv-gpu", "blocking", 3, {"QWEN_TP_AQV_GPU": "1"}, tests=( + ), group=2), + Selection("qwen-tp-mtp-gpu", "blocking", 2, {"QWEN_TP_MTP_GPU": "1"}, tests=QWEN_TP_MTP_GPU_TESTS, group=2), + Selection("qwen-tp-aqv-gpu", "blocking", 2, {"QWEN_TP_AQV_GPU": "1"}, tests=( "declinesWhatItDoesNotCover", "agreesWithTheDequantizedProduct", "everyVectorEqualsItsOwnSingleVectorCall", @@ -134,40 +147,40 @@ def base(self): "siluMultiplyEqualsTheUnfusedChain", "sigmoidGateEqualsTheUnfusedChain", "cachedGatedDeltaScalesEqualFreshOnes", - )), - Selection("qwen-tp-moe-gpu", "blocking", 3, {"QWEN_TP_MOE_GPU": "1", "QWEN_TP_MOE_GPU_DIAG": "1"}, tests=( + ), group=2), + Selection("qwen-tp-moe-gpu", "blocking", 2, {"QWEN_TP_MOE_GPU": "1", "QWEN_TP_MOE_GPU_DIAG": "1"}, tests=( "packedSharedExpertCollectiveIsBitIdenticalOnTwoGPURanks", "packedRunsRepeatAndShortPromptsOnTwoGPURanks", - )), - Selection("qwen-tp-share-probe-gpu", "blocking", 3, {"QWEN_TP_SHARE_PROBE_GPU": "1"}, tests=( + ), group=2), + Selection("qwen-tp-share-probe-gpu", "blocking", 1, {"QWEN_TP_SHARE_PROBE_GPU": "1"}, tests=( "eachRankTimesItsShareAloneAndReleasesItsRequest", "aRefusalOrAFailureGivesNoProbeAndKeepsNothing", )), - Selection("glm53-prefix-ssd", "blocking", 3, {"GLM53_PREFIX_SSD": "1"}, tests=( + Selection("glm53-prefix-ssd", "blocking", 2, {"GLM53_PREFIX_SSD": "1"}, tests=( "aServingStageRestoresFromTheSSDExactly", "aServingStageRestoresFromABalancedRecord", - )), + ), group=2), Selection("glm53-paged-kv", "blocking", 2, {"GLM53_PAGED_KV": "1"}, tests=( "pagedRequestsDecideAndHoldWhatContiguousOnesDo", "pagedMediaRequestsDecideAndHoldWhatContiguousOnesDo", - )), + ), group=1), Selection("glm53-row-invariance", "blocking", 2, {"GLM53_ROW_INVARIANCE": "1"}, tests=( "roundsAreEachRequestsOwnRound", - )), + ), group=1), Selection("glm53-depth-invariance", "blocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( "prefillIsTheSameWithAndWithoutTheSwitch", "unpaddedLastRoundsStayOneRowWindows", - )), + ), group=1), Selection("glm53-window-census", "blocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( "sublayerCensus", "projectionRowCensus", - )), + ), group=1), Selection("tf32-off", "blocking", 2, {"MLX_ENABLE_TF32": "0"}, tests=( "receiverCommitPrecedesProducerPublicationAndMatchesFullCachedForward", - )), + ), group=1), Selection("gemma-tp-diag", "blocking", 2, {"GEMMA_TP_DIAG": "1"}, tests=( "diagnosticShardOperationsEqualWholeOperations", - )), + ), group=1), Selection("qwen-tp-real-geometry-gpu", "nonblocking", 1, {"QWEN_TP_REAL_GEOMETRY_GPU": "1"}, tests=( "rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths", )), @@ -234,7 +247,7 @@ def base(self): "verifyWindowRoundsByRowCount", ) REQUIRES_MODEL_SUITES = ("GLM5NextServingMetadataTests", "GLM5NextTensorParallelMediaTowerTests") -# Runners the Cluster Metadata Checks job runs with its retained native build. +# Runners Cluster Focused Checks runs first, with its retained native build. METADATA_JOB_RUNNERS = ("GPTOSSStageChecks", "NemotronStageChecks", "PrefillScheduleChecks", "StageMetadataChecks") @@ -264,7 +277,12 @@ def swift_arguments(selection): def command(selection, output): if selection.runner is None: - return PACKAGE, [str(NESTED_SUITE), *swift_arguments(selection)] + filter_regex, *extra = swift_arguments(selection) + # The groups of a shard share one build. With --skip-build no process + # writes it, so they skip SwiftPM's lock on .build, which would + # otherwise run them one after another. + lock = ["--ignore-lock"] if selection.group is not None else [] + return PACKAGE, [str(NESTED_SUITE), filter_regex, *lock, *extra] directory = PACKAGE / "Tests" / selection.runner if (directory / "run.py").is_file(): return ROOT, ["python3", str(directory / "run.py"), "--output", str(output / selection.runner)] @@ -287,23 +305,95 @@ def shards(lane): return sorted({selection.shard for selection in SELECTIONS if selection.lane == lane}) +def lock_retry(): + """scripts/swift_test_lock_retry.py, loaded by path (scripts/ is not a package).""" + spec = importlib.util.spec_from_file_location("swift_test_lock_retry", ROOT / "scripts/swift_test_lock_retry.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def execute(selection, output, log=None, temporary=None): + """Run one selection in its own process; return (exit status, seconds). + + A grouped selection (log given) runs beside another group's process. Its + SwiftPM can find the build database locked by that process's startup; it + then runs the tests and exits 1. Such a selection runs once more, but only + when its log proves every test passed (scripts/swift_test_lock_retry.py). + The first attempt's log stays beside the log, as .attempt-1, and + prints with it. + """ + cwd, argv = command(selection, output) + env = environment(selection) + if temporary is not None: + env["TMPDIR"] = str(temporary) + started = time.monotonic() + for attempt in (1, 2): + status = subprocess.run(argv, cwd=cwd, env=env, stdout=log, + stderr=subprocess.STDOUT if log is not None else None).returncode + if status == 0 or log is None or attempt == 2: + break + log.flush() + path = Path(log.name) + text = path.read_bytes() + if not lock_retry().only_locked(text.decode(errors="replace")): + break + path.with_name(path.name + ".attempt-1").write_bytes(text) + log.seek(0) + log.truncate() + return status, time.monotonic() - started + + +def run_group(number, selections, output): + """Run one group's selections in plan order, each logging to its own file.""" + temporary = output / f"group-{number}-tmp" + temporary.mkdir() + results = [] + for selection in selections: + path = output / f"{selection.name}.log" + with path.open("wb") as log: + status, seconds = execute(selection, output, log, temporary) + results.append((selection, status, seconds, path)) + return results + + def run(lane, shard): selected = [selection for selection in SELECTIONS if selection.lane == lane and selection.shard == shard] if not selected: raise ValueError(f"No selections in {lane} shard {shard}") output = Path(tempfile.mkdtemp(prefix="cluster-runner-output-")) - rows = [] + groups = {} + for selection in selected: + if selection.group is not None: + groups.setdefault(selection.group, []).append(selection) + results = {} + if groups: + # The groups run at the same time; their logs print afterwards, whole. + with ThreadPoolExecutor(max_workers=len(groups)) as pool: + futures = [pool.submit(run_group, number, members, output) for number, members in sorted(groups.items())] + finished = [result for future in futures for result in future.result()] + for selection, status, seconds, path in finished: + print(f"::group::{selection.name} (group {selection.group})", flush=True) + first = path.with_name(path.name + ".attempt-1") + if first.is_file(): + print(f"Attempt 1: every test passed, but SwiftPM's build database was locked; " + f"the selection ran once more. Attempt 1's log:", flush=True) + sys.stdout.buffer.write(first.read_bytes()) + print("Attempt 2's log:", flush=True) + sys.stdout.buffer.write(path.read_bytes()) + sys.stdout.flush() + print("::endgroup::", flush=True) + results[selection.name] = (status, seconds) for selection in selected: - cwd, argv = command(selection, output) - print(f"::group::{selection.name}", flush=True) - started = time.monotonic() - status = subprocess.run(argv, cwd=cwd, env=environment(selection)).returncode - seconds = time.monotonic() - started - print("::endgroup::", flush=True) - rows.append((selection.name, status, seconds)) + if selection.group is None: + print(f"::group::{selection.name}", flush=True) + results[selection.name] = execute(selection, output) + print("::endgroup::", flush=True) + rows = [(selection.name, *results[selection.name]) for selection in selected] + for name, status, _ in rows: if status: level = "warning" if lane == "nonblocking" else "error" - print(f"::{level}::{selection.name} failed with exit status {status}", flush=True) + print(f"::{level}::{name} failed with exit status {status}", flush=True) summary = os.environ.get("GITHUB_STEP_SUMMARY") if summary: with open(summary, "a") as handle: diff --git a/scripts/docs-impact-rules.json b/scripts/docs-impact-rules.json index d12551a470..bd364e7144 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -75,7 +75,7 @@ }, { "name": "build and test tooling", - "source_patterns": ["Makefile", "mise.toml", ".githooks/**", ".github/dependabot.yml", ".github/workflows/ci.yml", ".github/workflows/component-changes.yml", ".github/workflows/darkbloom-route.yml", ".github/actions/provider-ci-build/**", "scripts/ci-component-paths.py", "scripts/test-ci-component-paths.py", "scripts/docs-*", "scripts/test-docs-*", "scripts/run-*", "scripts/stage-*", "scripts/fetch-metallib.sh", "scripts/provider-ci-cache.py", "provider-swift/Package.swift", ".gitmodules"], + "source_patterns": ["Makefile", "mise.toml", ".githooks/**", ".github/dependabot.yml", ".github/workflows/ci-dev.yml", ".github/workflows/ci-master.yml", ".github/workflows/provider-plan.yml", ".github/workflows/provider-tests.yml", ".github/workflows/component-changes.yml", ".github/workflows/darkbloom-route.yml", ".github/actions/provider-ci-build/**", "scripts/ci-component-paths.py", "scripts/test-ci-component-paths.py", "scripts/docs-*", "scripts/test-docs-*", "scripts/run-*", "scripts/stage-*", "scripts/fetch-metallib.sh", "scripts/provider-ci-cache.py", "provider-swift/Package.swift", ".gitmodules"], "docs_any_of": ["docs/developer/build.md", "docs/developer/test.md"] }, { diff --git a/scripts/install-release-cmake.sh b/scripts/install-release-cmake.sh index 036ee02d5f..bf93b222be 100755 --- a/scripts/install-release-cmake.sh +++ b/scripts/install-release-cmake.sh @@ -7,17 +7,29 @@ if [ "$(uname -s)-$(uname -m)" != Darwin-arm64 ]; then exit 2 fi -archive="$(mktemp)" -trap 'rm -f "$archive"' EXIT -curl --fail --silent --show-error --location --retry 3 \ - https://github.com/Kitware/CMake/releases/download/v3.31.12/cmake-3.31.12-macos-universal.tar.gz \ - --output "$archive" -printf '%s %s\n' \ - '799af7fd545db9bf1b9cfe72f8095880e727a2d4e0df0e3dffc3bc7b95c2d3b0' \ - "$archive" | shasum -a 256 --check -install_root="$RUNNER_TEMP/cmake-3.31.12" -mkdir -p "$install_root" -tar -xzf "$archive" -C "$install_root" -cmake_bin="$install_root/cmake-3.31.12-macos-universal/CMake.app/Contents/bin" +version=3.31.12 +# Darkbloom macOS images unpack this same sha256-checked archive into the +# runner tool cache (darkbloom-sandbox images/macos/guest/provision.sh, +# cmake_toolcache). Use that copy rather than downloading 80 MB again; download +# everywhere else, such as on Blacksmith. +cached="${RUNNER_TOOL_CACHE:-/nonexistent}/cmake/$version/universal" +if [ -f "$cached.complete" ] && + [ "$("$cached/CMake.app/Contents/bin/cmake" --version 2>/dev/null | head -n 1)" = "cmake version $version" ]; then + cmake_bin="$cached/CMake.app/Contents/bin" + echo "Using CMake $version from the runner tool cache" +else + archive="$(mktemp)" + trap 'rm -f "$archive"' EXIT + curl --fail --silent --show-error --location --retry 3 \ + "https://github.com/Kitware/CMake/releases/download/v$version/cmake-$version-macos-universal.tar.gz" \ + --output "$archive" + printf '%s %s\n' \ + '799af7fd545db9bf1b9cfe72f8095880e727a2d4e0df0e3dffc3bc7b95c2d3b0' \ + "$archive" | shasum -a 256 --check + install_root="$RUNNER_TEMP/cmake-$version" + mkdir -p "$install_root" + tar -xzf "$archive" -C "$install_root" + cmake_bin="$install_root/cmake-$version-macos-universal/CMake.app/Contents/bin" +fi "$cmake_bin/cmake" --version printf '%s\n' "$cmake_bin" >> "$GITHUB_PATH" diff --git a/scripts/prepare-mimo-image-http-fixtures.py b/scripts/prepare-mimo-image-http-fixtures.py index efe17efae4..57bf656a2b 100644 --- a/scripts/prepare-mimo-image-http-fixtures.py +++ b/scripts/prepare-mimo-image-http-fixtures.py @@ -8,6 +8,8 @@ import subprocess import zlib +from verified_download_cache import cached + SPEC = importlib.util.spec_from_file_location( "mimo_audio_pins", Path(__file__).with_name("prepare-mimo-audio-fixtures.py")) PINS = importlib.util.module_from_spec(SPEC) @@ -54,10 +56,12 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--github-env", type=Path, required=True) + parser.add_argument("--cache", type=Path, help="content-addressed directory of verified downloads") args = parser.parse_args() if any(c in str(args.output) for c in "\r\n"): raise ValueError("invalid environment path") - output = prepare(args.output) + fetch = download if args.cache is None else cached(download, args.cache, lambda name: PINS.FILES[name][1]) + output = prepare(args.output, fetch) with args.github_env.open("a", encoding="utf-8") as stream: stream.write(f"MIMO_CLUSTER_IMAGE_METADATA_DIR={output}\nMIMO_CLUSTER_IMAGE_ASSET_DIR={output}\n") diff --git a/scripts/prepare-mimo-prompt-fixtures.py b/scripts/prepare-mimo-prompt-fixtures.py index b6d3435fc6..c4fc0bd3ab 100644 --- a/scripts/prepare-mimo-prompt-fixtures.py +++ b/scripts/prepare-mimo-prompt-fixtures.py @@ -8,6 +8,8 @@ import urllib.parse import urllib.request +from verified_download_cache import cached + REPOSITORY = "XiaomiMiMo/MiMo-V2.6-Flash-RL" REVISION = "5711b268169967567844e1e560e8a3966da959b1" PINS = { @@ -61,10 +63,12 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--github-env", type=Path) + parser.add_argument("--cache", type=Path, help="content-addressed directory of verified downloads") args = parser.parse_args() root = Path(__file__).resolve().parent.parent corpus = root / "fixtures/prompt-contract/mimo-v26-additional20.json" - output = prepare(args.output, corpus) + download = public_metadata if args.cache is None else cached(public_metadata, args.cache, PINS.__getitem__) + output = prepare(args.output, corpus, download) lines = [f"MIMO_PROMPT_ARTIFACT_DIRECTORY={output}", f"MIMO_PROMPT_REFERENCE_VECTORS={corpus}"] if any("\n" in line or "\r" in line for line in lines): diff --git a/scripts/provider-ci-cache.py b/scripts/provider-ci-cache.py index 521d57d1a2..f7981fe91b 100644 --- a/scripts/provider-ci-cache.py +++ b/scripts/provider-ci-cache.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Emit compatible cache keys for provider and nested SDK CI. -Run `keys --lane provider|sdk|cluster` after Metal toolchain setup. +Run `keys --lane provider|cluster` after Metal toolchain setup. Redirect scalar stdout to GITHUB_OUTPUT. Swift restore prefixes retain all compatibility boundaries; the shared metallib key is exact-only. Cache hits never authorize skipping tests @@ -19,9 +19,12 @@ CACHE_VERSION = "v1" +# Swift build keys have three nested tiers since v3 (see keys()). +SWIFT_CACHE_VERSION = "v3" +# The MLX gitlinks: the provider's most expensive dependencies to compile. +MLX_GITLINKS = ("libs/mlx", "libs/mlx-swift", "libs/mlx-swift-lm") LANE_PURPOSES = { "provider": "provider-debug-tests", - "sdk": "sdk-nested-debug-tests", "cluster": "cluster-runtime-debug-tests", } MLX_SOURCE = "libs/mlx-swift/Source/Cmlx/mlx" @@ -29,7 +32,7 @@ METALLIB_RECIPE_PATHS = ("scripts/fetch-metallib.sh", "scripts/stage-test-metallib.sh", "scripts/install-release-cmake.sh") RECIPE_PATHS = ( - ".github/workflows/ci.yml", + ".github/workflows/provider-tests.yml", ".github/actions/provider-ci-build/action.yml", "scripts/provider-ci-cache.py", "scripts/test-provider-ci-cache.py", @@ -38,6 +41,8 @@ "scripts/prepare-provider-release-toolchain.sh", "scripts/provider-release-swift.sh", "scripts/run-provider-tests.sh", + "scripts/swift_test_lock_retry.py", + "scripts/provider-ci-cold-retry.sh", "scripts/run-provider-test-watchdog.py", "scripts/run-nested-suite.sh", "scripts/run-paged-kernel-tests.sh", @@ -124,14 +129,30 @@ def keys(root: Path, lane: str, metadata: dict | None = None) -> dict[str, str]: for path in (root / "scripts/provider_release_cache").glob("*.py")) recipe = {path: tracked.file_hash(root, path) if (root / path).exists() else "absent" for path in sorted(recipe_paths)} - compatibility_hash = identity.digest({ - "version": CACHE_VERSION, "purpose": LANE_PURPOSES[lane], + # Three nested tiers; a restore key matches by prefix, so each tier's + # prefix starts the next one's. The MLX prefix binds the toolchain, the + # checkout path and the MLX gitlinks only. The loose prefix adds the + # dependency manifests and pins (Package.swift, Package.resolved, every + # gitlink). The strict prefix adds the CI recipe (workflows, scripts), which + # changes often and rarely changes an object. A build restored from a + # looser tier rebuilds what changed (restore-mtimes; MLX's objects stay + # valid when its pins and the toolchain match) and, if it fails, builds once + # from nothing (scripts/provider-ci-cold-retry.sh). + mlx_pins = {path: commit for path, commit in sources.gitlinks.items() + if any(path == name or path.startswith(name + "/") for name in MLX_GITLINKS)} + mlx_hash = identity.digest({ + "version": SWIFT_CACHE_VERSION, "purpose": LANE_PURPOSES[lane], "checkout": checkout_path, "resolved_checkout": str(root), - "toolchain": metadata, "dependencies": dependencies, "recipe": recipe, + "toolchain": metadata, "mlx": mlx_pins, }) + dependency_hash = identity.digest({"version": SWIFT_CACHE_VERSION, "dependencies": dependencies}) + recipe_hash = identity.digest({"version": SWIFT_CACHE_VERSION, "recipe": recipe}) commit = tracked.git(root, "rev-parse", "HEAD").decode("ascii").strip() - prefix = f"provider-ci-swift-{CACHE_VERSION}-{LANE_PURPOSES[lane]}-{compatibility_hash}-" - result = {"swift-prefix": prefix, "swift-key": prefix + commit} + mlx_prefix = f"provider-ci-swift-{SWIFT_CACHE_VERSION}-{LANE_PURPOSES[lane]}-{mlx_hash}-" + loose_prefix = f"{mlx_prefix}{dependency_hash[:32]}-" + prefix = f"{loose_prefix}{recipe_hash[:32]}-" + result = {"swift-mlx-prefix": mlx_prefix, "swift-loose-prefix": loose_prefix, + "swift-prefix": prefix, "swift-key": prefix + commit} mlx_commit = sources.gitlinks.get(MLX_SOURCE) if mlx_commit is None: diff --git a/scripts/provider-ci-cold-retry.sh b/scripts/provider-ci-cold-retry.sh new file mode 100755 index 0000000000..2f50a2ce05 --- /dev/null +++ b/scripts/provider-ci-cold-retry.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# After a failed provider CI build: build once more from nothing only when the +# restored build came from the loose cache tier (another recipe, the same +# toolchain and dependencies). Exits 0 after deleting the restored builds, so +# the caller builds again; exits 1 when the failure is the build's own. +set -euo pipefail +matched=${PROVIDER_CI_MATCHED_KEY:-} +strict=${PROVIDER_CI_STRICT_PREFIX:?PROVIDER_CI_STRICT_PREFIX is required} +root=${GITHUB_WORKSPACE:?GITHUB_WORKSPACE is required} +case $matched in + "") + echo "The build failed without a restored cache entry; not building again." + exit 1 ;; + "$strict"*) + echo "The build failed over a cache entry of this recipe ($matched); not building again." + exit 1 ;; +esac +echo "::warning title=Build cache::The build failed over a cache entry of another recipe ($matched). Deleting the restored builds and building once from nothing." +rm -rf "$root/provider-swift/.build" "$root/libs/darkbloom-cluster/.build" diff --git a/scripts/provider-test-shards.py b/scripts/provider-test-shards.py index b137fcb9e4..285a262eb9 100755 --- a/scripts/provider-test-shards.py +++ b/scripts/provider-test-shards.py @@ -1,16 +1,20 @@ #!/usr/bin/env python3 -"""Split the provider Swift test suites into CI shards and check that every test ran. +"""Split the provider Swift test suites into CI selections and check that every test ran. +A selection is one serial `swift test` process. A CI job (a shard) runs +PROVIDER_TEST_PROCESSES selections at the same time (default 1: one selection +per job); job K of J runs selections (K-1)*P+1 .. K*P of N = J*P. The parallel class is the test targets whose dependency closure has no MLX or Metal (`PARALLEL_MODULES`); it runs in one process with Swift Testing's default -in-process parallelism. Every other suite stays serial (`--no-parallel`). -Prompt Parity runs in shard `PARITY_SHARD` against that shard's build; the -audit checks each parity run's executed count against the suite list. -Serial suites are assigned to shards by measured seconds -(`provider-test-shard-weights.json`, longest first onto the least loaded -shard). Shards 1..N-1 select their assigned suites with `--filter`; the last -shard skips the parallel class and every other shard's suites, so a suite that -is new or missing from the weights always runs there. +in-process parallelism, after selection 1. Every other suite stays serial +(`--no-parallel`). Prompt Parity runs in the job of selection `PARITY_SHARD` +against that job's build; the audit checks each parity run's executed count +against the suite list. Serial suites are assigned to selections by measured +seconds (`provider-test-shard-weights.json`, longest first onto the least +loaded selection). Selections 1..N-1 pick their assigned suites with +`--filter`; the last selection skips the parallel class and every other +selection's suites, so a suite that is new or missing from the weights always +runs there. Subcommands: args SHARD ISOLATED print the `swift test` selection for SHARD (`K/N` or @@ -20,8 +24,11 @@ write the executed test counts of one `swift test` run; SELECTION is `K/N` or `parallel` with the isolated pattern, or `parity` with the parity suite filter - audit LIST REPORTS check each shard executed exactly its planned tests and - that all shards together executed the full list + audit LIST REPORTS check each selection executed exactly its planned tests + and that all of them together executed the full list + audit-job LIST REPORTS K/N + the same for one CI job's own reports; job N also + checks that the plans cover the list once weights XUNIT... print measured seconds per suite from xUnit reports; suites they do not cover (SwiftPM writes no XCTest xUnit report for a serial run) keep their seconds in @@ -31,6 +38,7 @@ import argparse from collections import defaultdict import json +import os from pathlib import Path import re import sys @@ -47,10 +55,15 @@ ) # Prompt Parity's suites, run with their artifacts required (scripts/verify-*-parity.sh). PARITY_FILTERS = ("ProductionPromptParityTests", "NemotronTemplateParityLiveTests") +# CI runs Prompt Parity in the job that holds this selection: provider-tests.yml +# names that job (`matrix.shard == 1` with 3 processes), and +# test-provider-ci-workflow.py derives it from this value. PARITY_SHARD = 2 # Measured seconds of fixed work outside the assigned suites: the parallel -# process runs in shard 1, Prompt Parity in shard PARITY_SHARD, and the -# isolated processes and native gates in the last shard. +# process runs after selection 1, in its process; Prompt Parity runs after +# the processes of PARITY_SHARD's job, and the isolated processes and native +# gates after those of the last job, so their seconds load every selection +# of that job. FIRST_SHARD_EXTRA_SECONDS = 31.0 PARITY_SHARD_EXTRA_SECONDS = 65.0 LAST_SHARD_EXTRA_SECONDS = 190.0 @@ -70,16 +83,24 @@ def parse_shard(value): return int(match.group(1)), int(match.group(2)) -def assignment(shards, weights): - """Return each shard's serial suites and estimated seconds. +def assignment(shards, weights, processes=1): + """Return each selection's serial suites and estimated seconds. - The last shard's list only balances the load: that shard runs every serial - suite that shards 1..N-1 do not select. + `shards` is the number of selections, `processes` how many of them one job + runs at the same time. The last selection's list only balances the load: + that selection runs every serial suite that selections 1..N-1 do not pick. """ + if shards % processes: + raise ValueError(f"{shards} selections do not make jobs of {processes} processes") loads = [0.0] * shards loads[0] += FIRST_SHARD_EXTRA_SECONDS - loads[min(PARITY_SHARD, shards) - 1] += PARITY_SHARD_EXTRA_SECONDS - loads[-1] += LAST_SHARD_EXTRA_SECONDS + parity_job = (min(PARITY_SHARD, shards) - 1) // processes + last_job = (shards - 1) // processes + for index in range(shards): + if index // processes == parity_job: + loads[index] += PARITY_SHARD_EXTRA_SECONDS + if index // processes == last_job: + loads[index] += LAST_SHARD_EXTRA_SECONDS assigned = [[] for _ in range(shards)] serial = {key: seconds for key, seconds in weights.items() if key.split(".", 1)[0] not in PARALLEL_MODULES} @@ -111,12 +132,12 @@ def load_weights(): return weights -def selection(shard, isolated, weights): - """Return (filter regex or None, skip regex) for one shard.""" +def selection(shard, isolated, weights, processes=1): + """Return (filter regex or None, skip regex) for one selection.""" if shard == "parallel": return parallel_regex(), isolated index, shards = parse_shard(shard) - assigned, _ = assignment(shards, weights) + assigned, _ = assignment(shards, weights, processes) if index < shards: if not assigned[index - 1]: raise ValueError(f"Shard {shard} has no suites; use fewer shards") @@ -125,13 +146,13 @@ def selection(shard, isolated, weights): return None, "|".join([parallel_regex(), *others, isolated]) -def arguments(shard, isolated, weights): - selected, skipped = selection(shard, isolated, weights) +def arguments(shard, isolated, weights, processes=1): + selected, skipped = selection(shard, isolated, weights, processes) return (["--filter", selected] if selected else []) + ["--skip", skipped] -def planned(test_ids, shard, isolated, weights): - selected, skipped = selection(shard, isolated, weights) +def planned(test_ids, shard, isolated, weights, processes=1): + selected, skipped = selection(shard, isolated, weights, processes) return [test_id for test_id in test_ids if (selected is None or re.search(selected, test_id)) and not re.search(skipped, test_id)] @@ -167,8 +188,8 @@ def listed_tests(list_text): return sorted(line for line in lines if " " not in line and suite_key(line)) -def audit(test_ids, reports, isolated, weights): - """Return error lines; empty when every shard ran exactly its planned tests.""" +def audit(test_ids, reports, isolated, weights, processes=1): + """Return error lines; empty when every selection ran exactly its planned tests.""" errors = audit_parity(test_ids, [report for report in reports if report["shard"] == "parity"]) reports = [report for report in reports if report["shard"] != "parity"] expected = [test_id for test_id in test_ids if not re.search(isolated, test_id)] @@ -183,7 +204,7 @@ def audit(test_ids, reports, isolated, weights): executed = 0 seen = [] for report in sorted(reports, key=lambda report: report["shard"]): - plan = planned(test_ids, report["shard"], isolated, weights) + plan = planned(test_ids, report["shard"], isolated, weights, processes) seen.extend(plan) ran = report["swift_testing"] + report["xctest"] executed += ran @@ -203,6 +224,49 @@ def audit(test_ids, reports, isolated, weights): return errors +def audit_job(test_ids, reports, isolated, weights, job, jobs, processes): + """Return error lines for one CI job's own reports. + + Each job checks that every selection it ran executed exactly its planned + tests, and its Prompt Parity runs if it had any. The last job also checks + that the plans of all jobs together list every test once. With every job + required to pass, that is the full-suite audit without a job of its own. + """ + total = jobs * processes + first, last = (job - 1) * processes + 1, job * processes + expected = {"parallel"} if first == 1 else set() + expected |= {f"{index}/{total}" for index in range(first, last + 1)} + parity = [report for report in reports if report["shard"] == "parity"] + own = [report for report in reports if report["shard"] != "parity"] + errors = [] + if {report["shard"] for report in own} != expected or len(own) != len(expected): + errors.append(f"Expected one report per selection {sorted(expected)}, got {sorted(r['shard'] for r in own)}") + for report in own: + if report.get("processes", 1) != processes: + errors.append(f"Selection {report['shard']} was planned for {report.get('processes', 1)} processes, not {processes}") + plan = planned(test_ids, report["shard"], isolated, weights, processes) + ran = report["swift_testing"] + report["xctest"] + print(f"selection {report['shard']}: planned {len(plan)}, executed {ran}") + if ran != len(plan): + errors.append(f"Selection {report['shard']} executed {ran} tests but its plan lists {len(plan)}") + parity_job = (PARITY_SHARD - 1) // processes + 1 + if job == parity_job: + errors += audit_parity(test_ids, parity) + elif parity: + errors.append(f"Prompt Parity ran in job {job}, not job {parity_job}") + if job == jobs: + expected_tests = [test_id for test_id in test_ids if not re.search(isolated, test_id)] + seen = [test_id for selection in ("parallel", *(f"{index}/{total}" for index in range(1, total + 1))) + for test_id in planned(test_ids, selection, isolated, weights, processes)] + if len(seen) != len(set(seen)): + errors.append(f"{len(seen) - len(set(seen))} tests are planned in more than one selection") + if set(seen) != set(expected_tests): + errors.append(f"{len(set(expected_tests) - set(seen))} listed tests are in no selection") + print(f"all selections: plan {len(set(seen))} of {len(expected_tests)} listed tests " + f"({len(test_ids) - len(expected_tests)} more run in isolated processes)") + return errors + + def audit_parity(test_ids, reports): """Each Prompt Parity suite ran once, with every listed test of that suite.""" errors = [] @@ -219,8 +283,13 @@ def audit_parity(test_ids, reports): def measured_weights(paths, base=None): + """Seconds per suite from xUnit reports. A retried selection's first + attempt (attempt-1-shard-*.xml, run-provider-tests.sh) is not counted: its + second attempt's report measures the same suites.""" seconds = defaultdict(float) for path in paths: + if Path(path).name.startswith("attempt-1-"): + continue for case in ElementTree.parse(path).getroot().iter("testcase"): key = suite_key(case.get("classname", "")) if key: @@ -229,6 +298,14 @@ def measured_weights(paths, base=None): return dict(sorted({**(base or {}), **measured}.items())) +def processes_per_job(): + """PROVIDER_TEST_PROCESSES, the selections one job runs at the same time (default 1).""" + value = os.environ.get("PROVIDER_TEST_PROCESSES") or "1" + if not re.fullmatch(r"[1-9]", value): + raise ValueError(f"PROVIDER_TEST_PROCESSES must be 1 to 9, got {value!r}") + return int(value) + + def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) commands = parser.add_subparsers(dest="command", required=True) @@ -243,15 +320,20 @@ def main(): command = commands.add_parser("audit") command.add_argument("list", type=Path) command.add_argument("reports", type=Path) + command = commands.add_parser("audit-job") + command.add_argument("list", type=Path) + command.add_argument("reports", type=Path) + command.add_argument("job", help="K/N: this job and the job count") command = commands.add_parser("weights") command.add_argument("xunit", type=Path, nargs="+") args = parser.parse_args() if args.command == "args": - print("\n".join(arguments(args.shard, args.isolated, load_weights()))) + print("\n".join(arguments(args.shard, args.isolated, load_weights(), processes_per_job()))) elif args.command == "counts": if args.shard not in ("parallel", "parity"): parse_shard(args.shard) - report = {"shard": args.shard, "pattern": args.pattern, + # The report keeps the plan's process count, so the audit plans alike. + report = {"shard": args.shard, "pattern": args.pattern, "processes": processes_per_job(), **counts(args.log.read_text(errors="replace"), xctest_only=args.shard == "parity")} args.output.write_text(json.dumps(report)) elif args.command == "audit": @@ -260,7 +342,24 @@ def main(): if len(patterns) != 1: print(f"::error::Shard reports disagree on the isolated-process pattern: {sorted(patterns)}") return 1 - errors = audit(listed_tests(args.list.read_text()), reports, patterns.pop(), load_weights()) + processes = {report.get("processes", 1) for report in reports if report["shard"] != "parity"} + if len(processes) != 1: + print(f"::error::Shard reports disagree on the processes per job: {sorted(processes)}") + return 1 + errors = audit(listed_tests(args.list.read_text()), reports, patterns.pop(), load_weights(), + processes.pop()) + for error in errors: + print(f"::error::{error}") + return 1 if errors else 0 + elif args.command == "audit-job": + job, jobs = parse_shard(args.job) + reports = [json.loads(path.read_text()) for path in sorted(args.reports.glob("shard-*.json"))] + patterns = {report["pattern"] for report in reports if report["shard"] != "parity"} + if len(patterns) != 1: + print(f"::error::This job's reports disagree on the isolated-process pattern: {sorted(patterns)}") + return 1 + errors = audit_job(listed_tests(args.list.read_text()), reports, patterns.pop(), load_weights(), + job, jobs, processes_per_job()) for error in errors: print(f"::error::{error}") return 1 if errors else 0 diff --git a/scripts/run-provider-tests.sh b/scripts/run-provider-tests.sh index c08c4d22af..1ef621275a 100755 --- a/scripts/run-provider-tests.sh +++ b/scripts/run-provider-tests.sh @@ -39,37 +39,111 @@ isolated_pattern="ProcessMemoryNativeIntegrationTests|${isolated_pattern}" # MiMo native fixtures have their own explicit, bounded CI selections. # CI sets PROVIDER_TEST_SHARD=K/N (scripts/provider-test-shards.py chooses the # suites) and PROVIDER_TEST_REPORT_DIR for each run's log, xUnit report and -# executed counts. Shard 1 also runs the MLX-free test targets in one parallel -# process; the last shard also runs the isolated processes below. Without a -# shard, everything runs here as one serial suite. +# executed counts. Selection 1 also runs the MLX-free test targets in one +# parallel process; the last shard also runs the isolated processes below. +# Without a shard, everything runs here as one serial suite. +# +# PROVIDER_TEST_PROCESSES=P (default 1) makes job K of N run the P selections +# (K-1)*P+1 .. K*P of N*P at the same time, each serial in its own process with +# its own TMPDIR and provider state files. The isolated processes still run +# after all of them, alone. provider_test_shard=${PROVIDER_TEST_SHARD:-} +provider_test_processes=${PROVIDER_TEST_PROCESSES:-1} +# Processes of one job read the same build; SwiftPM's lock on .build would +# otherwise serialize them. With --skip-build none of them writes the build. +lock_flag=() run_provider_test_selection() { - local selection=$1 name=${1//\//-of-} arguments argument parallel_flag=(--no-parallel) status + local selection=$1 name=${1//\//-of-} arguments argument parallel_flag=(--no-parallel) status attempt local selected=() report="$PROVIDER_TEST_REPORT_DIR/shard-$name" arguments=$(python3 "$script_directory/provider-test-shards.py" args "$selection" "$isolated_pattern") || return 1 while IFS= read -r argument; do selected+=("$argument"); done <<<"$arguments" # The parallel class keeps Swift Testing's default in-process parallelism. [ "$selection" != parallel ] || parallel_flag=() echo "Provider test selection $name: ${#arguments} characters of filters" - env -u MIMO_V26_SERIAL_NATIVE_TESTS -u DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST -u DARKBLOOM_ISOLATED_DEADLINE_TEST \ - swift test --skip-build ${parallel_flag[@]+"${parallel_flag[@]}"} "${selected[@]}" \ - --xunit-output "$report.xml" 2>&1 | tee "$report.log" - status=${PIPESTATUS[0]} + # Beside other processes, SwiftPM can find the build database locked by + # another process's startup; it then runs the tests and exits 1. Such a + # selection runs once more, but only when its log proves every test passed + # (scripts/swift_test_lock_retry.py). The first attempt's log and xUnit + # report stay beside the second's, as attempt-1-shard-.*. + for attempt in 1 2; do + env -u MIMO_V26_SERIAL_NATIVE_TESTS -u DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST -u DARKBLOOM_ISOLATED_DEADLINE_TEST \ + swift test --skip-build ${lock_flag[@]+"${lock_flag[@]}"} ${parallel_flag[@]+"${parallel_flag[@]}"} "${selected[@]}" \ + --xunit-output "$report.xml" 2>&1 | tee "$report.log" + status=${PIPESTATUS[0]} + if [ "$status" = 0 ] || [ "$attempt" = 2 ] || [ "$provider_test_processes" = 1 ] || + ! python3 "$script_directory/swift_test_lock_retry.py" "$report.log"; then + break + fi + echo "Provider test selection $name: every test passed, but SwiftPM's build database was locked; running the selection once more" + mv "$report.log" "$PROVIDER_TEST_REPORT_DIR/attempt-1-shard-$name.log" + [ ! -f "$report.xml" ] || mv "$report.xml" "$PROVIDER_TEST_REPORT_DIR/attempt-1-shard-$name.xml" + done python3 "$script_directory/provider-test-shards.py" counts "$selection" "$isolated_pattern" "$report.log" "$report.json" || status=1 return "$status" } +# One process slot: a selection, and after selection 1 the parallel class. +run_provider_test_slot() { + local status=0 + run_provider_test_selection "$1" || status=$? + if [[ "$1" == 1/* ]]; then + run_provider_test_selection parallel || status=$? + fi + return "$status" +} +# A slot that runs beside others gets its own temporary directory and state +# files, in a subshell, so tests that write either never meet another +# process's files. +run_provider_test_slot_alone() ( + slot_root=$(mktemp -d "$provider_test_state_root/slot.XXXXXX") || exit 1 + mkdir -p "$slot_root/tmp" || exit 1 + export TMPDIR="$slot_root/tmp" + export DARKBLOOM_STATE_FILE="$slot_root/daemon-state.json" + export DARKBLOOM_LOADED_MODELS_FILE="$slot_root/loaded-models.json" + export DARKBLOOM_VERIFIED_WEIGHTS_FILE="$slot_root/verified-weights.json" + run_provider_test_slot "$1" +) if [ -z "$provider_test_shard" ]; then env -u MIMO_V26_SERIAL_NATIVE_TESTS -u DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST -u DARKBLOOM_ISOLATED_DEADLINE_TEST \ swift test --skip-build --no-parallel --skip "$isolated_pattern" || provider_test_status=$? else : "${PROVIDER_TEST_REPORT_DIR:?PROVIDER_TEST_SHARD needs PROVIDER_TEST_REPORT_DIR}" mkdir -p "$PROVIDER_TEST_REPORT_DIR" || exit 1 - run_provider_test_selection "$provider_test_shard" || provider_test_status=$? - if [[ "$provider_test_shard" == 1/* ]]; then - run_provider_test_selection parallel || provider_test_status=$? + # Read K and N before any other match replaces BASH_REMATCH. + job="" jobs="" + if [[ "$provider_test_shard" =~ ^([1-9][0-9]*)/([1-9][0-9]*)$ ]]; then + job=${BASH_REMATCH[1]} jobs=${BASH_REMATCH[2]} + fi + if [ -z "$job" ] || (( job > jobs )) || ! [[ "$provider_test_processes" =~ ^[1-9]$ ]]; then + echo "PROVIDER_TEST_SHARD must be K/N with 1 <= K <= N and PROVIDER_TEST_PROCESSES 1 to 9" >&2 + exit 2 + fi + if [ "$provider_test_processes" = 1 ]; then + run_provider_test_slot "$provider_test_shard" || provider_test_status=$? + else + lock_flag=(--ignore-lock) + selections_total=$((jobs * provider_test_processes)) + pids=() names=() + for ((slot = 1; slot <= provider_test_processes; slot++)); do + selection="$(((job - 1) * provider_test_processes + slot))/$selections_total" + name=${selection//\//-of-} + names+=("$name") + run_provider_test_slot_alone "$selection" > "$PROVIDER_TEST_REPORT_DIR/slot-$name.out" 2>&1 & + pids+=("$!") + # Start the processes apart, so their SwiftPM startups rarely meet on + # the build database. + (( slot == provider_test_processes )) || sleep "${PROVIDER_TEST_START_GAP:-15}" + done + for index in "${!pids[@]}"; do + status=0 + wait "${pids[$index]}" || status=$? + [ "$status" = 0 ] || provider_test_status=$status + echo "::group::Provider test selection ${names[$index]} (exit $status)" + cat "$PROVIDER_TEST_REPORT_DIR/slot-${names[$index]}.out" + echo "::endgroup::" + done fi - # Only the last shard (K == N) continues to the isolated processes. - if [ "${provider_test_shard%/*}" != "${provider_test_shard#*/}" ]; then + # Only the last job (K == N) continues to the isolated processes. + if [ "$job" != "$jobs" ]; then exit "$provider_test_status" fi fi diff --git a/scripts/swift_test_lock_retry.py b/scripts/swift_test_lock_retry.py new file mode 100644 index 0000000000..30b2686df8 --- /dev/null +++ b/scripts/swift_test_lock_retry.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Whether a failed `swift test` run failed only on SwiftPM's locked build database. + +Processes that share one build (`swift test --skip-build --ignore-lock`) can +start together. SwiftPM in one of them can then find the build database +locked by another's startup; it prints + + error: unable to attach DB: ... database is locked ... + +runs the tests anyway, and exits 1. Such a run may run once more, but only +when its log proves that every test it ran passed, so the exit status can +have no other cause: + +- the lock message is there; +- Swift Testing's summary says the run passed, and no line reports a failed + test, a failed run or an issue (`✘`); +- every XCTest summary has 0 failures, and no XCTest case failed; +- no `::error::` line (run-nested-suite.sh's tripwires) is there. + +Usage: swift_test_lock_retry.py LOG +Exit status 0: only the lock failed, run once more. 1: do not run again. +""" + +from pathlib import Path +import re +import sys + +LOCKED = re.compile(r"unable to attach DB: .*database is locked") +SWIFT_TESTING_PASSED = re.compile(r"Test run with \d+ tests?(?: in \d+ suites?)? passed after") +FAILED = re.compile(r"✘|Test run with .* failed|Test Case .* failed|^::error::", re.MULTILINE) +XCTEST_SUMMARY = re.compile(r"Executed \d+ tests?, with (?:\d+ tests? skipped and )?(\d+) failures? \((\d+) unexpected\)") + + +def only_locked(text): + """True when the log shows the lock message and nothing else that fails.""" + if not LOCKED.search(text) or not SWIFT_TESTING_PASSED.search(text) or FAILED.search(text): + return False + return all(failures == "0" and unexpected == "0" for failures, unexpected in XCTEST_SUMMARY.findall(text)) + + +def main(argv): + if len(argv) != 2: + print(__doc__.split("\n\n", 1)[0], file=sys.stderr) + return 2 + return 0 if only_locked(Path(argv[1]).read_text(errors="replace")) else 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index df454508b8..592d4439a5 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -5,6 +5,7 @@ import itertools import json import os +import re from pathlib import Path import subprocess import tempfile @@ -22,10 +23,18 @@ class ComponentPathsTests(unittest.TestCase): def test_only_same_workflow_pr_revisions_share_cancellation_group(self): - source = (ROOT / ".github/workflows/ci.yml").read_text() - concurrency = source.split("\nconcurrency:\n", 1)[1].split("\njobs:\n", 1)[0] - self.assertIn(" group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.run_id }}\n", concurrency) - self.assertIn(" cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n", concurrency) + # Pull request revisions cancel each other; every push has a group of + # its own (a push of a tested tree runs no test job, so none is skipped). + for filename in ("ci-dev.yml", "ci-master.yml"): + key = "github.event.pull_request.number || github.run_id" + with self.subTest(workflow=filename): + source = (ROOT / ".github/workflows" / filename).read_text() + concurrency = source.split("\nconcurrency:\n", 1)[1].split("\njobs:\n", 1)[0] + self.assertIn(" group: ${{ github.workflow }}-${{ github.event_name }}-${{ %s }}\n" % key, + concurrency) + self.assertIn(" cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n", concurrency) + # The shared test workflow takes its callers' concurrency. + self.assertNotIn("\nconcurrency:", (ROOT / ".github/workflows/provider-tests.yml").read_text()) def test_instructions_and_docs_never_select_expensive_lanes(self): paths = ["AGENTS.md", "docs/AGENTS.md", "docs/developer/test.md", @@ -47,20 +56,33 @@ def test_component_and_shared_dependency_matrix(self): "provider-swift/Sources/ProviderCoreFoundation/Manifest.swift": {"provider", "cluster"}, "provider-swift/Tests/ClusterOnboardingChecks/run.sh": {"provider", "cluster"}, "provider-swift/Tests/ProviderCoreTests/Inference/DistributedServeLoopTests.swift": {"provider"}, - "provider-swift/Package.swift": {"provider", "cluster"}, - "libs/mlx-swift-lm": {"provider", "sdk", "cluster"}, - "libs/mlx-swift-lm/Libraries/MLXLMCommon/Generate.swift": {"provider", "sdk", "cluster"}, - "libs/mlx-swift": {"provider", "sdk", "cluster"}, - "libs/mlx": {"provider", "cluster"}, + "provider-swift/Package.swift": {"provider", "cluster", "mimo_audio"}, + "provider-swift/Sources/ProviderCore/Inference/Engine/Factory/MiMo/MiMoV26ManagedMediaForwarding.swift": + {"provider", "mimo_audio"}, + "provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift": {"provider", "mimo_audio"}, + "scripts/prepare-mimo-audio-fixtures.py": {"provider", "mimo_audio"}, + # The audio fixture script runs this generator with --audio-source. + "scripts/prepare-mimo-provider-fixtures.py": {"provider", "mimo_audio"}, + "libs/mlx-swift-lm": {"provider", "cluster", "mimo_audio"}, + "libs/mlx-swift-lm/Libraries/MLXLMCommon/Generate.swift": {"provider", "cluster", "mimo_audio"}, + "libs/mlx-swift": {"provider", "cluster", "mimo_audio"}, + "libs/mlx": {"provider", "cluster", "mimo_audio"}, "libs/darkbloom-cluster/Package.swift": {"provider", "cluster"}, "libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh": {"provider", "cluster"}, "fixtures/prompt-contract/v1/corpus.json": {"provider"}, - ".github/actions/provider-ci-build/action.yml": {"provider", "sdk", "cluster"}, - ".github/workflows/ci.yml": {"provider", "sdk", "cluster"}, - "scripts/run-paged-kernel-tests.sh": {"provider", "sdk"}, + ".github/actions/provider-ci-build/action.yml": {"provider", "cluster"}, + ".github/workflows/provider-tests.yml": {"provider", "cluster", "mimo_audio"}, + ".github/workflows/ci-dev.yml": {"provider", "cluster", "mimo_audio"}, + ".github/workflows/provider-plan.yml": {"provider", "cluster", "mimo_audio"}, + "scripts/ci-tested-tree.py": {"provider", "cluster", "mimo_audio"}, + ".github/workflows/ci-master.yml": {"provider", "cluster", "mimo_audio"}, + "scripts/run-paged-kernel-tests.sh": {"provider"}, "scripts/run-provider-tests.sh": {"provider"}, + "scripts/provider-ci-cold-retry.sh": {"provider", "cluster"}, + "scripts/verified_download_cache.py": {"provider"}, "scripts/provider-test-shards.py": {"provider"}, "scripts/cluster-test-plan.py": {"provider", "cluster"}, + "scripts/swift_test_lock_retry.py": {"provider", "cluster"}, "coordinator/store/postgres/users.go": set(), "coordinator/protocol/messages.go": set(), "console-ui/package-lock.json": set(), @@ -74,12 +96,12 @@ def test_component_and_shared_dependency_matrix(self): self.assertEqual({name for name, value in routing.classify([path]).items() if value}, expected) for path in routing.COMMON: self.assertTrue(all(routing.classify([path]).values()), path) - # Every SDK-lane and cluster input is also a provider input. - for pattern in (*routing.SDK, *routing.CLUSTER): - path = pattern.replace("**", "x").replace("*", "Cluster") - self.assertTrue(routing.classify([path])[ - "sdk" if pattern in routing.SDK else "cluster"], path) - self.assertTrue(routing.classify([path])["provider"], path) + # Every cluster and MiMo audio input is also a provider input. + for component, patterns in (("cluster", routing.CLUSTER), ("mimo_audio", routing.MIMO_AUDIO)): + for pattern in patterns: + path = pattern.replace("**", "x").replace("*", "Cluster" if component == "cluster" else "MiMo") + self.assertTrue(routing.classify([path])[component], path) + self.assertTrue(routing.classify([path])["provider"], path) def test_swift_prompt_corpora_select_provider(self): for filename in ("nemotron-prompt-edge-corpus.json", "nemotron-reference-corpus.json"): @@ -185,7 +207,6 @@ def test_added_deleted_renamed_paths_and_nul_delimited_names(self): selected = self.pr(base, head) self.assertTrue(selected["provider"], "rename source must be considered") self.assertEqual(set(selected), set(routing.COMPONENTS)) - self.assertFalse(selected["sdk"], "provider sources are not SDK-lane inputs") base = head self.git("mv", "docs/moved.md", "provider-swift/new.swift") head = self.commit() @@ -215,21 +236,48 @@ def test_push_before_after_and_new_branch_and_manual(self): head = self.commit() event = {"before": self.base, "after": head, "ref": "refs/heads/topic"} self.assertFalse(any(self.run_detector("push", event).values())) - # A provider-only change: a pull request skips the cluster jobs, a - # push that runs the provider lanes runs them too. + # A provider-only change skips the cluster jobs, on a pull request and + # on a push alike. self.write("provider-swift/Sources/ProviderCore/Inference/Engine/EngineV2.swift") provider_only = self.commit() - self.assertEqual(self.pr(head, provider_only), {"provider": True, "sdk": False, "cluster": False}) - self.assertEqual(self.run_detector("push", {"before": head, "after": provider_only, "ref": "refs/heads/dev"}), - {"provider": True, "sdk": False, "cluster": True}) + self.assertEqual(self.pr(head, provider_only), + {"provider": True, "cluster": False, "mimo_audio": False}) + for ref in ("refs/heads/topic", "refs/heads/dev"): + self.assertEqual(self.run_detector("push", {"before": head, "after": provider_only, "ref": ref}), + {"provider": True, "cluster": False, "mimo_audio": False}) self.write("libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/New.swift") cluster = self.commit() - self.assertEqual(self.pr(provider_only, cluster), {"provider": True, "sdk": False, "cluster": True}) - for ref in ("refs/heads/master", "refs/heads/main"): - self.assertTrue(all(self.run_detector("push", {**event, "ref": ref}).values())) + self.assertEqual(self.pr(provider_only, cluster), + {"provider": True, "cluster": True, "mimo_audio": False}) + # The MiMo audio gate and its 1.87 GB codec run only for their inputs. + self.write("provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ManagedAudioProviderTests.swift") + audio = self.commit() + self.assertEqual(self.pr(cluster, audio), {"provider": True, "cluster": False, "mimo_audio": True}) + # A push to dev selects by its diff, as a pull request into dev does. + self.assertFalse(any(self.run_detector("push", {**event, "ref": "refs/heads/dev"}).values())) self.assertTrue(all(self.run_detector("push", {**event, "before": "0" * 40}).values())) self.assertTrue(all(self.run_detector("workflow_dispatch", {}).values())) + def test_master_pushes_and_pull_requests_into_master_select_every_component(self): + # Master is the release line: a docs-only change into master still + # runs every component, so a master record always covers them all. + self.write("landing/new.ts") + head = self.commit() + everything = dict.fromkeys(routing.COMPONENTS, True) + for ref in ("refs/heads/master", "refs/heads/main"): + with self.subTest(ref=ref): + self.assertEqual(self.run_detector("push", {"before": self.base, "after": head, "ref": ref}), + everything) + for branch in ("master", "main"): + with self.subTest(base=branch): + event = {"pull_request": {"base": {"sha": self.base, "ref": branch}, "head": {"sha": head}}} + self.assertEqual(self.run_detector("pull_request", event), everything) + # Into dev or a stacked branch, the diff decides. + for branch in ("dev", "ci/stacked"): + with self.subTest(base=branch): + event = {"pull_request": {"base": {"sha": self.base, "ref": branch}, "head": {"sha": head}}} + self.assertFalse(any(self.run_detector("pull_request", event).values())) + def test_missing_invalid_revisions_and_unsupported_events_fail_closed(self): for before in ("f" * 40, "--help", "", None): self.run_detector("push", {"before": before, "after": self.base}, success=False) @@ -238,8 +286,42 @@ def test_missing_invalid_revisions_and_unsupported_events_fail_closed(self): class WorkflowRoutingTests(unittest.TestCase): + def test_every_pull_request_runs_exactly_one_ci_workflow(self): + # CI (dev) runs for pull requests into any branch but master (dev and + # stacked branches); CI (master) for pull requests into master. The + # two filters are disjoint and cover every base. + def triggers(filename): + """The `on:` block as {event: {key: value}}, one level deep.""" + text = (ROOT / ".github/workflows" / filename).read_text() + block = text.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + events = {} + for line in block.splitlines(): + event = re.fullmatch(r" ([a-z_]+):(?: (.*))?", line) + option = re.fullmatch(r" ([a-z-]+): (.*)", line) + if event: + events[event.group(1)] = {} + elif option: + events[list(events)[-1]][option.group(1)] = option.group(2) + return events + + dev, master = triggers("ci-dev.yml"), triggers("ci-master.yml") + self.assertEqual(dev, {"push": {"branches": "[dev]"}, + "pull_request": {"branches-ignore": "[master, main]"}}) + self.assertEqual(master, {"push": {"branches": "[master, main]"}, + "pull_request": {"branches": "[master, main]"}}) + # Both run the same plan and tests, whatever the base (Release + # Integrity alone reads the base, for the branch's build default). + for filename in ("ci-dev.yml", "ci-master.yml"): + jobs = workflow.job_blocks((ROOT / ".github/workflows" / filename).read_text().split("\njobs:\n", 1)[1]) + with self.subTest(workflow=filename): + self.assertNotIn("github.base_ref", jobs["plan"] + jobs["tests"]) + self.assertIn(" uses: ./.github/workflows/provider-plan.yml\n", jobs["plan"]) + self.assertIn(" uses: ./.github/workflows/provider-tests.yml\n", jobs["tests"]) + self.assertIn(" needs: plan\n if: ${{ !cancelled() }}\n", jobs["tests"]) + def test_public_provider_workflows_have_no_backend_execution_or_private_access(self): - for filename in ("ci.yml", "component-changes.yml", "provider-release-cache.yml", + for filename in ("ci-dev.yml", "ci-master.yml", "provider-tests.yml", "component-changes.yml", + "provider-release-cache.yml", "provider-signing-validation.yml", "release-swift.yml", "release-provider.yml"): text = (ROOT / ".github/workflows" / filename).read_text() @@ -248,46 +330,66 @@ def test_public_provider_workflows_have_no_backend_execution_or_private_access(s "console-ui/", "e2e/", "install-release-rust.sh", "cargo "): self.assertNotIn(forbidden, text) self.assertNotRegex(text, r"(?m)^\s+repository:") - for filename in ("integration.yml", "benchmarks.yml", "telemetry-archive.yml"): + for filename in ("integration.yml", "benchmarks.yml", "telemetry-archive.yml", "ci.yml"): self.assertFalse((ROOT / ".github/workflows" / filename).exists()) - for filename in ("ci.yml", "provider-release-cache.yml", "component-changes.yml"): + for filename in ("ci-dev.yml", "ci-master.yml", "provider-tests.yml", "provider-release-cache.yml", + "component-changes.yml"): text = (ROOT / ".github/workflows" / filename).read_text() self.assertNotIn("secrets.", text) self.assertNotRegex(text, r"(?m)^\s+(environment:|id-token:|repository:)") def test_expensive_jobs_depend_on_successful_classifier(self): - expected = { - "ci.yml": {"test-provider": "provider", "test-cluster-checks": "cluster", "test-cluster": "cluster", - "test-cluster-focused": "cluster"}, - } - for name, lanes in expected.items(): - jobs = workflow.job_blocks((ROOT / ".github/workflows" / name).read_text()) - self.assertIn("uses: ./.github/workflows/component-changes.yml", jobs["changes"]) - self.assertIn("contents: read", jobs["changes"]) - # Runner routing follows the classifier, so only selected lanes are requested. - self.assertIn(" needs: changes\n", jobs["route"]) - for lane, component in lanes.items(): - self.assertIn(" needs: [changes, route]\n", jobs[lane]) - self.assertIn(" if: ${{ needs.changes.outputs." + component + " == 'true' }}\n", jobs[lane]) - self.assertNotIn("continue-on-error:", jobs[lane]) - ci = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) - # The GPU job's test step continues on error (scripts/test-cluster-test-plan.py). - self.assertIn(" needs: [changes, route]\n", ci["test-cluster-gpu"]) - self.assertIn(" if: ${{ needs.changes.outputs.cluster == 'true' }}\n", ci["test-cluster-gpu"]) - # The SDK lane runs on every push and on pull requests that change its inputs. - self.assertIn(" needs: [changes, route]\n", ci["test-provider-sdk"]) - self.assertIn(" if: ${{ github.event_name == 'push' || needs.changes.outputs.sdk == 'true' }}\n", - ci["test-provider-sdk"]) - self.assertNotIn("continue-on-error:", ci["test-provider-sdk"]) - # The summary runs after failed shards too, but only when the shards were selected. - self.assertIn(" needs: [changes, route, test-provider]\n", ci["test-provider-summary"]) - self.assertIn(" if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }}\n", - ci["test-provider-summary"]) - self.assertNotIn("continue-on-error:", ci["test-provider-summary"]) - for policy in ("release-integrity", "docs"): - self.assertNotIn(" if:", ci[policy]) - self.assertIn("python3 scripts/test-ci-component-paths.py", ci["release-integrity"]) + # The plan (provider-plan.yml) runs the classifier and the tree lookup, + # then routes only the lanes of the components it chose; the test jobs + # read those components as inputs, on pull requests and pushes alike. + plan = workflow.job_blocks((ROOT / ".github/workflows/provider-plan.yml").read_text().split("\njobs:\n", 1)[1]) + self.assertIn("uses: ./.github/workflows/component-changes.yml", plan["changes"]) + self.assertIn("contents: read", plan["changes"]) + self.assertIn(" needs: [changes, tested]\n", plan["components"]) + # The lookup needs the classifier's components: a record must cover them. + self.assertIn(" needs: changes\n if: ${{ !cancelled() && needs.changes.result == 'success' }}\n", + plan["tested"]) + self.assertIn(" SELECTED: provider=${{ needs.changes.outputs.provider }}," + "cluster=${{ needs.changes.outputs.cluster }}," + "mimo_audio=${{ needs.changes.outputs.mimo_audio }}\n", plan["tested"]) + self.assertIn(" needs: [components, tested]\n", plan["route"]) + for name in routing.COMPONENTS: + self.assertIn(f" {name}: ${{{{ steps.choose.outputs.{name} }}}}\n", plan["components"]) + ci = workflow.job_blocks((ROOT / ".github/workflows/provider-tests.yml").read_text().split("\njobs:\n", 1)[1]) + lanes = {"test-provider": "provider", "test-cluster": "cluster", "test-cluster-focused": "cluster", + "test-cluster-gpu": "cluster"} + for lane, component in lanes.items(): + with self.subTest(job=lane): + self.assertNotRegex(ci[lane], r"(?m)^ needs:") + self.assertIn(" if: ${{ inputs." + component + " == 'true' }}\n", ci[lane]) + if lane != "test-cluster-gpu": + self.assertNotIn("continue-on-error:", ci[lane]) + # Pull requests and pushes run the same jobs: only cache saving and the + # push-only refresh of a tested tree read the event. + for name, job in ci.items(): + if name != "refresh-caches": + self.assertNotIn("github.event_name", job, name) + self.assertNotIn("github.event_name", "".join(plan[name] for name in ("changes", "components"))) + # The lookup reads the event only to bind a record to its change. + self.assertEqual(plan["tested"].count("github.event_name"), 1) + self.assertIn(" EVENT: ${{ github.event_name }}\n", plan["tested"]) + # The Provider SDK Tests lane is gone (David, 2026-11-04): its suites run + # in the SDK's own Fork Tests. + self.assertNotIn("test-provider-sdk", ci) + self.assertNotIn("sdk", routing.COMPONENTS) + # No Mac job exists only to audit or to run the metadata runners. + self.assertNotIn("test-provider-summary", ci) + self.assertNotIn("test-cluster-checks", ci) self.assertNotIn("cache-swift", ci) + # Release Integrity and Docs Lint run for master only, after the plan + # whose route they read; nothing but cancellation skips them. + master = workflow.job_blocks((ROOT / ".github/workflows/ci-master.yml").read_text()) + for policy in ("release-integrity", "docs"): + self.assertIn(" needs: plan\n if: ${{ !cancelled() }}\n", master[policy]) + self.assertIn("python3 scripts/test-ci-component-paths.py", master["release-integrity"]) + dev = (ROOT / ".github/workflows/ci-dev.yml").read_text() + self.assertEqual(set(workflow.job_blocks(dev.split("\njobs:\n", 1)[1])), {"plan", "tests"}) + self.assertIn(" uses: ./.github/workflows/provider-tests.yml\n", dev) def test_detector_has_full_history_no_credentials_or_api_truncation(self): text = (ROOT / ".github/workflows/component-changes.yml").read_text() @@ -304,17 +406,17 @@ def test_detector_has_full_history_no_credentials_or_api_truncation(self): self.assertIn(name + ": ${{ steps.paths.outputs." + name + " }}", text) def test_provider_aggregate_exhaustive_truth_table(self): - jobs = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) + jobs = workflow.job_blocks((ROOT / ".github/workflows/provider-tests.yml").read_text()) gate = jobs["provider-test-gate"] - self.assertIn("needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused]", gate) + self.assertIn("needs: [test-provider, test-cluster, test-cluster-focused]", gate) self.assertNotIn("test-provider-sdk", gate) self.assertIn("if: ${{ always() }}", gate) self.assertNotIn("continue-on-error:", gate) step = workflow.step_blocks(gate)[0] for name, expression in { - "CHANGES_RESULT": "needs.changes.result", "PROVIDER_CHANGED": "needs.changes.outputs.provider", - "CLUSTER_CHANGED": "needs.changes.outputs.cluster", - "UNIT_RESULT": "needs.test-provider.result", "SUMMARY_RESULT": "needs.test-provider-summary.result", + "CHANGES_RESULT": "inputs.changes_result", "PROVIDER_CHANGED": "inputs.provider", + "CLUSTER_CHANGED": "inputs.cluster", "SKIP": "inputs.skip", "TESTED_RUN": "inputs.tested_run", + "UNIT_RESULT": "needs.test-provider.result", "CLUSTER_RESULT": "needs.test-cluster.result", "CLUSTER_FOCUSED_RESULT": "needs.test-cluster-focused.result", }.items(): @@ -323,7 +425,7 @@ def test_provider_aggregate_exhaustive_truth_table(self): results = ("success", "skipped", "failure", "cancelled") # Prompt Parity runs in a provider shard, so UNIT_RESULT carries it. self.assertNotIn("PARITY_RESULT", step) - names = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") + names = ("UNIT_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") selections = ("true", "false", "") def passes(selected, lanes): @@ -337,7 +439,7 @@ def passes(selected, lanes): "CLUSTER_CHANGED": cluster, **dict(zip(names, lanes))}) # A skipped cluster job passes only when the classifier did not # select the cluster jobs; a failed or cancelled one never passes. - expected = detector == "success" and passes(changed, lanes[:2]) and passes(cluster, lanes[2:]) + expected = detector == "success" and passes(changed, lanes[:1]) and passes(cluster, lanes[1:]) self.assertEqual(result.returncode == 0, expected, (detector, changed, cluster, *lanes)) diff --git a/scripts/test-ci-tested-tree.py b/scripts/test-ci-tested-tree.py new file mode 100755 index 0000000000..3aa2a3de2c --- /dev/null +++ b/scripts/test-ci-tested-tree.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""Offline checks of the tested-change lookup (scripts/ci-tested-tree.py); no network.""" + +import importlib.util +from pathlib import Path +import subprocess +import sys +import unittest +import urllib.error + +ROOT = Path(__file__).resolve().parent.parent +SPEC = importlib.util.spec_from_file_location("ci_tested_tree", ROOT / "scripts/ci-tested-tree.py") +lookup = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(lookup) + +REPO = "Layr-Labs/d-inference" +REF = f"{REPO}/.github/workflows/ci-dev.yml@refs/heads/dev" +TREE, OTHER = "a" * 40, "b" * 40 +BASE, HEAD, MERGE, ELSE = "1" * 40, "2" * 40, "3" * 40, "4" * 40 +ALL = {"provider": True, "cluster": True, "mimo_audio": True} +PROVIDER = {"provider": True, "cluster": False, "mimo_audio": False} + + +def run(run_id, **changes): + value = {"id": run_id, "status": "completed", "conclusion": "success", "path": ".github/workflows/ci-dev.yml", + "event": "pull_request", "head_sha": HEAD, "repository": {"full_name": REPO}, + "head_repository": {"full_name": REPO}, "html_url": f"https://github.com/{REPO}/actions/runs/{run_id}"} + value.update(changes) + return value + + +class Api: + """Answers the GET paths the lookup uses, and records them.""" + + def __init__(self, artifacts=(), runs=None, commits=None, fail=None): + self.artifacts, self.runs, self.fail, self.paths = list(artifacts), runs or {}, fail, [] + self.commits = commits if commits is not None else {MERGE: {"tree": {"sha": TREE}, + "parents": [{"sha": BASE}, {"sha": HEAD}]}} + + def __call__(self, path): + self.paths.append(path) + if self.fail: + raise self.fail + if "/actions/artifacts?name=" in path: + name = path.split("name=", 1)[1].split("&", 1)[0] + return {"artifacts": [artifact for artifact in self.artifacts if artifact["name"] == name]} + if "/git/commits/" in path: + return self.commits[path.rsplit("/", 1)[1]] + return self.runs[int(path.rsplit("/", 1)[1])] + + +def record(run_id, tree=TREE, base=BASE, head=HEAD, selected=None, **changes): + name = lookup.record_name(tree, base, head, selected or ALL) + return {"name": name, "expired": False, "workflow_run": {"id": run_id}, **changes} + + +class LookupTests(unittest.TestCase): + def push(self, api, selected=PROVIDER, commit=MERGE, tree=TREE): + return lookup.decide(REPO, REF, "push", commit, tree, "", "", selected, 99, get=api) + + def pull(self, api, selected=PROVIDER, base=BASE, head=HEAD, tree=TREE): + return lookup.decide(REPO, REF, "pull_request", MERGE, tree, base, head, selected, 99, get=api) + + def test_merge_push_skips_after_the_pull_request_run_of_the_same_change(self): + api = Api([record(7)], {7: run(7)}) + skip, url, note = self.push(api) + self.assertTrue(skip) + self.assertEqual(url, f"https://github.com/{REPO}/actions/runs/7") + self.assertIn("already passed", note) + + def test_a_different_tree_runs(self): + self.assertFalse(self.push(Api([record(7, tree=OTHER)], {7: run(7)}))[0]) + self.assertFalse(self.pull(Api([record(7, tree=OTHER)], {7: run(7)}))[0]) + + def test_lookup_failure_runs(self): + for failure in (urllib.error.URLError("down"), TimeoutError(), KeyError("GITHUB_TOKEN"), ValueError("bad")): + with self.subTest(failure=type(failure).__name__): + skip, url, note = self.push(Api(fail=failure)) + self.assertFalse(skip) + self.assertIn("lookup failed", note) + + def test_a_record_must_cover_every_component_this_run_selects(self): + provider_only = record(7, selected=PROVIDER) + # A provider-only record does not cover a full (master) run... + self.assertFalse(self.push(Api([provider_only], {7: run(7)}), selected=ALL)[0]) + # ...a full record covers a provider-only run, and a superset is found. + self.assertTrue(self.push(Api([record(7, selected=ALL)], {7: run(7)}), selected=PROVIDER)[0]) + self.assertTrue(self.push(Api([provider_only], {7: run(7)}), selected=PROVIDER)[0]) + partial = {"provider": True, "cluster": True, "mimo_audio": False} + self.assertFalse(self.push(Api([record(7, selected=partial)], {7: run(7)}), selected=ALL)[0]) + + def test_the_record_binds_to_the_merged_head_and_the_tested_base(self): + # The pushed merge commit merges HEAD into BASE; a record of another + # head, another base, or a run of another head proves nothing. + self.assertFalse(self.push(Api([record(7, head=ELSE)], {7: run(7, head_sha=ELSE)}))[0]) + self.assertFalse(self.push(Api([record(7, base=ELSE)], {7: run(7)}))[0]) + self.assertFalse(self.push(Api([record(7)], {7: run(7, head_sha=ELSE)}))[0]) + # A record a push run made is used only by a run of that same push. + pushed = record(7, base="push", head=MERGE) + self.assertTrue(self.push(Api([pushed], {7: run(7, event="push", head_sha=MERGE)}))[0]) + self.assertFalse(self.push(Api([pushed], {7: run(7, event="pull_request", head_sha=MERGE)}))[0]) + # A pushed commit whose tree is not the tree under test proves nothing. + commits = {MERGE: {"tree": {"sha": OTHER}, "parents": [{"sha": BASE}, {"sha": HEAD}]}} + self.assertFalse(self.push(Api([record(7)], {7: run(7)}, commits=commits))[0]) + # A direct push (one parent) can only match a run of itself. + commits = {MERGE: {"tree": {"sha": TREE}, "parents": [{"sha": BASE}]}} + self.assertFalse(self.push(Api([record(7)], {7: run(7)}, commits=commits))[0]) + # A pull request matches only its own base and head. + self.assertTrue(self.pull(Api([record(7)], {7: run(7)}))[0]) + self.assertFalse(self.pull(Api([record(7)], {7: run(7)}), base=ELSE)[0]) + + def test_unproven_runs_never_skip(self): + cases = { + "failed": run(7, conclusion="failure"), + "cancelled": run(7, conclusion="cancelled"), + "unfinished": run(7, status="in_progress", conclusion=None), + "another workflow": run(7, path=".github/workflows/ci-master.yml"), + "a fork's run": run(7, head_repository={"full_name": "someone/d-inference"}), + "another repository": run(7, repository={"full_name": "someone/d-inference"}), + } + for name, recorded in cases.items(): + with self.subTest(case=name): + self.assertFalse(self.push(Api([record(7)], {7: recorded}))[0]) + self.assertFalse(self.push(Api([record(7, expired=True)], {7: run(7)}))[0]) + self.assertFalse(self.push(Api([record(99)], {99: run(99)}))[0]) + api = Api([record(7), record(8)], {7: run(7, conclusion="failure"), 8: run(8)}) + self.assertEqual(self.push(api)[1], f"https://github.com/{REPO}/actions/runs/8") + + def test_inputs_are_validated_before_any_record_is_read(self): + for kwargs in ({"tree": "abc"}, {"commit": "A" * 40}): + with self.subTest(**kwargs): + api = Api([record(7)], {7: run(7)}) + self.assertFalse(self.push(api, **kwargs)[0]) + self.assertFalse(any("/artifacts" in path for path in api.paths)) + api = Api([record(7)], {7: run(7)}) + self.assertFalse(lookup.decide(REPO, f"{REPO}/ci.yml@main", "push", MERGE, TREE, "", "", PROVIDER, 99, + get=api)[0]) + self.assertEqual(api.paths, []) + self.assertFalse(lookup.decide(REPO, REF, "schedule", MERGE, TREE, "", "", PROVIDER, 99, get=api)[0]) + with self.assertRaises(ValueError): + lookup.components("provider=true,cluster=false") + # Nothing selected: nothing to skip, and no record is read. + api = Api([record(7)], {7: run(7)}) + none = dict.fromkeys(lookup.COMPONENTS, False) + self.assertFalse(self.push(api, selected=none)[0]) + self.assertEqual(api.paths, []) + + def test_the_gate_and_the_lookup_name_records_alike(self): + result = subprocess.run([sys.executable, str(ROOT / "scripts/ci-tested-tree.py"), "name", "--tree", TREE, + "--base", "push", "--head", MERGE, + "--components", "provider=true,cluster=false,mimo_audio=true"], + capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.strip(), f"ci-tested-{TREE}-push-{MERGE}-p1c0m1") + self.assertEqual(lookup.workflow_path(f"{REPO}/.github/workflows/ci-master.yml@refs/pull/12/merge", REPO), + ".github/workflows/ci-master.yml") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-cluster-test-plan.py b/scripts/test-cluster-test-plan.py index 0a24a8b209..3e3273cfd1 100755 --- a/scripts/test-cluster-test-plan.py +++ b/scripts/test-cluster-test-plan.py @@ -2,9 +2,12 @@ """Offline checks of the cluster test plan and the jobs that run it.""" import importlib.util +import io import os from pathlib import Path import re +import sys +import tempfile import unittest from unittest import mock @@ -27,7 +30,8 @@ def selected(selection, test_id): class ClusterTestPlanTests(unittest.TestCase): def setUp(self): - self.jobs = workflow.job_blocks(plan.WORKFLOW.read_text()) + self.jobs = {**workflow.job_blocks(plan.WORKFLOW.read_text()), + **workflow.job_blocks(workflow.PLAN_WORKFLOW.read_text().split("\njobs:\n", 1)[1])} def test_plan_names_every_gated_test_and_runner(self): self.assertEqual(plan.audit(), []) @@ -63,6 +67,10 @@ def test_every_selection_runs_through_the_zero_skip_wrapper_serially(self): self.assertEqual(cwd, plan.PACKAGE) self.assertEqual(argv[0], str(ROOT / "scripts/run-nested-suite.sh")) self.assertEqual(argv[-1], "--no-parallel") + # Only a grouped selection runs beside others on one build, + # so only it skips SwiftPM's lock on .build. + self.assertEqual("--ignore-lock" in argv, selection.group is not None) + self.assertEqual(argv[1], plan.swift_arguments(selection)[0]) else: self.assertEqual(cwd, ROOT) self.assertTrue(Path(argv[1]).is_file(), argv) @@ -75,13 +83,97 @@ def test_order_dependent_selections_keep_their_process_and_order(self): base = [selection for selection in plan.SELECTIONS if selection.base] self.assertEqual([(selection.name, selection.suites) for selection in base], [("base-batch-session", ("QwenTensorParallelBatchSessionTests",)), ("base", None)]) - # The share probe's 1.5 s budget includes the first use of the Qwen TP - # kernels on the Mac: it runs in the shard of qwen-tp-batch-gpu, after it. + # `base`, the longest selection, and then the share probe have shard 1 + # and its Mac to themselves, one process at a time. The probe times + # its share against a 1.5 s budget: it never shares a shard with the + # concurrent GPU groups (run 41973436945 failed it right after them). order = [selection.name for selection in plan.SELECTIONS] probe = next(selection for selection in plan.SELECTIONS if selection.name == "qwen-tp-share-probe-gpu") - batch = next(selection for selection in plan.SELECTIONS if selection.name == "qwen-tp-batch-gpu") - self.assertEqual((probe.lane, probe.shard), (batch.lane, batch.shard)) - self.assertGreater(order.index(probe.name), order.index(batch.name)) + base_selection = next(selection for selection in plan.SELECTIONS if selection.name == "base") + self.assertIsNone(base_selection.group) + self.assertIsNone(probe.group) + self.assertEqual([selection.name for selection in plan.SELECTIONS + if (selection.lane, selection.shard) == ("blocking", base_selection.shard)], + ["base", "qwen-tp-share-probe-gpu"]) + self.assertGreater(order.index(probe.name), order.index(base_selection.name)) + grouped_shards = {(selection.lane, selection.shard) for selection in plan.SELECTIONS + if selection.group is not None} + self.assertNotIn((probe.lane, probe.shard), grouped_shards) + # Groups exist only where the plan puts them: the focused and GPU lanes + # still run one selection at a time. + self.assertEqual({selection.lane for selection in plan.SELECTIONS if selection.group is not None}, + {"blocking"}) + + def test_a_shard_runs_its_groups_together_then_its_other_selections_alone(self): + marks = Path(self.enterContext(tempfile.TemporaryDirectory())) / "marks" + script = ("import os, sys, time; name = sys.argv[1]; path = sys.argv[2]\n" + "open(path, 'a').write(f'start {name} {time.monotonic()} {os.environ.get(\"TMPDIR\", \"-\")}\\n')\n" + "time.sleep(0.4)\n" + "open(path, 'a').write(f'end {name} {time.monotonic()}\\n')\n" + "sys.exit(3 if name == 'b2' else 0)\n") + selections = ( + plan.Selection("a1", "blocking", 1, group=1), plan.Selection("a2", "blocking", 1, group=1), + plan.Selection("b1", "blocking", 1, group=2), plan.Selection("b2", "blocking", 1, group=2), + plan.Selection("alone", "blocking", 1), plan.Selection("other-shard", "blocking", 2), + ) + command = lambda selection, output: (ROOT, [sys.executable, "-c", script, selection.name, str(marks)]) + with mock.patch.object(plan, "SELECTIONS", selections), mock.patch.object(plan, "command", command), \ + mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": ""}): + self.assertEqual(plan.run("blocking", 1), 1) + events = {} + for line in marks.read_text().splitlines(): + kind, name, moment, *rest = line.split() + events[(kind, name)] = float(moment) + if kind == "start": + events[("tmp", name)] = rest[0] if rest else None + names = ("a1", "a2", "b1", "b2", "alone") + self.assertEqual({name for kind, name in events if kind == "start"}, set(names)) + # Each group keeps its order; the two groups overlap. + self.assertLessEqual(events[("end", "a1")], events[("start", "a2")]) + self.assertLessEqual(events[("end", "b1")], events[("start", "b2")]) + self.assertLess(events[("start", "b1")], events[("end", "a1")]) + # Each group has its own TMPDIR; the alone selection starts after all of them. + self.assertEqual(events[("tmp", "a1")], events[("tmp", "a2")]) + self.assertNotEqual(events[("tmp", "a1")], events[("tmp", "b1")]) + self.assertGreaterEqual(events[("start", "alone")], max(events[("end", name)] for name in names[:4])) + + def test_a_grouped_selection_that_finds_the_build_database_locked_runs_once_more(self): + root = Path(self.enterContext(tempfile.TemporaryDirectory())) + # The first run of "locked-once" finds build.db locked, as SwiftPM + # reports it, passes its tests and exits 1; "locked" always does; + # "locked-failing" finds it locked and a test fails; "failing" fails. + script = ("import os, sys; name, root = sys.argv[1], sys.argv[2]\n" + "runs = os.path.join(root, name)\n" + "count = len(open(runs).read()) if os.path.exists(runs) else 0\n" + "open(runs, 'a').write('x')\n" + "locked = name in ('locked', 'locked-failing') or (name == 'locked-once' and count == 0)\n" + "if locked: print('error: unable to attach DB: error: accessing build database '\n" + " '\"/x/.build/build.db\": database is locked', flush=True)\n" + "print(f'run {count + 1}', flush=True)\n" + "if name == 'locked-failing': print('\u2718 Test run with 2 tests failed after 0.1 seconds.')\n" + "else: print('\u2714 Test run with 2 tests passed after 0.1 seconds.')\n" + "sys.exit(1 if locked or name == 'failing' else 0)\n") + selections = (plan.Selection("locked-once", "blocking", 1, group=1), + plan.Selection("locked", "blocking", 1, group=2), + plan.Selection("failing", "blocking", 1, group=3), + plan.Selection("locked-failing", "blocking", 1, group=4)) + command = lambda selection, output: (ROOT, [sys.executable, "-c", script, selection.name, str(root)]) + with mock.patch.object(plan, "SELECTIONS", selections), mock.patch.object(plan, "command", command), \ + mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": ""}), \ + mock.patch.object(sys, "stdout", io.TextIOWrapper(io.BytesIO(), write_through=True)) as stdout: + self.assertEqual(plan.run("blocking", 1), 1) + printed = stdout.buffer.getvalue().decode() + runs = {selection.name: len((root / selection.name).read_text()) for selection in selections} + self.assertEqual(runs, {"locked-once": 2, "locked": 2, "failing": 1, "locked-failing": 1}) + # The first attempt's log prints before the second's. + once = printed.split("::group::locked-once (group 1)", 1)[1].split("::endgroup::", 1)[0] + self.assertLess(once.index("Attempt 1's log"), once.index("run 1")) + self.assertLess(once.index("run 1"), once.index("Attempt 2's log")) + self.assertLess(once.index("Attempt 2's log"), once.index("run 2")) + # A selection alone has no other process to meet: no retry. + with mock.patch.object(plan, "command", command): + status, _ = plan.execute(plan.Selection("locked", "blocking", 1), root) + self.assertEqual((status, len((root / "locked").read_text())), (1, 3)) def test_each_process_has_only_its_own_switches(self): switches = {name: "1" for selection in plan.SELECTIONS for name in selection.environment} diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index fc13b6b139..374b21eb92 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -39,24 +39,10 @@ "warm": MACOS_FALLBACK, "docs": LINUX_FALLBACK} GRANTED = {"release-integrity": LINUX, "test-provider": MACOS, "warm": MACOS, "docs": LINUX_FALLBACK} -PROVIDER = "${{ needs.changes.outputs.provider == 'true' && 1 || 0 }}" -SDK = "${{ (github.event_name == 'push' || needs.changes.outputs.sdk == 'true') && 1 || 0 }}" -CLUSTER = "${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }}" PULL_REQUEST_WARM = "${{ github.event_name == 'pull_request' && 2 || 0 }}" # Every routed job: (profile, fallback label, count expression or None for 1) # of each lane it reads. ROUTED = { - "ci.yml": { - "release-integrity": ("linux_arm64", LINUX_FALLBACK, None), - "docs": ("linux_arm64", LINUX_FALLBACK, None), - "test-provider": ("macos_arm64", MACOS_FALLBACK, PROVIDER), - "test-provider-summary": ("macos_arm64", MACOS_FALLBACK, PROVIDER), - "test-provider-sdk": ("macos_arm64", MACOS_FALLBACK, SDK), - "test-cluster-checks": ("macos_arm64", MACOS_FALLBACK, CLUSTER), - "test-cluster": ("macos_arm64", MACOS_FALLBACK, CLUSTER), - "test-cluster-gpu": ("macos_arm64", MACOS_FALLBACK, CLUSTER), - "test-cluster-focused": ("macos_arm64", MACOS_FALLBACK, CLUSTER), - }, "docs-impact.yml": { "commit-signatures": ("linux_arm64", LINUX_FALLBACK, None), "docs-impact": ("linux_arm64", LINUX_FALLBACK, None), @@ -66,6 +52,35 @@ "nightly-linear-package.yml": {"test": ("linux_arm64", LINUX_FALLBACK, None)}, "provider-release-cache.yml": {"warm": ("macos_arm64", MACOS_FALLBACK, PULL_REQUEST_WARM)}, } +# CI: the callers run provider-plan.yml, whose route job is the run's only +# route request (the plane routes a run attempt once), with the caller's own +# Linux lanes. The test jobs (provider-tests.yml) read `inputs.routes`; CI +# (master)'s Release Integrity and Docs Lint read the plan's output. +CALLERS = ("ci-dev.yml", "ci-master.yml") +PLAN = "provider-plan.yml" +COMPONENT = "${{{{ needs.components.outputs.{} == 'true' && 1 || 0 }}}}" +REFRESH = ("${{ github.event_name == 'push' && needs.tested.outputs.skip == 'true' && " + "(needs.components.outputs.changed_provider == 'true' || needs.components.outputs.changed_cluster == 'true') " + "&& 1 || 0 }}") +PLAN_LANES = { + "test-cluster-1": COMPONENT.format("cluster"), "test-provider-1": COMPONENT.format("provider"), + "test-provider-2": COMPONENT.format("provider"), "test-cluster-2": COMPONENT.format("cluster"), + "test-cluster-focused": COMPONENT.format("cluster"), "test-cluster-gpu-1": COMPONENT.format("cluster"), + "test-cluster-gpu-2": COMPONENT.format("cluster"), "refresh-caches": REFRESH, +} +MASTER_LINUX_LANES = (f"release-integrity linux_arm64 {LINUX_FALLBACK}", f"docs linux_arm64 {LINUX_FALLBACK}") +# (workflow, job): the expression its runs-on reads. +CI_ROUTED = { + ("provider-tests.yml", "test-provider"): "inputs.routes", ("provider-tests.yml", "test-cluster"): "inputs.routes", + ("provider-tests.yml", "test-cluster-gpu"): "inputs.routes", + ("provider-tests.yml", "test-cluster-focused"): "inputs.routes", + ("provider-tests.yml", "refresh-caches"): "inputs.routes", + ("ci-master.yml", "release-integrity"): "needs.plan.outputs.routes", + ("ci-master.yml", "docs"): "needs.plan.outputs.routes", +} +# darkbloom-sandbox's GitHub-side watchdog (public/darkbloom-actions +# .github/workflows/watchdog.yml at 31236c54), copied unchanged. +WATCHDOG = "darkbloom-watchdog.yml" # Credentialed, release, review or publication workflows keep literal runners. UNROUTED = ("release-swift.yml", "release-provider.yml", "release-dev-branch.yml", "release-desktop.yml", "provider-signing-validation.yml", "register-model.yml", @@ -153,8 +168,12 @@ def lane_lines(route_job): def route_lanes(route_job): """Parse the caller's `lanes` lines into {lane: (profile, fallback, count)}.""" + return route_lanes_text(lane_lines(route_job)) + + +def route_lanes_text(lines): lanes = {} - for line in lane_lines(route_job): + for line in lines: lane, profile, fallback, *count = line.split(maxsplit=3) lanes[lane] = (profile, fallback, count[0] if count else None) return lanes @@ -257,7 +276,8 @@ def route(self, plane_url, routing="on", lanes=LANES, trust=True, **context): if routing == "on" and not plane_url: raise AssertionError("Tests must never fall through to the production plane") variables = dict(LANES=lanes, ROUTING=routing, PLANE_URL=plane_url, REPOSITORY="Layr-Labs/d-inference", - EVENT_NAME="push", HEAD_REPOSITORY="", RUN_ID="40408691758", RUN_ATTEMPT="2") + EVENT_NAME="push", HEAD_REPOSITORY="", RUN_ID="40408691758", RUN_ATTEMPT="2", + MACOS_LANES="") variables.update(context) if trust: variables["CURL_CA_BUNDLE"] = str(self.certificate) @@ -409,6 +429,36 @@ def test_pull_requests_from_forks_never_contact_the_plane(self): self.assertRoutes(result, routes, GRANTED) self.assertEqual(len(plane.requests), 1) + def test_macos_lane_cap_keeps_lanes_in_order_and_asks_for_none_past_it(self): + # LANES asks for test-provider (1 macOS job), then warm (2 macOS jobs). + none = {**GRANTED, "test-provider": MACOS_FALLBACK, "warm": MACOS_FALLBACK} + cases = {"": (["release-integrity", "test-provider", "warm"], GRANTED), + "3": (["release-integrity", "test-provider", "warm"], GRANTED), + "2": (["release-integrity", "test-provider"], {**GRANTED, "warm": MACOS_FALLBACK}), + "1": (["release-integrity", "test-provider"], {**GRANTED, "warm": MACOS_FALLBACK}), + "0": (["release-integrity"], none), + # A malformed cap is a repository setting: it asks for no + # macOS lane and never fails the route job. + "two": (["release-integrity"], none), "-1": (["release-integrity"], none), + "100": (["release-integrity"], none)} + for value, (requested, expected) in cases.items(): + with self.subTest(cap=value), self.plane() as plane: + result, routes, summary = self.route(plane.url, MACOS_LANES=value) + self.assertRoutes(result, routes, expected) + request, = plane.requests + self.assertEqual([lane["lane"] for lane in json.loads(request["body"])["lanes"]], requested) + if expected["warm"] == MACOS_FALLBACK: + self.assertIn("| `warm` | macos_arm64 | 2 | `blacksmith-12vcpu-macos-27` | fallback: over the " + "macOS lane cap (DARKBLOOM_MACOS_LANES) |", summary) + if value in ("two", "-1", "100"): + self.assertIn("DARKBLOOM_MACOS_LANES is not a number from 0 to 99", summary) + # Routing off still names its own reason, and capped lanes never reach a plane. + with self.plane() as plane: + result, routes, summary = self.route(plane.url, routing="off", MACOS_LANES="0") + self.assertRoutes(result, routes) + self.assertIn("fallback: routing is off |", summary) + self.assertEqual(plane.requests, []) + def test_lanes_without_jobs_or_run_identity_send_nothing(self): with self.plane() as plane: result, routes, summary = self.route(plane.url, lanes=f"docs linux_arm64 {LINUX_FALLBACK} 0\n") @@ -456,8 +506,8 @@ def setUp(self): self.texts = {path.name: path.read_text() for path in WORKFLOWS.glob("*.yml")} def test_every_workflow_is_classified(self): - self.assertEqual(set(self.texts), set(ROUTED) | set(UNROUTED) | - {"darkbloom-route.yml", "component-changes.yml"}) + self.assertEqual(set(self.texts), set(ROUTED) | set(UNROUTED) | set(CALLERS) | + {"darkbloom-route.yml", "component-changes.yml", PLAN, "provider-tests.yml", WATCHDOG}) def test_router_is_isolated_and_defaults_to_the_sandbox_plane(self): text = self.texts["darkbloom-route.yml"] @@ -475,6 +525,7 @@ def test_router_is_isolated_and_defaults_to_the_sandbox_plane(self): self.assertIn("value: ${{ jobs.select.outputs.routes }}", header) self.assertIn(" routes: ${{ steps.route.outputs.routes }}\n", select) for name, expression in {"LANES": "inputs.lanes", "ROUTING": "vars.DARKBLOOM_ROUTING", + "MACOS_LANES": "vars.DARKBLOOM_MACOS_LANES", "PLANE_URL": "vars.DARKBLOOM_SANDBOX_URL", "REPOSITORY": "github.repository", "EVENT_NAME": "github.event_name", "HEAD_REPOSITORY": "github.event.pull_request.head.repo.full_name", @@ -564,6 +615,75 @@ def test_router_accepts_every_caller_configuration(self): self.assertEqual(routes, [{lane: fallback for lane, (_, fallback, _) in requested_lanes(workflow, ROUTED[filename]).items()}]) + def test_ci_routes_every_job_that_runs_code_through_one_plan(self): + plan = jobs(self.texts[PLAN]) + route = plan["route"] + self.assertIn(" uses: ./.github/workflows/darkbloom-route.yml\n", route) + self.assertEqual(job_field(route, "permissions"), "{}") + self.assertEqual(lane_lines(route)[0], "${{ inputs.linux_lanes }}") + planned = {lane: (profile, fallback, count) for lane, (profile, fallback, count) + in route_lanes_text(lane_lines(route)[1:]).items()} + self.assertEqual({lane: count for lane, (_, _, count) in planned.items()}, PLAN_LANES) + self.assertEqual(list(planned), list(PLAN_LANES)) + self.assertTrue(all(profile == "macos_arm64" and fallback == MACOS_FALLBACK + for profile, fallback, _ in planned.values())) + # The callers: CI (dev) adds no lane; CI (master) adds its Linux lanes. + for filename in CALLERS: + workflow = jobs(self.texts[filename]) + with self.subTest(workflow=filename): + self.assertEqual(job_field(workflow["plan"], "uses"), f"./.github/workflows/{PLAN}") + self.assertEqual(job_field(workflow["tests"], "uses"), "./.github/workflows/provider-tests.yml") + self.assertEqual(needs(workflow["tests"]), ["plan"]) + self.assertNotIn("darkbloom-route.yml", self.texts[filename]) + self.assertEqual(set(jobs(self.texts["ci-dev.yml"])), {"plan", "tests"}) + self.assertNotIn("linux_lanes", self.texts["ci-dev.yml"]) + self.assertEqual(set(jobs(self.texts["ci-master.yml"])), {"plan", "tests", "release-integrity", "docs"}) + self.assertEqual(literal_block(jobs(self.texts["ci-master.yml"])["plan"], "linux_lanes", 6).splitlines(), + list(MASTER_LINUX_LANES)) + # Every routed job reads its own lane (each shard its own), and every + # lane is read: no job hard-codes a Blacksmith label. + read = set() + for (filename, name), source in CI_ROUTED.items(): + job = jobs(self.texts[filename])[name] + with self.subTest(workflow=filename, job=name): + if name in SHARDED: + lane = f"format('{name}-{{0}}', matrix.shard)" + read |= {f"{name}-{shard}" for shard in matrix_shards(job)} + else: + lane = f"'{name}'" + read.add(name) + self.assertEqual(job_field(job, "runs-on"), f"${{{{ fromJSON({source})[{lane}] }}}}") + # A lane is requested exactly when its job runs. + condition = job_field(job, "if") + if name.startswith("test-"): + component = re.fullmatch(r"\$\{\{ inputs\.(\w+) == 'true' \}\}", condition).group(1) + for each in ([f"{name}-{shard}" for shard in matrix_shards(job)] if name in SHARDED else [name]): + self.assertEqual(PLAN_LANES[each], COMPONENT.format(component)) + self.assertEqual(read, set(PLAN_LANES) | {line.split()[0] for line in MASTER_LINUX_LANES}) + # The router accepts both callers' lane sets, with every count either way. + script = route_step() + for linux in ("", "\n".join(MASTER_LINUX_LANES)): + text = "\n".join([linux, *lane_lines(route)[1:]]) + "\n" + for outcome in ("1", "0"): + lanes = re.sub(r"\$\{\{ .+? && (\d+) \|\| 0 \}\}", + lambda match: match.group(1) if outcome == "1" else "0", text) + with self.subTest(linux=bool(linux), requested=outcome), tempfile.TemporaryDirectory() as work: + result, routes, _ = run_route_step( + script, Path(work), LANES=lanes, ROUTING="", PLANE_URL="", EVENT_NAME="push", + HEAD_REPOSITORY="", REPOSITORY="Layr-Labs/d-inference", RUN_ID="1", RUN_ATTEMPT="1") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + expected = {lane: MACOS_FALLBACK for lane in PLAN_LANES} + expected.update({line.split()[0]: LINUX_FALLBACK for line in linux.splitlines()}) + self.assertEqual(routes, [expected]) + for filename in ("provider-tests.yml", "ci-dev.yml", "ci-master.yml", PLAN): + for name, job in jobs(self.texts[filename]).items(): + runner = job_field(job, "runs-on") + if runner and "fromJSON(" not in runner: + with self.subTest(workflow=filename, job=name): + # Only bookkeeping without tests stays GitHub-hosted. + self.assertEqual(runner, "ubuntu-24.04") + self.assertIn(name, ("tested", "components", "provider-test-gate")) + def test_release_and_credentialed_workflows_keep_literal_runners(self): for filename in UNROUTED: text = self.texts[filename] @@ -573,7 +693,8 @@ def test_release_and_credentialed_workflows_keep_literal_runners(self): for runner in re.findall(r"(?m)^\s+runs-on: (.+)$", text): self.assertRegex(runner, r"^blacksmith-[a-z0-9-]+$") for filename, text in self.texts.items(): - if filename != "darkbloom-route.yml": + # The watchdog names the labels it looks for; it routes nothing. + if filename not in ("darkbloom-route.yml", WATCHDOG): with self.subTest(workflow=filename): for label in ("self-hosted", "darkbloom-linux-arm64", "darkbloom-macos-arm64"): self.assertNotIn(label, text) @@ -584,15 +705,44 @@ def test_release_and_credentialed_workflows_keep_literal_runners(self): with self.subTest(workflow=filename, job=name): self.assertRegex(job_field(job, "runs-on"), r"^(blacksmith-[a-z0-9-]+|ubuntu-24\.04)$") + def test_watchdog_rescues_only_this_repositorys_routed_runs(self): + text = self.texts[WATCHDOG] + header, body = text.split("\njobs:\n", 1) + # Scheduled and on demand only; no token permission at the top. + self.assertEqual(re.findall(r"(?m)^ ([a-z_]+):$", header.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]), + ["schedule", "workflow_dispatch"]) + self.assertIn("\npermissions: {}\n", header) + watch, = jobs(text).values() + self.assertEqual(job_field(watch, "runs-on"), "ubuntu-24.04") + # Cancel and re-run, read and write its marker: on this repository only. + self.assertEqual(permissions(watch, 4), {"actions": "write", "checks": "write"}) + self.assertIn('"${api%/}/repos/$REPOSITORY/$path"', body) + self.assertIn("REPOSITORY: ${{ github.repository }}", body) + for forbidden in ("uses:", "secrets.", "checkout", "id-token", "contents:"): + self.assertNotIn(forbidden, body) + # It acts only on runs with a queued Darkbloom-labelled job, and the + # release, signing and credentialed workflows never carry one. + self.assertIn('index("self-hosted") != null and any(.[]; startswith("darkbloom-"))', body) + for filename in UNROUTED: + for runner in re.findall(r"(?m)^\s+runs-on: (.+)$", self.texts[filename]): + self.assertNotIn("darkbloom", runner, filename) + self.assertNotIn("self-hosted", self.texts[filename], filename) + # The route job it re-runs is CI's: provider-plan.yml's, called as + # `plan / route / Select Runners`, which it matches by suffix. + self.assertIn('route_job=${ROUTE_JOB:-Select Runners}', body) + self.assertIn('(.name | endswith(" / " + $name))', body) + self.assertIn(" name: Select Runners\n", jobs(self.texts["darkbloom-route.yml"])["select"]) + def test_classifier_gate_and_route_need_no_routed_runner(self): - ci = jobs(self.texts["ci.yml"]) - self.assertEqual(needs(ci["route"]), ["changes"]) - self.assertEqual(job_field(ci["route"], "if"), "${{ !cancelled() }}") + ci = jobs(self.texts["provider-tests.yml"]) + plan = jobs(self.texts[PLAN]) + self.assertEqual(needs(plan["route"]), ["components", "tested"]) + self.assertEqual(job_field(plan["route"], "if"), "${{ !cancelled() }}") self.assertEqual(job_field(ci["provider-test-gate"], "runs-on"), "ubuntu-24.04") self.assertNotIn("route", needs(ci["provider-test-gate"])) changes = jobs(self.texts["component-changes.yml"])["changes"] self.assertEqual(job_field(changes, "runs-on"), "ubuntu-24.04") - self.assertIn("python3 scripts/test-darkbloom-route.py", ci["release-integrity"]) + self.assertIn("python3 scripts/test-darkbloom-route.py", jobs(self.texts["ci-master.yml"])["release-integrity"]) self.assertEqual(permissions(self.texts["docs-impact.yml"].split("\njobs:\n", 1)[0], 0), {"contents": "read"}) diff --git a/scripts/test-native-gpu-ci.py b/scripts/test-native-gpu-ci.py index 0d344788b4..959ca2da1d 100644 --- a/scripts/test-native-gpu-ci.py +++ b/scripts/test-native-gpu-ci.py @@ -203,10 +203,11 @@ def test_exclusive_helper_rejects_broad_or_extra_selectors_before_swift(self): self.assertEqual(calls, []) def test_workflow_keeps_checked_entrypoints(self): - workflow = (ROOT / '.github/workflows/ci.yml').read_text() + # The test jobs, then CI (master)'s Release Integrity, which runs this file. + workflow = ((ROOT / '.github/workflows/provider-tests.yml').read_text() + + (ROOT / '.github/workflows/ci-master.yml').read_text()) self.assertIn('python3 ../scripts/run-provider-test-watchdog.py', workflow) self.assertIn('-- ../scripts/run-provider-tests.sh', workflow) - self.assertIn('run: ../../scripts/run-paged-kernel-tests.sh', workflow) self.assertIn('run: python3 scripts/test-native-gpu-ci.py', workflow) diff --git a/scripts/test-prepare-mimo-image-http-fixtures.py b/scripts/test-prepare-mimo-image-http-fixtures.py index 81d77f6f61..bc7de7bf12 100644 --- a/scripts/test-prepare-mimo-image-http-fixtures.py +++ b/scripts/test-prepare-mimo-image-http-fixtures.py @@ -1,10 +1,12 @@ #!/usr/bin/env python3 """CPU checks for metadata authentication and actual deterministic PNG pixels.""" +import hashlib import importlib.util from pathlib import Path import struct import tempfile import unittest +from unittest import mock import zlib SPEC = importlib.util.spec_from_file_location( @@ -35,6 +37,29 @@ def test_real_pixels_and_chunk_integrity(self): self.assertEqual(position, len(data)) self.assertNotEqual(F.png((255, 0, 0)), F.png((0, 0, 255))) + def test_cached_metadata_is_used_only_when_its_bytes_match_the_pin(self): + payloads = {name: f"{name} fixture\n".encode() for name in F.NAMES} + pins = {name: (len(data), hashlib.sha256(data).hexdigest()) for name, data in payloads.items()} + calls = [] + def fetch(name): + calls.append(name) + return payloads[name] + with tempfile.TemporaryDirectory() as root, mock.patch.dict(F.PINS.FILES, pins): + cache = Path(root) / "cache" + cached = F.cached(fetch, cache, lambda name: F.PINS.FILES[name][1]) + F.prepare(Path(root) / "first", fetch=cached) + F.prepare(Path(root) / "second", fetch=cached) + self.assertEqual(calls, list(F.NAMES)) + # A corrupted entry is fetched again; a wrong download is refused and not kept. + (cache / pins[F.NAMES[0]][1]).write_bytes(b"corrupted") + F.prepare(Path(root) / "third", fetch=cached) + self.assertEqual(calls, [*F.NAMES, F.NAMES[0]]) + empty = Path(root) / "empty" + with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): + F.prepare(Path(root) / "fourth", fetch=F.cached(lambda name: b"corrupt", empty, + lambda name: F.PINS.FILES[name][1])) + self.assertFalse(empty.exists()) + def test_corrupt_metadata_refuses(self): with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): diff --git a/scripts/test-prepare-mimo-prompt-fixtures.py b/scripts/test-prepare-mimo-prompt-fixtures.py index c569d39556..8f2e6b7c5f 100644 --- a/scripts/test-prepare-mimo-prompt-fixtures.py +++ b/scripts/test-prepare-mimo-prompt-fixtures.py @@ -40,6 +40,33 @@ def download(name): self.assertFalse((result / name).is_symlink()) self.assertEqual((result / name).stat().st_mode & 0o777, 0o600) + def test_cache_serves_only_verified_bytes_and_keeps_only_verified_downloads(self): + cache = self.root / "cache" + calls = [] + def download(name): + calls.append(name) + return self.payloads[name] + fetch = SETUP.cached(download, cache, SETUP.PINS.__getitem__) + first = SETUP.prepare(self.root / "first", self.corpus, fetch) + self.assertEqual(calls, list(self.payloads)) + self.assertEqual(sorted(path.name for path in cache.iterdir()), sorted(SETUP.PINS.values())) + # A second run reads every file from the cache. + second = SETUP.prepare(self.root / "second", self.corpus, fetch) + self.assertEqual(calls, list(self.payloads)) + for name in self.payloads: + self.assertEqual((second / name).read_bytes(), (first / name).read_bytes()) + # A corrupted entry is fetched again and replaced. + name = next(iter(self.payloads)) + (cache / SETUP.PINS[name]).write_bytes(b"corrupted") + SETUP.prepare(self.root / "third", self.corpus, fetch) + self.assertEqual(calls, [*self.payloads, name]) + self.assertEqual((cache / SETUP.PINS[name]).read_bytes(), self.payloads[name]) + # A download with the wrong bytes is refused and never cached. + empty = self.root / "empty-cache" + with self.assertRaises(ValueError): + SETUP.prepare(self.root / "fourth", self.corpus, SETUP.cached(lambda _: b"wrong", empty, SETUP.PINS.__getitem__)) + self.assertFalse(empty.exists()) + def test_wrong_download_hash_is_rejected(self): with self.assertRaises(ValueError): SETUP.prepare(self.root / "metadata", self.corpus, lambda _: b"wrong") diff --git a/scripts/test-prepare-mimo-provider-fixtures.py b/scripts/test-prepare-mimo-provider-fixtures.py index b7f622b1d0..fd14a1a0bf 100644 --- a/scripts/test-prepare-mimo-provider-fixtures.py +++ b/scripts/test-prepare-mimo-provider-fixtures.py @@ -110,8 +110,8 @@ def test_cli_exports_only_fixture_path_not_native_opt_ins(self): self.assertEqual(env_file.read_text(), expected) def test_provider_job_provisions_prompt_and_tiny_inputs_before_tests(self): - workflow = (ROOT / ".github/workflows/ci.yml").read_text().split(" test-provider:", 1)[1] - workflow = workflow.split(" test-provider-sdk:", 1)[0] + workflow = (ROOT / ".github/workflows/provider-tests.yml").read_text().split(" test-provider:", 1)[1] + workflow = workflow.split(" test-cluster:", 1)[0] run = workflow.index("-- ../scripts/run-provider-tests.sh") for command in ("scripts/prepare-mimo-prompt-fixtures.py", "scripts/prepare-mimo-provider-fixtures.py"): self.assertLess(workflow.index(command), run) diff --git a/scripts/test-provider-build-default.py b/scripts/test-provider-build-default.py index 8309c3e628..4fcdda45f8 100644 --- a/scripts/test-provider-build-default.py +++ b/scripts/test-provider-build-default.py @@ -79,9 +79,12 @@ def test_command_exit_status_and_message(self): self.assertIn("provider-build-default:", missing.stderr) def test_ci_checks_the_target_branch_in_release_integrity(self): - ci = (ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8") + # Release Integrity runs only in CI (master) (David, 2026-11-04). + ci = (ROOT / ".github/workflows/ci-master.yml").read_text(encoding="utf-8") job = re.search(r"(?ms)^ release-integrity:\n(.*?)(?=^ [a-z][a-z0-9_-]*:\n)", ci).group(1) - self.assertNotIn("\n if:", job) + # Nothing but cancellation skips it: it waits only for the plan whose + # route it reads. + self.assertEqual(re.findall(r"(?m)^ if: (.+)$", job), ["${{ !cancelled() }}"]) self.assertIn("TARGET_BRANCH: ${{ github.base_ref || github.ref_name }}", job) self.assertIn("python3 scripts/test-provider-build-default.py", job) self.assertIn('python3 scripts/provider-build-default.py --branch "$TARGET_BRANCH"', job) diff --git a/scripts/test-provider-ci-cache.py b/scripts/test-provider-ci-cache.py index a51f344339..c6f0289879 100644 --- a/scripts/test-provider-ci-cache.py +++ b/scripts/test-provider-ci-cache.py @@ -116,6 +116,46 @@ def test_deterministic_keys_have_only_compatible_restore_prefixes(self): self.assertTrue(all("\n" not in value for name, value in outputs.items() if name.endswith(("-key", "-prefix", "-digest")))) + def test_loose_tier_ignores_only_the_recipe(self): + sources = cache.tracked.inventory(self.root) + for lane in cache.LANE_PURPOSES: + with self.subTest(lane=lane): + before = self.keys(lane) + self.assertTrue(before["swift-prefix"].startswith(before["swift-loose-prefix"])) + self.assertTrue(before["swift-loose-prefix"].startswith(before["swift-mlx-prefix"])) + self.assertTrue(before["swift-loose-prefix"].startswith( + f"provider-ci-swift-{cache.SWIFT_CACHE_VERSION}-{cache.LANE_PURPOSES[lane]}-")) + # A recipe edit keeps the loose tier and changes the strict one. + for relative in cache.RECIPE_PATHS: + path = self.root / relative + original = path.read_text() + path.write_text(original + "changed\n") + with patch.object(cache.tracked, "inventory", return_value=sources): + after = self.keys(lane) + path.write_text(original) + self.assertEqual(before["swift-loose-prefix"], after["swift-loose-prefix"], relative) + self.assertNotEqual(before["swift-prefix"], after["swift-prefix"], relative) + # A manifest, a toolchain or a checkout path changes both tiers. + manifest = self.root / "provider-swift/Package.resolved" + original = manifest.read_text() + manifest.write_text(original + "changed\n") + with patch.object(cache.tracked, "inventory", return_value=sources): + after = self.keys(lane) + self.assertNotEqual(before["swift-loose-prefix"], after["swift-loose-prefix"]) + # ... but keeps the MLX tier, whose objects do not depend on it. + self.assertEqual(before["swift-mlx-prefix"], after["swift-mlx-prefix"]) + manifest.write_text(original) + metadata = deepcopy(self.metadata) + metadata["swift"]["version"] += "changed" + self.assertNotEqual(before["swift-loose-prefix"], self.keys(lane, metadata=metadata)["swift-loose-prefix"]) + self.assertNotEqual(before["swift-mlx-prefix"], self.keys(lane, metadata=metadata)["swift-mlx-prefix"]) + other = self.temporary / "loose other checkout" + shutil.copytree(self.root, other) + self.assertNotEqual(self.keys()["swift-loose-prefix"], self.keys(root=other)["swift-loose-prefix"]) + self.assertNotEqual(self.keys()["swift-mlx-prefix"], self.keys(root=other)["swift-mlx-prefix"]) + # The metallib key keeps its own version. + self.assertTrue(self.keys()["metallib-key"].startswith(f"provider-ci-metallib-{cache.CACHE_VERSION}-")) + def test_source_commits_change_generations_not_prefixes_or_metallib(self): before = {lane: self.keys(lane) for lane in cache.LANE_PURPOSES} self.write("provider-swift/Sources/main.swift", 'print("after")\n') @@ -240,7 +280,7 @@ def test_metallib_uses_actual_sdk_xcode_deployment_and_fetch_stage_hashes(self): metadata["sdk"]["version"] += "different Swift SDK" metadata["swift"]["version"] += "different Swift toolchain" self.assertEqual(before, self.keys(metadata=metadata)["metallib-key"]) - self.write(".github/workflows/ci.yml", "# changed CI\n") + self.write(".github/workflows/provider-tests.yml", "# changed CI\n") self.assertEqual(before, self.keys()["metallib-key"]) def test_native_recursive_gitlink_not_top_level_mlx_keys_metallib(self): @@ -261,6 +301,8 @@ def test_native_recursive_gitlink_not_top_level_mlx_keys_metallib(self): commit(self.root) after = self.keys() self.assertNotEqual(before["swift-prefix"], after["swift-prefix"]) + # An MLX pin, top level or nested, also splits the MLX tier. + self.assertNotEqual(before["swift-mlx-prefix"], after["swift-mlx-prefix"]) if relative == cache.MLX_SOURCE: self.assertNotEqual(before["metallib-key"], after["metallib-key"]) self.assertEqual(after["mlx-sha"], git(module, "rev-parse", "HEAD")) @@ -439,7 +481,7 @@ def test_failed_probes_restore_missing_and_empty_environment_values(self): with patch.object(identity, "toolchain_metadata", return_value={"swift": {}}): with patch.object(identity, target, side_effect=ValueError("probe failed")): with self.assertRaisesRegex(ValueError, "probe failed"): - cache.toolchain_metadata("sdk") + cache.toolchain_metadata("cluster") self.assertEqual(dict(os.environ), {"PROVIDER_SWIFT": ""}) @@ -459,7 +501,7 @@ def test_scalar_output_cannot_inject_additional_github_records(self): def test_probe_errors_have_no_partial_output(self): stdout, stderr = io.StringIO(), io.StringIO() with patch.object(cache, "keys", side_effect=KeyError("PROVIDER_SWIFT")): - with patch.object(cache.sys, "argv", [str(SCRIPT), "keys", "--lane", "sdk"]): + with patch.object(cache.sys, "argv", [str(SCRIPT), "keys", "--lane", "cluster"]): with redirect_stdout(stdout), redirect_stderr(stderr): self.assertEqual(cache.main(), 1) self.assertEqual(stdout.getvalue(), "") diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index 298784aa64..aac68768a9 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -7,11 +7,11 @@ import os from pathlib import Path import re -import shlex import subprocess import sys import tempfile import textwrap +import time import unittest @@ -19,7 +19,19 @@ _SPEC = importlib.util.spec_from_file_location("provider_test_shards", ROOT / "scripts/provider-test-shards.py") shards = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(shards) -WORKFLOW = ROOT / ".github/workflows/ci.yml" +# The test jobs live in the reusable provider-tests.yml; Release Integrity and +# Docs Lint are CI (master)'s own jobs. CI (dev) runs only the test jobs. +WORKFLOW = ROOT / ".github/workflows/provider-tests.yml" +MASTER_WORKFLOW = ROOT / ".github/workflows/ci-master.yml" +# The plan the callers share: the classifier, the tree lookup and the route. +PLAN_WORKFLOW = ROOT / ".github/workflows/provider-plan.yml" +DEV_WORKFLOW = ROOT / ".github/workflows/ci-dev.yml" + + +def workflow_text(): + """The test workflow, then CI (master): every job CI runs, each once.""" + return WORKFLOW.read_text() + "\n" + MASTER_WORKFLOW.read_text() + ACTION = ROOT / ".github/actions/provider-ci-build/action.yml" BUILD_ACTION = "./.github/actions/provider-ci-build" PROVIDER_TEST_COMMAND = ('python3 ../scripts/run-provider-test-watchdog.py \\\n' @@ -28,36 +40,22 @@ ' -- ../scripts/run-provider-tests.sh') READY = "${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }}" MIMO_READY = "${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }}" -SDK_CONDITION = "github.event_name == 'push' || needs.changes.outputs.sdk == 'true'" # Steps that run once, in the last provider shard. LAST_SHARD = "matrix.shard == strategy.job-total" LAST_SHARD_READY = READY.replace("!cancelled() && ", f"!cancelled() && {LAST_SHARD} && ") LAST_SHARD_MIMO_READY = MIMO_READY.replace("!cancelled() && ", f"!cancelled() && {LAST_SHARD} && ") PROVIDER_MIMO_READY = "${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }}" +MIMO_METADATA_CACHE = '--cache "$RUNNER_TEMP/mimo-metadata-cache"' MIMO_PREPARE = ('python3 scripts/prepare-mimo-prompt-fixtures.py ' - '--output "$RUNNER_TEMP/mimo-prompt-fixtures" --github-env "$GITHUB_ENV"') + '--output "$RUNNER_TEMP/mimo-prompt-fixtures" --github-env "$GITHUB_ENV" ' + MIMO_METADATA_CACHE) MIMO_HTTP_PREPARE = ('python3 scripts/test-prepare-mimo-image-http-fixtures.py\n' + MIMO_PREPARE + '\n' + 'python3 scripts/prepare-mimo-image-http-fixtures.py ' - '--output "$RUNNER_TEMP/mimo-image-http-fixtures" --github-env "$GITHUB_ENV"') + '--output "$RUNNER_TEMP/mimo-image-http-fixtures" --github-env "$GITHUB_ENV" ' + MIMO_METADATA_CACHE) MIMO_PROVIDER_PREPARE = ('python3 scripts/prepare-mimo-provider-fixtures.py ' '--output "$RUNNER_TEMP/mimo-provider-fixtures" --github-env "$GITHUB_ENV"\n' 'python3 scripts/prepare-mimo-provider-fixtures.py ' '--output "$RUNNER_TEMP/mimo-prefix-fixtures" --asymmetric') -SDK_MIMO_PREPARE_NAME = "Prepare tiny MiMo fixture for media-to-text isolation" -SDK_MIMO_GATE_NAME = "Verify media refusal leaves the native text engine usable" -SDK_MIMO_READY = "${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.sdk-mimo-isolation-fixture.outcome == 'success' }}" -SDK_RETENTION_PREPARE_NAME = "Prepare asymmetric tiny MiMo fixture for native retention" -SDK_RETENTION_GATE_NAME = "Verify native retained frontier after donor retirement" -SDK_RETENTION_READY = "${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.sdk-mimo-retention-fixture.outcome == 'success' }}" -SDK_RETENTION_HOST_COMMANDS = { - "Verify native historical retention policy": - "../../scripts/run-nested-suite.sh CBv2NativeHistoricalRetentionTests --no-parallel", - "Verify demanded checkpoint scheduling and projection": - "../../scripts/run-nested-suite.sh CBv2DemandedCheckpointPartitionTests --no-parallel", - "Verify demanded long range continuation and projection": - "../../scripts/run-nested-suite.sh CBv2DemandedCheckpointContinuationTests --no-parallel", -} MIMO_NATIVE_COMMANDS = { "Run isolated native MiMo startup gates": "../scripts/run-nested-suite.sh 'MiMoV26StandaloneLifecycleTests.test(ActualScannerPreloadStartsListenerWithSameNativeOwner|StartRefusesActualUnpublishedPreloadWithoutReplacingOwner)' --no-parallel", @@ -73,55 +71,24 @@ "../scripts/run-nested-suite.sh testGracefulDrainAfterServedRequestRetiresNativeOwnerWithinDeadline --no-parallel", } COVERAGE_STEPS = ("Collect provider coverage profiles", "Merge shard coverage profiles") +# Each shard's own audit and coverage report (test_only_the_provider_lane_collects_and_reports_coverage). +SHARD_CHECK_STEPS = ("Check this shard's selections against the suite list", "Report provider coverage") SHARD_UPLOAD = "Upload shard counts, timings and coverage" LANES = { "test-provider": "provider", - "test-provider-sdk": "sdk", } -PROVIDER_SHARDS = [1, 2, 3] -# Prompt Parity runs in a provider shard (scripts/provider-test-shards.py PARITY_SHARD). +PROVIDER_SHARDS = [1, 2] +# Each shard runs this many selections at the same time (scripts/run-provider-tests.sh), +# so the planner splits the suite into len(PROVIDER_SHARDS) * PROVIDER_PROCESSES selections. +PROVIDER_PROCESSES = 3 +# Prompt Parity runs in the provider shard that holds selection +# PARITY_SHARD (scripts/provider-test-shards.py). PARITY_STEPS = { "Verify public prompt golden vectors": ("./scripts/verify-prompt-parity.sh", "ProductionPromptParityTests", "prompt"), "Verify pinned Nemotron prompts and numeric cache plans": ("./scripts/verify-nemotron-prompt-parity.sh", "NemotronTemplateParityLiveTests", "nemotron"), } -SDK_COMMANDS = { - **SDK_RETENTION_HOST_COMMANDS, - SDK_RETENTION_PREPARE_NAME: - 'python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-native-retention" --asymmetric', - SDK_RETENTION_GATE_NAME: - "../../scripts/run-nested-suite.sh MiMoV26NativeHistoricalRetentionTests.testDemandedMiddleFrontierSurvivesNativePublicationAndReopenedFork --no-parallel", - "Verify DiffusionGemma artifact and expert reduction": - "../../scripts/run-nested-suite.sh 'DiffusionGemma(ArtifactFixture|ExpertReduction)Tests' --no-parallel", - "Run nested MiMo media decode tests": - "../../scripts/run-nested-suite.sh 'MiMoV26(OpenRouterMedia|VisionWorkingSet|AudioWorkingSet|VisualDecodeMemory|EncodedVisualDecoder|EncodedAudioDecoder|EncodedAACAudio|EncodedAudiovisualDecoder)Tests|MiMoV26PixelsTests.test(RGB|Temporal|Invalid|Explicit)' --no-parallel", - SDK_MIMO_PREPARE_NAME: - 'python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-media-isolation"', - SDK_MIMO_GATE_NAME: - "../../scripts/run-nested-suite.sh MiMoV26NativeMediaDeadlineTests --no-parallel", - "Run nested paged safety tests": - "../../scripts/run-nested-suite.sh CBv2PagedSafetyTests", - "Run nested prompt-hash tests": - "../../scripts/run-nested-suite.sh CBv2PrefixCacheHasherTests", - "Run nested paged eligibility tests": - "../../scripts/run-nested-suite.sh CBv2PagedEligibilityTests", - "Run nested paged backend tests": - "../../scripts/run-nested-suite.sh CBv2PagedBackendTests", - "Run nested paged kernel parity tests": - "../../scripts/run-paged-kernel-tests.sh", - "Run nested KV-sharing contiguous/paged parity tests": - "../../scripts/run-nested-suite.sh CBv2KVSharingParityTests", -} -SDK_ONBOARDING_SUITES = ( - "SSMDecodeBoundsTests", "NemotronHTests", - "NemotronH35BackendParityTests", "NemotronH35StorageParityTests", - "NemotronH35MTPTests", "NemotronH35MTPPrimingTests", - "MutableInputKernelTests", "MutableInputExportTests", - "CBv2QwenMTPIntegrationTests", "CBv2MTPDepthControllerTests", - "PagedMTPBatchedColumnsTests", "CBv2CompleteCheckpointEngineTests", - "NemotronH35ProductionDefaultsTests", "OpenAIServiceTests", - "ToolCallParserIntegrationTests", -) + def job_blocks(workflow): @@ -152,10 +119,45 @@ def run_command(step): return textwrap.dedent("\n".join(lines[:end])).strip() +CHECKOUT = "actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2" +CACHE_RESTORE = "actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0" +CACHE_SAVE = "actions/cache/save@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0" +# Pushes to master and dev save caches; pull requests never do. +SAVE_POLICY = (" SAVE_CACHES: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' " + "|| github.ref == 'refs/heads/dev') }}\n") +SAVE_CACHES = "env.SAVE_CACHES == 'true'" +SAVE_INPUT = "inputs.save-caches == 'true'" +VALIDATE_GIT = """if [ -d .git ] && ! { git rev-parse --verify -q HEAD >/dev/null && + git fsck --connectivity-only --no-progress >/dev/null 2>&1; }; then + echo "::warning title=.git cache::git fsck rejected the restored .git; checking out without it." + rm -rf .git +fi""" +SPARSE_PATTERNS = ("/*", "!/docs/reports/evidence/**/*.gz", "!/landing/public/media/") +GIT_CACHE_STEPS = ("Select today's .git cache", "Restore the newest saved .git", + "Discard a damaged cached .git", None, "Save .git for later runs") + + +def uses(step): + """The action a step uses, whether `uses:` opens the step or follows `name:`.""" + return field(step, "uses") or field(step, "uses", indent=6) + + +def checkout_options(step): + lines = step.split(" with:\n", 1)[1].splitlines() + return [line.split(" #", 1)[0].strip() for line in lines if line.startswith(" ")] + + +def work_steps(job): + """The steps after the shared .git cache and checkout steps.""" + return [step for step in step_blocks(job) if field(step, "name", indent=6) not in GIT_CACHE_STEPS] + + class ProviderCIWorkflowTests(unittest.TestCase): def setUp(self): - self.workflow = WORKFLOW.read_text() - self.jobs = job_blocks(self.workflow) + self.workflow = workflow_text() + self.jobs = {**job_blocks(WORKFLOW.read_text().split("\njobs:\n", 1)[1]), + **job_blocks(MASTER_WORKFLOW.read_text().split("\njobs:\n", 1)[1]), + **job_blocks(PLAN_WORKFLOW.read_text().split("\njobs:\n", 1)[1])} def test_nested_wrapper_preserves_long_filters_and_failure_gates(self): selector = "NativeSuite/" + "VeryLongTestName" * 30 + "|OtherSuite/testCase" @@ -209,17 +211,16 @@ def test_lanes_are_independent_on_dedicated_supported_mac_runners(self): lane_key = f"'{job_id}'" # A Darkbloom macOS sandbox when granted, otherwise the same # dedicated Blacksmith runner; requested only when the job runs. - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)[%s] }}\n" % lane_key, job) - # The SDK lane runs on every push and on pull requests that change its inputs. - condition = (SDK_CONDITION if job_id == "test-provider-sdk" - else "needs.changes.outputs.provider == 'true'") - requested = f"({condition})" if "||" in condition else condition + self.assertIn(" runs-on: ${{ fromJSON(inputs.routes)[%s] }}\n" % lane_key, job) + # The plan's components are the classifier's, or none for a + # tree that already passed (provider-plan.yml). for route_lane in route_lanes: self.assertIn(" %s macos_arm64 blacksmith-12vcpu-macos-27 " - "${{ %s && 1 || 0 }}\n" % (route_lane, requested), self.jobs["route"]) + "${{ needs.components.outputs.provider == 'true' && 1 || 0 }}\n" % route_lane, + self.jobs["route"]) self.assertIn(" timeout-minutes: 60\n", job) - self.assertIn(" needs: [changes, route]\n", job) - self.assertIn(" if: ${{ %s }}\n" % condition, job) + self.assertNotRegex(job, r"(?m)^ needs:") + self.assertIn(" if: ${{ inputs.provider == 'true' }}\n", job) self.assertNotIn("continue-on-error:", job) self.assertNotIn("DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST:", job) self.assertIn(" name: Provider Unit Tests (shard ${{ matrix.shard }})\n", self.jobs["test-provider"]) @@ -235,8 +236,7 @@ def test_route_requests_exactly_one_lane_per_provider_shard(self): def test_existing_required_check_requires_every_lane_even_after_failures(self): job = self.jobs["provider-test-gate"] self.assertIn(" name: Provider Tests\n", job) - self.assertIn(" needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused]\n", job) - # Provider SDK Tests notifies after merge and never blocks this gate. + self.assertIn(" needs: [test-provider, test-cluster, test-cluster-focused]\n", job) self.assertNotIn("test-provider-sdk", job) self.assertIn(" if: ${{ always() }}\n", job) self.assertNotIn("continue-on-error:", job) @@ -244,7 +244,7 @@ def test_existing_required_check_requires_every_lane_even_after_failures(self): command = run_command(step) # Prompt Parity is a step of a provider shard: its failure is UNIT_RESULT's. self.assertNotIn("test-provider-parity", job) - lanes = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") + lanes = ("UNIT_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") for failed in (None, *lanes): for outcome in ("failure", "skipped", "cancelled"): results = {lane: outcome if lane == failed else "success" for lane in lanes} @@ -254,25 +254,48 @@ def test_existing_required_check_requires_every_lane_even_after_failures(self): capture_output=True, timeout=5) self.assertEqual(result.returncode == 0, failed is None, results) + def test_the_gate_checks_the_ci_plans_on_every_run(self): + # dev has no Release Integrity: the gate audits the cluster plan and + # runs the plan self-tests on every run, skipped or not. + steps = {field(step, "name", indent=6): step for step in step_blocks(self.jobs["provider-test-gate"])} + check = steps["Check the CI plans"] + # They run even when the requirement above failed; only a cancel stops them. + self.assertEqual(field(check, "if"), "${{ !cancelled() }}") + commands = run_command(check).splitlines() + for command in ("python3 scripts/cluster-test-plan.py audit", "python3 scripts/test-cluster-test-plan.py", + "python3 scripts/test-provider-test-shards.py", "python3 scripts/test-ci-component-paths.py", + "python3 scripts/test-ci-tested-tree.py"): + self.assertIn(command, commands) + # The record names its change through the lookup's own code, and only + # a run that tested something records. + record = steps["Name the record of the change these tests passed"] + self.assertIn('python3 scripts/ci-tested-tree.py name --tree "$TREE" --base "$BASE" --head "$HEAD"', record) + for name in ("Name the record of the change these tests passed", "Upload the record"): + self.assertEqual(field(steps[name], "if"), + "${{ inputs.skip != 'true' && (inputs.provider == 'true' || inputs.cluster == 'true') }}") + def test_each_lane_checks_out_recursive_sources_before_its_build(self): for job_id, lane in LANES.items(): with self.subTest(lane=lane): steps = step_blocks(self.jobs[job_id]) - self.assertIn("actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683", steps[0]) - self.assertEqual(field(steps[0], "submodules", indent=10), "recursive") + checkout = next(step for step in steps if uses(step) == CHECKOUT) + self.assertEqual(uses(checkout), CHECKOUT) + self.assertEqual(field(checkout, "submodules", indent=10), "recursive") builds = [step for step in steps if field(step, "uses") == BUILD_ACTION] self.assertEqual(len(builds), 1) + self.assertGreater(steps.index(builds[0]), steps.index(checkout)) self.assertEqual(field(builds[0], "lane", indent=10), lane) self.assertEqual(field(builds[0], "id"), "provider-ci-build") self.assertIsNone(field(builds[0], "if")) - if lane == "sdk": - self.assertEqual(field(builds[0], "timeout-minutes"), "35") - restores = [step for step in steps if "actions/cache/restore@" in step] + restores = [step for step in steps + if "actions/cache/restore@" in step and field(step, "id") != "git-cache"] if lane == "provider": - self.assertEqual(len(restores), 1) - self.assertEqual(field(restores[0], "id"), "mimo-audio-cache") - self.assertIn("mimo-audio-source-v2-", restores[0]) - self.assertGreater(steps.index(restores[0]), steps.index(builds[0])) + # The verified MiMo metadata downloads, then the audio codec. + self.assertEqual([field(step, "id") for step in restores], ["mimo-metadata-cache", "mimo-audio-cache"]) + self.assertIn("mimo-metadata-v1-", restores[0]) + self.assertIn("mimo-audio-source-v2-", restores[1]) + for restore in restores: + self.assertGreater(steps.index(restore), steps.index(builds[0])) else: self.assertEqual(restores, []) self.assertNotIn("spm-v3-", self.jobs[job_id]) @@ -293,7 +316,7 @@ def test_only_the_provider_lane_collects_and_reports_coverage(self): self.assertIn('echo "LLVM_PROFILE_FILE=$profiles/%p-%m.profraw" >> "$GITHUB_ENV"', steps[collect]) self.assertIn('echo "PROVIDER_COVERAGE_DIR=$profiles" >> "$GITHUB_ENV"', steps[collect]) self.assertGreater(merge, max(tests)) - self.assertEqual(shard_upload, merge + 1) + self.assertGreater(shard_upload, merge) skipped_tests = "${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }}" self.assertEqual(field(steps[merge], "if"), skipped_tests) self.assertEqual(field(steps[shard_upload], "if"), skipped_tests) @@ -303,48 +326,42 @@ def test_only_the_provider_lane_collects_and_reports_coverage(self): self.assertIn("if-no-files-found: error", steps[shard_upload]) for step in (steps[merge], steps[shard_upload]): self.assertNotIn("continue-on-error:", step) - # The summary merges every shard's profile against the shards' cached - # build and writes the report; the gate requires it. - summary = self.jobs["test-provider-summary"] - self.assertIn(" name: Provider Unit Tests Summary\n", summary) - self.assertIn(" needs: [changes, route, test-provider]\n", summary) - self.assertIn(" if: ${{ !cancelled() && needs.changes.outputs.provider == 'true' }}\n", summary) - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-provider-summary'] }}\n", summary) - self.assertIn(" test-provider-summary macos_arm64 blacksmith-12vcpu-macos-27 " - "${{ needs.changes.outputs.provider == 'true' && 1 || 0 }}\n", self.jobs["route"]) - self.assertNotIn("continue-on-error:", summary) - summary_steps = step_blocks(summary) - summary_names = [field(step, "name", indent=6) for step in summary_steps] - summary_build = next(index for index, step in enumerate(summary_steps) - if field(step, "uses") == BUILD_ACTION) - self.assertEqual(field(summary_steps[summary_build], "lane", indent=10), "provider") - download = summary_names.index("Download shard reports") - audit = summary_names.index("Check that the shards executed the full provider suite") - report = summary_names.index("Report provider coverage") - upload = summary_names.index("Upload provider coverage report") - self.assertLess(summary_build, download) - self.assertLess(download, audit) + # Each shard audits its own selections against `swift test list` of + # its own build (the last shard also checks that the plans cover the + # list once) and writes its own coverage report; no Mac job exists only + # to audit (David, 2026-11-04). + self.assertNotIn("test-provider-summary", self.jobs) + swift_tests = names.index("Run Swift tests") + audit = names.index("Check this shard's selections against the suite list") + report = names.index("Report provider coverage") + upload = names.index("Upload provider coverage report") + self.assertLess(swift_tests, audit) + self.assertLess(merge, report) self.assertLess(audit, report) self.assertEqual(upload, report + 1) - self.assertIn("pattern: provider-unit-shard-*", summary_steps[download]) - self.assertEqual(field(summary_steps[report], "if"), READY) - self.assertEqual(field(summary_steps[audit], "if"), READY) - self.assertIn('profiles=("$RUNNER_TEMP"/provider-unit-shards/*/provider.profdata)', summary_steps[report]) - self.assertIn("xcrun llvm-profdata merge", summary_steps[report]) - self.assertIn("name: provider-coverage", summary_steps[upload]) + self.assertLess(upload, shard_upload) + for index in (audit, report): + self.assertEqual(field(steps[index], "if"), skipped_tests) + self.assertNotIn("continue-on-error:", steps[index]) + self.assertIn("swift test list --skip-build", steps[audit]) + self.assertIn('provider-test-shards.py audit-job "$RUNNER_TEMP/provider-tests.txt"', steps[audit]) + self.assertEqual(field(steps[audit], "SHARD", indent=10), "${{ matrix.shard }}/${{ strategy.job-total }}") + self.assertEqual(field(steps[audit], "PROVIDER_TEST_PROCESSES", indent=10), f"'{PROVIDER_PROCESSES}'") + self.assertIn('cp "$RUNNER_TEMP/provider-unit-shard/provider.profdata" "$out/provider.profdata"', steps[report]) + self.assertIn("name: provider-coverage-${{ matrix.shard }}", steps[upload]) test_step = next(step for step in steps if run_command(step) == PROVIDER_TEST_COMMAND) self.assertEqual(field(test_step, "id"), "provider-unit-tests") - self.assertNotIn("LLVM_PROFILE_FILE", summary) - self.assertNotIn("LLVM_PROFILE_FILE", self.jobs["test-provider-sdk"]) - self.assertNotIn("PROVIDER_COVERAGE_DIR", self.jobs["test-provider-sdk"]) build_step = next(step for step in step_blocks(ACTION.read_text(), indent=4) if field(step, "id", indent=6) == "provider-build") self.assertEqual(textwrap.dedent(build_step.split("run: |\n", 1)[1]).strip(), - "swift build --build-tests --enable-code-coverage\n" - "swift build --product darkbloom-fan-helper --enable-code-coverage") + "build() {\n" + " swift build --build-tests --enable-code-coverage &&\n" + " swift build --product darkbloom-fan-helper --enable-code-coverage\n" + "}\n" + "build || { ../scripts/provider-ci-cold-retry.sh && build; }") def test_provider_entrypoint_and_resource_installer_checks_are_retained(self): - steps = step_blocks(self.jobs["test-provider"]) + steps = work_steps(self.jobs["test-provider"]) expected = ( "python3 scripts/test-qwen4-packaged-resources.py", "python3 scripts/test-stage-swiftpm-resource-bundles.py", @@ -359,13 +376,15 @@ def test_provider_entrypoint_and_resource_installer_checks_are_retained(self): "./scripts/test-install-atomic.sh", ) runs = [run_command(step) for step in steps - if field(step, "run") and field(step, "name", indent=6) not in (*COVERAGE_STEPS, *PARITY_STEPS)] + if field(step, "run") + and field(step, "name", indent=6) not in (*COVERAGE_STEPS, *PARITY_STEPS, *SHARD_CHECK_STEPS)] self.assertEqual(runs, list(expected)) test_step = next(step for step in steps if run_command(step) == PROVIDER_TEST_COMMAND) self.assertEqual(field(test_step, "id"), "provider-unit-tests") self.assertEqual(field(test_step, "timeout-minutes"), "35") self.assertEqual(field(test_step, "PROVIDER_TEST_SHARD", indent=10), "${{ matrix.shard }}/${{ strategy.job-total }}") + self.assertEqual(field(test_step, "PROVIDER_TEST_PROCESSES", indent=10), f"'{PROVIDER_PROCESSES}'") self.assertEqual(field(test_step, "PROVIDER_TEST_REPORT_DIR", indent=10), "${{ runner.temp }}/provider-unit-shard") # Every shard prepares the fixtures its suites read; every other check @@ -408,12 +427,13 @@ def test_provider_watchdog_diagnostics_survive_test_failure_not_cancellation(sel upload = next(step for step in steps if field(step, "name", indent=6) == "Upload provider test diagnostics") self.assertEqual(field(upload, "if"), "${{ !cancelled() && steps.provider-unit-tests.outcome != 'skipped' }}") self.assertEqual(field(upload, "uses"), "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1") - self.assertEqual(field(upload, "path", indent=10), "${{ runner.temp }}/provider-test-diagnostics") + self.assertIn(" path: |\n ${{ runner.temp }}/provider-test-diagnostics\n" + " ${{ runner.temp }}/provider-unit-shard/slot-*.out\n", upload) self.assertEqual(field(upload, "retention-days", indent=10), "7") self.assertNotIn("continue-on-error:", self.jobs["test-provider"]) def test_coverage_summary_preserves_weighted_rows_and_failure_checks(self): - report = next(step for step in step_blocks(self.jobs["test-provider-summary"]) + report = next(step for step in step_blocks(self.jobs["test-provider"]) if field(step, "id") == "provider-coverage") summary_script = run_command(report).split("<<'PY'\n", 1)[1].split("\nPY", 1)[0] source_root = "/fixture/provider-swift/Sources" @@ -463,106 +483,24 @@ def summary(covered, count): ]) self.assertIn("These targets are only in the total: `darkbloom-fan-helper`.", result.stdout) - def test_sdk_retains_every_original_gate_command(self): - steps = step_blocks(self.jobs["test-provider-sdk"]) - gates = {field(step, "name", indent=6): step for step in steps if field(step, "run")} - self.assertEqual(len(gates), sum(bool(field(step, "run")) for step in steps)) - self.assertEqual(set(gates), set(SDK_COMMANDS) | {"Run Nemotron production SDK gates"}) - for name, command in SDK_COMMANDS.items(): - with self.subTest(gate=name): - self.assertEqual(run_command(gates[name]), command) - commands = "\n".join(run_command(step) for step in gates.values()) - self.assertNotIn("swift test", commands) - self.assertNotIn("--skip", commands) - self.assertNotIn("rustup", self.jobs["test-provider-sdk"]) - - def test_every_sdk_gate_requires_successful_build_but_not_earlier_tests(self): - fixture_conditions = { - SDK_MIMO_GATE_NAME: SDK_MIMO_READY, - SDK_RETENTION_GATE_NAME: SDK_RETENTION_READY, - } - preparation_steps = {SDK_MIMO_PREPARE_NAME, SDK_RETENTION_PREPARE_NAME} - for step in step_blocks(self.jobs["test-provider-sdk"]): - if field(step, "run"): - with self.subTest(gate=field(step, "name", indent=6)): - name = field(step, "name", indent=6) - self.assertEqual(field(step, "if"), fixture_conditions.get(name, READY)) - expected_directory = None if name in preparation_steps else "libs/mlx-swift-lm" - self.assertEqual(field(step, "working-directory"), expected_directory) - self.assertNotIn("continue-on-error:", step) - - def test_sdk_retention_requires_asymmetric_fixture_and_non_skipping_selectors(self): - steps = step_blocks(self.jobs["test-provider-sdk"]) - by_name = {field(step, "name", indent=6): step for step in steps} - prepare = by_name[SDK_RETENTION_PREPARE_NAME] - gate = by_name[SDK_RETENTION_GATE_NAME] - self.assertEqual(field(prepare, "id"), "sdk-mimo-retention-fixture") - self.assertEqual(run_command(prepare), SDK_COMMANDS[SDK_RETENTION_PREPARE_NAME]) - self.assertLess(steps.index(prepare), steps.index(gate)) - self.assertEqual(field(gate, "if"), SDK_RETENTION_READY) - self.assertEqual(field(gate, "timeout-minutes"), "5") - self.assertEqual(field(gate, "MIMO_V26_SERIAL_NATIVE_TESTS", indent=10), "'1'") - self.assertEqual(field(gate, "MIMO_V26_SERIAL_LOAD_FIXTURES", indent=10), "${{ runner.temp }}/mimo-native-retention") - self.assertEqual(run_command(gate), SDK_COMMANDS[SDK_RETENTION_GATE_NAME]) - for name, command in SDK_RETENTION_HOST_COMMANDS.items(): - with self.subTest(gate=name): - host = by_name[name] - self.assertEqual(run_command(host), command) - self.assertEqual(field(host, "timeout-minutes"), "5") - self.assertNotIn("\n env:", host) - - def test_sdk_media_isolation_requires_its_fixture_and_native_lane(self): - steps = step_blocks(self.jobs["test-provider-sdk"]) - prepare = next(step for step in steps if field(step, "name", indent=6) == SDK_MIMO_PREPARE_NAME) - gate = next(step for step in steps if field(step, "name", indent=6) == SDK_MIMO_GATE_NAME) - self.assertEqual(field(prepare, "id"), "sdk-mimo-isolation-fixture") - self.assertLess(steps.index(prepare), steps.index(gate)) - self.assertEqual(field(gate, "timeout-minutes"), "5") - self.assertEqual(field(gate, "MIMO_V26_SERIAL_NATIVE_TESTS", indent=10), "'1'") - self.assertEqual(field(gate, "MIMO_V26_NATIVE_MEDIA_DEADLINE_TESTS", indent=10), "'1'") - self.assertEqual(field(gate, "MIMO_V26_SERIAL_LOAD_FIXTURES", indent=10), "${{ runner.temp }}/mimo-media-isolation") - - def test_sdk_onboarding_selectors_execute_once_and_continue_after_failure(self): - step = next(step for step in step_blocks(self.jobs["test-provider-sdk"]) - if field(step, "name", indent=6) == "Run Nemotron production SDK gates") - command = run_command(step) - with tempfile.TemporaryDirectory(prefix="provider-ci-workflow-") as temporary: - root = Path(temporary) - package = root / "libs/mlx-swift-lm" - package.mkdir(parents=True) - scripts = root / "scripts" - scripts.mkdir() - runner = scripts / "run-nested-suite.sh" - runner.write_text('#!/bin/bash\n' - 'printf "%s\\n" "$*" >> "$CI_GATE_LOG"\n' - '[ "$1" != "${CI_FAIL_SUITE:-}" ]\n') - runner.chmod(0o700) - for failure in ("", *SDK_ONBOARDING_SUITES): - with self.subTest(failure=failure): - log = root / "calls" - log.write_text("") - result = subprocess.run( - ["bash", "-e", "-o", "pipefail", "-c", command], cwd=package, - env={**os.environ, "CI_GATE_LOG": str(log), "CI_FAIL_SUITE": failure}, - capture_output=True, text=True, timeout=10, - ) - self.assertEqual(result.returncode, 1 if failure else 0, result.stderr) - self.assertEqual(log.read_text().splitlines(), list(SDK_ONBOARDING_SUITES)) - - def test_required_sdk_selectors_are_not_duplicated_in_other_lanes(self): - selectors = [shlex.split(command)[1] for command in SDK_COMMANDS.values() - if "run-nested-suite.sh" in command] - selectors.extend(SDK_ONBOARDING_SUITES) - sdk = "\n".join(run_command(step) for step in step_blocks(self.jobs["test-provider-sdk"]) - if field(step, "run")) - for selector in selectors: - with self.subTest(selector=selector): - self.assertEqual(sdk.count(selector), 1) - self.assertNotIn(selector, self.jobs["test-provider"]) + def test_sdk_suites_run_in_the_sdks_own_fork_tests(self): + # David, 2026-11-04: Provider SDK Tests repeated the SDK's own Fork + # Tests (226 of its 236 test seconds), so the lane and the SDK build + # lane are gone. Fork Tests skips the one other step, + # MiMoV26NativeMediaDeadlineTests; un-skipping it there is the SDK's + # (work/d-inference-test-dedup-inventory.md, class C). + self.assertNotIn("test-provider-sdk", self.jobs) + self.assertNotIn("test-provider-sdk", self.jobs["route"]) + for selector in ("MiMoV26NativeMediaDeadlineTests", "CBv2PagedSafetyTests", "NemotronH35MTPTests", + "run-paged-kernel-tests.sh", "swift package edit"): + self.assertNotIn(selector, self.workflow) + action = ACTION.read_text() + self.assertIn(" provider|cluster) ;;\n", action) + self.assertNotIn("libs/mlx-swift-lm", action) + # Each provider entry point and parity script still runs exactly once. commands = Counter(run_command(step) for job in self.jobs.values() for step in step_blocks(job)) - self.assertEqual(commands["../../scripts/run-paged-kernel-tests.sh"], 1) self.assertEqual(commands[PROVIDER_TEST_COMMAND], 1) - workflow = WORKFLOW.read_text() + workflow = workflow_text() for script, _, _ in PARITY_STEPS.values(): self.assertEqual(workflow.count(script), 1, script) @@ -571,7 +509,7 @@ def test_parity_retains_public_swift_golden_vector_scripts(self): self.assertEqual([step for step in steps if "actions/setup-go@" in step], []) names = [field(step, "name", indent=6) for step in steps] tests = names.index("Run Swift tests") - shard = f"matrix.shard == {shards.PARITY_SHARD}" + shard = f"matrix.shard == {(shards.PARITY_SHARD - 1) // PROVIDER_PROCESSES + 1}" conditions = { "Verify public prompt golden vectors": "${{ !cancelled() && %s && steps.provider-ci-build.outcome == 'success' && " @@ -647,7 +585,12 @@ def test_audio_qualification_uses_real_codec_and_no_skip_gate(self): steps = step_blocks(self.jobs["test-provider"]) fixture = next(s for s in steps if field(s, "id") == "mimo-audio-fixtures") self.assertIn("prepare-mimo-audio-fixtures.py", run_command(fixture)) - self.assertEqual(field(fixture, "if"), LAST_SHARD_READY) + # The 1.87 GB codec is fetched only when the gate's inputs changed; + # the gate needs the fixture, so it skips with it. + audio_ready = LAST_SHARD_READY.replace(" }}", " && inputs.mimo_audio == 'true' }}") + self.assertEqual(field(fixture, "if"), audio_ready) + restore = next(s for s in steps if field(s, "id") == "mimo-audio-cache") + self.assertEqual(field(restore, "if"), audio_ready) gate = next(s for s in steps if field(s, "name", indent=6) == "Run isolated native MiMo audio gate") self.assertIn("testNativeAudioRelease", run_command(gate)) self.assertIn("run-nested-suite.sh", run_command(gate)) @@ -657,18 +600,22 @@ def test_audio_qualification_uses_real_codec_and_no_skip_gate(self): self.assertNotIn("continue-on-error:", gate) def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): - job = self.jobs["test-cluster-checks"] - self.assertIn(" name: Cluster Metadata Checks\n", job) - self.assertIn(" needs: [changes, route]\n", job) - self.assertIn(" if: ${{ needs.changes.outputs.cluster == 'true' }}\n", job) - self.assertIn(" runs-on: ${{ fromJSON(needs.route.outputs.routes)['test-cluster-checks'] }}\n", job) - self.assertIn(" test-cluster-checks macos_arm64 blacksmith-12vcpu-macos-27 " - "${{ needs.changes.outputs.cluster == 'true' && 1 || 0 }}\n", self.jobs["route"]) + # The metadata runners run in Cluster Focused Checks, before the other + # focused runners: no Mac job runs only these (David, 2026-11-04). + self.assertNotIn("test-cluster-checks", self.jobs) + self.assertNotIn("test-cluster-checks", self.jobs["route"]) + job = self.jobs["test-cluster-focused"] + self.assertIn(" name: Cluster Focused Checks\n", job) + self.assertIn(" if: ${{ inputs.cluster == 'true' }}\n", job) + self.assertIn(" runs-on: ${{ fromJSON(inputs.routes)['test-cluster-focused'] }}\n", job) + self.assertIn(" test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 " + "${{ needs.components.outputs.cluster == 'true' && 1 || 0 }}\n", self.jobs["route"]) for forbidden in ("continue-on-error:", "secrets.", "DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST:"): self.assertNotIn(forbidden, job) steps = step_blocks(job) - self.assertIn("actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683", steps[0]) - self.assertEqual(field(steps[0], "submodules", indent=10), "recursive") + checkout = next(step for step in steps if uses(step) == CHECKOUT) + self.assertEqual(uses(checkout), CHECKOUT) + self.assertEqual(field(checkout, "submodules", indent=10), "recursive") toolchain = next(step for step in steps if field(step, "id") == "toolchain") self.assertEqual(run_command(toolchain), "./scripts/prepare-provider-release-toolchain.sh") runners = { @@ -711,33 +658,40 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertIn("python3 scripts/provider-release-cache.py restore-mtimes", steps[timestamps]) self.assertIn("python3 scripts/provider-release-cache.py snapshot-mtimes", steps[record]) key = named["Resolve cluster metadata build cache key"] - for component in ("swift --version", "xcodebuild -version", "git submodule status --recursive", + pins = "git submodule status --recursive | awk '{print $1, $2}'" + for component in ("swift --version", "xcodebuild -version", pins, "$GITHUB_WORKSPACE $RUNNER_TEMP $MANIFESTS", "native-metadata.sh"): self.assertIn(component, key) + # `git describe` text depends on the refs a restored .git holds; the + # key keeps only each submodule's state, pin and path. + status = " 0123abc libs/mlx (heads/main)\n+4567def libs/mlx-swift (v0.30.0-2-g4567def)\n" + pinned = subprocess.run(["awk", "{print $1, $2}"], input=status, capture_output=True, text=True, check=True) + self.assertEqual(pinned.stdout, "0123abc libs/mlx\n+4567def libs/mlx-swift\n") for step in (steps[record], steps[upload]): self.assertIn("steps.capability-checks.outcome == 'success'", field(step, "if")) - # A pull request saves only when it restored nothing; pushes save. - self.assertIn("steps.cluster-build-cache.outputs.cache-hit != 'true' && (github.event_name != " - "'pull_request' || steps.cluster-build-cache.outputs.cache-matched-key == '')", - field(step, "if")) + # Only pushes to a saving branch save; a pull request never does. + self.assertIn(SAVE_CACHES + " && ", field(step, "if")) + self.assertIn("steps.cluster-build-cache.outputs.cache-hit != 'true'", field(step, "if")) support = (ROOT / "libs/darkbloom-cluster/Tests/Support/native-metadata.sh").read_text() self.assertIn('task_jobs="${DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS:-4}"', support) self.assertIn('--jobs "$task_jobs"', support) def test_parity_has_no_backend_caches_or_credentials(self): - # Prompt Parity now runs in the provider shards; the only cache that - # job saves directly is the verified MiMo audio codec. + # Prompt Parity now runs in the provider shards; besides .git, the only + # caches that job saves directly are the verified MiMo downloads. steps = step_blocks(self.jobs["test-provider"]) saves = [step for step in steps if "actions/cache/save@" in step] - self.assertEqual([field(step, "name", indent=6) for step in saves], ["Cache verified MiMo audio codec"]) - self.assertNotIn("test-provider-parity", WORKFLOW.read_text()) + self.assertEqual([field(step, "name", indent=6) for step in saves], + ["Save .git for later runs", "Save verified MiMo metadata downloads", + "Cache verified MiMo audio codec"]) + self.assertNotIn("test-provider-parity", workflow_text()) for forbidden in ("coordinator/", "cargo ", "rust-key", "secrets.", "darkbloom-platform"): self.assertNotIn(forbidden, self.jobs["test-provider"]) def test_obsolete_self_consuming_cache_warmer_is_absent(self): # cache-swift saved a release build that only its own next run restored. self.assertNotIn("cache-swift", self.jobs) - self.assertNotIn("spm-v4-blacksmith-macos27-native-", WORKFLOW.read_text()) + self.assertNotIn("spm-v4-blacksmith-macos27-native-", workflow_text()) def test_offline_workflow_test_runs_in_release_integrity(self): self.assertIn("python3 provider-swift/Tests/test_protocol_fixture_resources.py", self.jobs["release-integrity"]) @@ -746,6 +700,174 @@ def test_offline_workflow_test_runs_in_release_integrity(self): self.assertIn("python3 scripts/test-provider-test-shards.py", self.jobs["release-integrity"]) self.assertIn("python3 scripts/test-native-gpu-ci.py", self.jobs["release-integrity"]) + def test_only_pushes_to_master_and_dev_save_caches(self): + # A pull request's entry is scoped to its merge ref, where nothing else + # restores it, and evicts its base branch's entries from the quota. + tests = WORKFLOW.read_text() + self.assertIn("\nenv:\n DARKBLOOM_RELEASE_ENVIRONMENT: prod\n", tests) + self.assertIn(SAVE_POLICY, tests.split("\njobs:\n", 1)[0]) + # CI (master)'s own jobs run only for master, so only master pushes save theirs. + self.assertIn(" SAVE_CACHES: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}\n", + MASTER_WORKFLOW.read_text().split("\njobs:\n", 1)[0]) + saves = [(job_id, field(step, "name", indent=6), field(step, "if")) + for job_id, job in self.jobs.items() for step in step_blocks(job) if "actions/cache/save@" in step] + self.assertTrue(saves) + for job_id, name, condition in saves: + with self.subTest(job=job_id, step=name): + self.assertIn(SAVE_CACHES + " && ", condition) + # The composite saves only when its caller passes the same switch. + action = ACTION.read_text() + self.assertIn(" save-caches:\n", action.split("\nruns:\n", 1)[0]) + self.assertIn("\n default: 'false'\nruns:\n", action) + composite = {field(step, "name", indent=4): field(step, "if", indent=6) + for step in step_blocks(action, indent=4) if "actions/cache/save@" in step} + self.assertEqual(set(composite), {"Save lane-specific Swift test build", "Save SwiftPM repositories", + "Save validated source-matched Metal cache"}) + for name, condition in composite.items(): + with self.subTest(step=name): + self.assertIn(SAVE_INPUT + " && ", condition) + calls = [step for job in self.jobs.values() for step in step_blocks(job) if field(step, "uses") == BUILD_ACTION] + # The provider shards, the two cluster runtime jobs and the push-only + # cache refresh, which builds the provider and the cluster lanes. + self.assertEqual(len(calls), 5) + for call in calls: + self.assertEqual(field(call, "save-caches", indent=10), "${{ env.SAVE_CACHES }}") + self.assertEqual(field(call, "strict-cache", indent=10), "${{ inputs.strict_cache }}") + + def test_master_restores_only_the_strict_cache_tier(self): + # Master runs (pushes and pull requests into master) restore only an + # entry of this exact recipe; dev may restore the looser tiers. + self.assertIn(" strict_cache: {type: boolean, default: false}\n", + WORKFLOW.read_text().split("\njobs:\n", 1)[0]) + self.assertIn(" strict_cache: true\n", MASTER_WORKFLOW.read_text()) + self.assertIn(" strict_cache: false\n", DEV_WORKFLOW.read_text()) + self.assertIn(" strict-cache:\n", ACTION.read_text().split("\nruns:\n", 1)[0]) + + def test_every_checkout_reuses_master_git_and_falls_back_to_a_cold_checkout(self): + # The tree lookup checks out only its script, and the gate the files of + # its CI plan checks (blobs on demand), both without the .git cache. + self.assertIn("sparse-checkout: scripts/ci-tested-tree.py", self.jobs["tested"]) + gate = self.jobs["provider-test-gate"] + self.assertEqual(gate.count("actions/checkout@"), 1) + self.assertIn(" filter: blob:none\n sparse-checkout: ${{ env.CHECKOUT_SPARSE }}\n", gate) + checkouts = {job_id: job for job_id, job in self.jobs.items() + if "actions/checkout@" in job and job_id not in ("tested", "provider-test-gate")} + self.assertEqual(set(checkouts), {"release-integrity", "docs", *LANES, "test-cluster", "test-cluster-gpu", + "test-cluster-focused", "refresh-caches"}) + for job_id, job in checkouts.items(): + with self.subTest(job=job_id): + steps = step_blocks(job) + self.assertEqual([field(step, "name", indent=6) for step in steps[:5]], list(GIT_CACHE_STEPS)) + day, restore, validate, checkout, save = steps[:5] + self.assertEqual(run_command(day).splitlines()[:3], ['day=$(date -u +%F)', 'echo "day=$day" >> "$GITHUB_OUTPUT"', + 'echo "month=${day%-*}" >> "$GITHUB_OUTPUT"']) + self.assertIn("command -v zstd >/dev/null && echo zstd || echo gzip", day) + # Full history never seeds, or is restored by, a shallow job. + family = ("git-full-v1" if job_id == "docs" else "git-v1") + "-${{ runner.os }}-" + # One entry per day and branch; restore the newest earlier day. + monthly = family + "${{ steps.git-day.outputs.month }}-" + self.assertEqual(field(restore, "uses"), CACHE_RESTORE) + self.assertEqual(field(restore, "path", indent=10), ".git") + self.assertEqual(field(restore, "key", indent=10), family + "${{ steps.git-day.outputs.day }}") + self.assertIn(f"restore-keys: |\n {monthly}\n {family}\n", restore) + # The validation cannot fail and nothing may continue on error: + # one ordinary checkout follows, and its failure fails the job. + self.assertEqual(run_command(validate), VALIDATE_GIT) + for step in (validate, checkout): + self.assertIsNone(field(step, "if")) + self.assertFalse(any("continue-on-error" in step for step in steps[:5])) + self.assertEqual(uses(checkout), CHECKOUT) + self.assertEqual(sum(uses(step) == CHECKOUT for step in steps), 1) + # Each job keeps its checkout options; a persisted token would + # be saved with .git/config. + sparse = ["sparse-checkout: ${{ env.CHECKOUT_SPARSE }}", "sparse-checkout-cone-mode: false"] + options = {"release-integrity": ["persist-credentials: false", *sparse], + "docs": ["fetch-depth: 0", "filter: blob:none", "persist-credentials: false"] + }.get(job_id, ["submodules: recursive", "persist-credentials: false", *sparse]) + self.assertEqual(checkout_options(checkout), options) + self.assertEqual(field(save, "if"), SAVE_CACHES + " && steps.git-cache.outputs.cache-hit != 'true'") + self.assertEqual(field(save, "uses"), CACHE_SAVE) + self.assertEqual(field(save, "path", indent=10), ".git") + self.assertEqual(field(save, "key", indent=10), "${{ steps.git-cache.outputs.cache-primary-key }}") + + def test_git_validation_keeps_healthy_and_partial_clones_and_discards_damage(self): + with tempfile.TemporaryDirectory() as work: + def git(cwd, *args): + return subprocess.run(["git", "-C", str(cwd), "-c", "user.name=t", "-c", "user.email=t@t", + "-c", "commit.gpgsign=false", "-c", "protocol.file.allow=always", *args], + check=True, capture_output=True, text=True).stdout.strip() + origin = Path(work, "origin") + origin.mkdir() + git(origin, "init", "-q") + for name in ("a", "b"): + (origin / name).write_text(name * 1000) + git(origin, "add", name) + git(origin, "commit", "-q", "-m", name) + git(origin, "config", "uploadpack.allowFilter", "true") + cases = {"healthy": True, "blobless": True, "damaged": False} + for case in cases: + options = ["--filter=blob:none", "--no-checkout"] if case == "blobless" else [] + git(work, "clone", "-q", *options, f"file://{origin}", case) + loose = Path(work, "damaged", ".git", "objects") + tree = git(Path(work, "damaged"), "rev-parse", "HEAD^{tree}") + git(Path(work, "damaged"), "repack", "-q", "-a", "-d") + for pack in (loose / "pack").glob("*.pack"): + pack.unlink() + Path(work, "empty").mkdir() + for case, kept in {**cases, "empty": False}.items(): + with self.subTest(case=case): + result = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", VALIDATE_GIT], + cwd=Path(work, case), capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(Path(work, case, ".git").is_dir(), kept, result.stdout) + self.assertEqual("::warning" in result.stdout, case == "damaged") + self.assertTrue(tree) + + def test_sparse_checkouts_skip_only_evidence_tarballs_and_landing_media(self): + for path in (WORKFLOW, MASTER_WORKFLOW): + with self.subTest(workflow=path.name): + env = path.read_text().split("\njobs:\n", 1)[0] + self.assertIn(" CHECKOUT_SPARSE: |\n" + "".join(f" {pattern}\n" for pattern in SPARSE_PATTERNS), + env) + # The 6 build and test checkouts, and the gate's for its CI plan checks. + self.assertEqual(self.workflow.count("sparse-checkout: ${{ env.CHECKOUT_SPARSE }}"), 7) + docs_impact = (ROOT / ".github/workflows/docs-impact.yml").read_text() + self.assertIn(" filter: blob:none\n sparse-checkout: |\n" + + "".join(f" {pattern}\n" for pattern in SPARSE_PATTERNS) + + " sparse-checkout-cone-mode: false\n", docs_impact) + # Real git decides what the patterns keep: every file a job may read, + # including the report a provider test hashes and the evidence harness + # manifest the provider CI cache hashes, but no evidence tarball or media. + kept = ["Makefile", "docs/reports/report.md", "docs/reports/archive.tar.gz", + "docs/reports/evidence/run/cpu-harness/Package.swift", "docs/reports/evidence/notes.json", + "provider-swift/Tests/Fixtures/clip.mp4", "fixtures/data.gz", "landing/src/page.tsx", + "landing/README.md", "landing/public/favicon.svg", + "docs/reports/2026-10-31-public-cluster-models.md"] + skipped = ["docs/reports/evidence/run/packets.jsonl.gz", "docs/reports/evidence/payloads.tar.gz", + "landing/public/media/demo.mp4", "landing/public/media/poster.png"] + with tempfile.TemporaryDirectory() as work: + def git(*args): + subprocess.run(["git", "-C", work, "-c", "user.name=t", "-c", "user.email=t@t", + "-c", "commit.gpgsign=false", *args], check=True, capture_output=True) + git("init", "-q") + for path in kept + skipped: + (Path(work) / path).parent.mkdir(parents=True, exist_ok=True) + (Path(work) / path).write_text(path) + git("add", "-A") + git("commit", "-q", "-m", "tree") + git("sparse-checkout", "set", "--no-cone", *SPARSE_PATTERNS) + self.assertEqual([path for path in kept if not (Path(work) / path).is_file()], []) + self.assertEqual([path for path in skipped if (Path(work) / path).exists()], []) + self.assertTrue((ROOT / "docs/reports/2026-10-31-public-cluster-models.md").is_file()) + # scripts/provider-ci-cache.py hashes every tracked Package.swift, + # Package.resolved and .gitmodules; the patterns must keep each one. + tracked = subprocess.run(["git", "-C", str(ROOT), "ls-files", "-z"], check=True, + capture_output=True, text=True).stdout.split("\0") + manifests = [path for path in tracked if Path(path).name in {"Package.swift", "Package.resolved", ".gitmodules"}] + self.assertIn("docs/reports/evidence/ssd-read-coordination-runtime-2026-09-06/cpu-harness/Package.swift", manifests) + self.assertEqual([path for path in manifests + if path.endswith(".gz") or path.startswith("landing/public/media/")], []) + def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): action = ACTION.read_text() self.assertIn("using: composite", action) @@ -754,23 +876,18 @@ def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): steps = step_blocks(action, indent=4) by_id = {field(step, "id", indent=6): step for step in steps if field(step, "id", indent=6)} provider = by_id["provider-build"] - sdk = by_id["sdk-build"] cluster = by_id["cluster-build"] metallib = by_id["metallib"] self.assertEqual(field(provider, "if", indent=6), "inputs.lane == 'provider'") self.assertEqual(field(provider, "working-directory", indent=6), "provider-swift") self.assertIn("swift build --build-tests", provider) self.assertIn("swift build --product darkbloom-fan-helper", provider) - self.assertEqual(field(sdk, "if", indent=6), "inputs.lane == 'sdk'") - self.assertEqual(field(sdk, "working-directory", indent=6), "libs/mlx-swift-lm") - self.assertIn("swift package edit --path ../mlx-swift mlx-swift", sdk) - self.assertIn("swift build --build-tests", sdk) self.assertEqual(field(cluster, "if", indent=6), "inputs.lane == 'cluster'") self.assertEqual(field(cluster, "working-directory", indent=6), "libs/darkbloom-cluster") self.assertIn("swift build --build-tests", cluster) self.assertIsNone(field(metallib, "if", indent=6)) self.assertIn('./scripts/stage-test-metallib.sh "$bin"', metallib) - for step in (provider, sdk, cluster, metallib): + for step in (provider, cluster, metallib): self.assertNotIn("--filter", step) self.assertNotIn("--skip", step) self.assertNotIn("cache-hit", step) @@ -780,8 +897,28 @@ def test_composite_cache_keys_retain_swift_and_metal_without_backend_work(self): steps = step_blocks(action, indent=4) by_id = {field(step, "id", indent=6): step for step in steps if field(step, "id", indent=6)} swift_cache = by_id["swift-cache"] - self.assertIn("key: ${{ steps.keys.outputs.swift-key }}", swift_cache) - self.assertIn("restore-keys: ${{ steps.keys.outputs.swift-prefix }}", swift_cache) + self.assertIn("key: ${{ steps.build-key.outputs.key }}", swift_cache) + # This recipe's entries first, then any recipe's with the same toolchain, + # dependencies and checkout path, then any with the same MLX pins. + # With strict-cache (master), only this recipe's entries: the looser + # tiers evaluate to empty lines, which actions/cache ignores. + self.assertIn("restore-keys: |\n ${{ steps.keys.outputs.swift-prefix }}\n" + " ${{ inputs.strict-cache != 'true' && steps.keys.outputs.swift-loose-prefix || '' }}\n" + " ${{ inputs.strict-cache != 'true' && steps.keys.outputs.swift-mlx-prefix || '' }}\n", + swift_cache) + self.assertIn("strict-cache:\n", action.split("\nruns:\n", 1)[0]) + save = next(step for step in steps if field(step, "name", indent=4) == "Save lane-specific Swift test build") + self.assertIn("key: ${{ steps.build-key.outputs.key }}", save) + # Every build step builds once more from nothing only through the retry + # helper, which reads the matched key and this recipe's prefix. + for step_id in ("provider-build", "cluster-build"): + with self.subTest(step=step_id): + step = by_id[step_id] + self.assertIn("provider-ci-cold-retry.sh && ", step) + self.assertEqual(field(step, "PROVIDER_CI_MATCHED_KEY", indent=8), + "${{ steps.swift-cache.outputs.cache-matched-key }}") + self.assertEqual(field(step, "PROVIDER_CI_STRICT_PREFIX", indent=8), + "${{ steps.keys.outputs.swift-prefix }}") metal_cache = by_id["metallib-cache"] self.assertIn("key: ${{ steps.keys.outputs.metallib-key }}", metal_cache) self.assertNotIn("restore-keys:", metal_cache) @@ -790,14 +927,66 @@ def test_composite_cache_keys_retain_swift_and_metal_without_backend_work(self): self.assertEqual(rust_steps, []) self.assertNotIn("rust-key:", action) self.assertNotIn("rust-cache-hit:", action) - self.assertEqual(sum("actions/cache/save@" in step for step in steps), 2) - # Pushes save the Swift build. A pull request saves it only when it - # restored nothing, so its later pushes do not evict the base entry. - swift_save = next(step for step in steps if field(step, "name", indent=4) == "Save lane-specific Swift test build") - self.assertEqual(field(swift_save, "if", indent=6), - "${{ !cancelled() && steps.timestamps.outcome == 'success' && " - "steps.swift-cache.outputs.cache-hit != 'true' && (github.event_name != 'pull_request' " - "|| steps.swift-cache.outputs.cache-matched-key == '') }}") + self.assertEqual(sum("actions/cache/save@" in step for step in steps), 3) + + def test_darkbloom_hosts_save_one_build_per_lane_and_day(self): + steps = step_blocks(ACTION.read_text(), indent=4) + step = next(step for step in steps if field(step, "id", indent=6) == "build-key") + script = textwrap.dedent(step.split("run: |\n", 1)[1]) + day = time.strftime("%Y-%m-%d", time.gmtime()) + for runner, expected in (("darkbloom-5ab1e68d", f"prefix-day-{day}"), ("blacksmith-12vcpu-macos-27-x", "prefix-commit"), + ("", "prefix-commit")): + with self.subTest(runner=runner), tempfile.TemporaryDirectory() as work: + output = Path(work) / "output" + result = subprocess.run(["bash", "-eo", "pipefail", "-c", script], text=True, capture_output=True, + env={"PATH": os.environ["PATH"], "RUNNER_NAME": runner, + "PREFIX": "prefix-", "COMMIT_KEY": "prefix-commit", + "GITHUB_OUTPUT": str(output)}, timeout=30) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(output.read_text(), f"key={expected}\n") + + def test_cold_retry_deletes_only_a_loose_tier_build(self): + helper = ROOT / "scripts/provider-ci-cold-retry.sh" + builds = ("provider-swift/.build", "libs/darkbloom-cluster/.build") + for matched, retries in (("", False), ("strict-abc-commit", False), ("strict-abc-day-2026-11-04", False), + ("strict-other-commit", True)): + with self.subTest(matched=matched), tempfile.TemporaryDirectory() as work: + for build in builds: + Path(work, build).mkdir(parents=True) + result = subprocess.run(["bash", str(helper)], text=True, capture_output=True, timeout=30, + env={"PATH": os.environ["PATH"], "GITHUB_WORKSPACE": work, + "PROVIDER_CI_MATCHED_KEY": matched, + "PROVIDER_CI_STRICT_PREFIX": "strict-abc-"}) + self.assertEqual(result.returncode, 0 if retries else 1, result.stdout + result.stderr) + self.assertEqual([Path(work, build).exists() for build in builds], [not retries] * len(builds)) + self.assertEqual("::warning title=Build cache::" in result.stdout, retries) + + def test_composite_restores_swiftpm_repositories_per_lane_and_runner_layout(self): + steps = step_blocks(ACTION.read_text(), indent=4) + by_id = {field(step, "id", indent=6): step for step in steps if field(step, "id", indent=6)} + names = [field(step, "name", indent=4) for step in steps] + restore = by_id["spm-repos"] + save = next(step for step in steps if field(step, "name", indent=4) == "Save SwiftPM repositories") + # actions/cache archives this home path relative to the workspace, so + # the key binds the runner layout as well as the lane and the pins. + self.assertIn('echo "home-layout=$(printf \'%s\\n\' "$HOME" "$GITHUB_WORKSPACE" | shasum -a 256', + by_id["keys"]) + self.assertIn("command -v zstd >/dev/null && echo zstd || echo gzip", by_id["keys"]) + prefix = "spm-repos-v1-${{ runner.os }}-${{ steps.keys.outputs.home-layout }}-${{ inputs.lane }}-" + for step in (restore, save): + self.assertEqual(field(step, "path", indent=8), "~/Library/Caches/org.swift.swiftpm/repositories") + self.assertEqual(field(restore, "uses", indent=6), CACHE_RESTORE) + self.assertEqual(field(restore, "key", indent=8), + prefix + "${{ hashFiles('**/Package.resolved', '!**/.build/**') }}") + self.assertEqual(field(restore, "restore-keys", indent=8), prefix) + self.assertLess(steps.index(restore), steps.index(by_id["provider-build"])) + self.assertLess(steps.index(restore), steps.index(by_id["cluster-build"])) + self.assertEqual(field(save, "uses", indent=6), CACHE_SAVE) + self.assertEqual(field(save, "key", indent=8), "${{ steps.spm-repos.outputs.cache-primary-key }}") + self.assertEqual(field(save, "if", indent=6), + "${{ !cancelled() && " + SAVE_INPUT + " && steps.timestamps.outcome == 'success' " + "&& steps.spm-repos.outputs.cache-hit != 'true' }}") + self.assertGreater(names.index("Save SwiftPM repositories"), names.index("Record timestamps for successfully built sources")) if __name__ == "__main__": diff --git a/scripts/test-provider-release-toolchain.py b/scripts/test-provider-release-toolchain.py index 4dc52be897..6af461df80 100644 --- a/scripts/test-provider-release-toolchain.py +++ b/scripts/test-provider-release-toolchain.py @@ -2,6 +2,7 @@ """Exercise toolchain selection/argument propagation without installing software.""" import json import os +import shutil from pathlib import Path import subprocess import tempfile @@ -61,5 +62,59 @@ def test_old_swift_cannot_select_sdk_27(self): self.assertFalse((self.root / "env").exists()) + +class ReleaseCMakeTests(unittest.TestCase): + """The image's tool-cache CMake is used when complete and exact; otherwise download.""" + + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="release cmake ") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + stubs = self.root / "bin" + stubs.mkdir() + # An Apple Silicon Mac whose network refuses, recording each download. + (stubs / "uname").write_text('#!/bin/sh\ncase "$1" in -s) echo Darwin ;; -m) echo arm64 ;; esac\n') + (stubs / "curl").write_text(f'#!/bin/sh\necho "$@" >> "{self.root}/curl.log"\nexit 7\n') + for stub in stubs.iterdir(): + stub.chmod(0o755) + self.cache = self.root / "toolcache" + self.env = {**os.environ, "PATH": f"{stubs}:{os.environ['PATH']}", "RUNNER_TOOL_CACHE": str(self.cache), + "RUNNER_TEMP": str(self.root), "GITHUB_PATH": str(self.root / "path")} + + def provision(self, version="3.31.12", complete=True): + cmake = self.cache / "cmake/3.31.12/universal/CMake.app/Contents/bin/cmake" + cmake.parent.mkdir(parents=True) + cmake.write_text(f"#!/bin/sh\necho 'cmake version {version}'\n") + cmake.chmod(0o755) + if complete: + (self.cache / "cmake/3.31.12/universal.complete").touch() + return cmake.parent + + def install(self): + return subprocess.run([str(ROOT / "scripts/install-release-cmake.sh")], env=self.env, + text=True, capture_output=True) + + def test_uses_the_complete_exact_tool_cache_copy_without_downloading(self): + cached = self.provision() + result = self.install() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.root / "path").read_text(), f"{cached}\n") + self.assertFalse((self.root / "curl.log").exists()) + + def test_downloads_when_the_tool_cache_copy_is_absent_incomplete_or_another_version(self): + for case in ("absent", "incomplete", "another version"): + with self.subTest(case=case): + shutil.rmtree(self.cache, ignore_errors=True) + for leftover in ("curl.log", "path"): + (self.root / leftover).unlink(missing_ok=True) + if case != "absent": + self.provision(version="3.30.0" if case == "another version" else "3.31.12", + complete=case != "incomplete") + result = self.install() + # The refused download fails the step; nothing reaches PATH. + self.assertEqual(result.returncode, 7, result.stderr) + self.assertIn("/v3.31.12/cmake-3.31.12-macos-universal.tar.gz", (self.root / "curl.log").read_text()) + self.assertFalse((self.root / "path").exists()) + if __name__ == "__main__": unittest.main() diff --git a/scripts/test-provider-test-shards.py b/scripts/test-provider-test-shards.py index 5291fb2d80..52af33580e 100755 --- a/scripts/test-provider-test-shards.py +++ b/scripts/test-provider-test-shards.py @@ -141,6 +141,26 @@ def test_longest_suites_spread_over_the_shards(self): self.assertEqual(loads, [shards.FIRST_SHARD_EXTRA_SECONDS + shards.PARITY_SHARD_EXTRA_SECONDS + shards.LAST_SHARD_EXTRA_SECONDS]) + def test_job_level_extras_load_every_selection_of_their_job(self): + first, parity, last = (shards.FIRST_SHARD_EXTRA_SECONDS, shards.PARITY_SHARD_EXTRA_SECONDS, + shards.LAST_SHARD_EXTRA_SECONDS) + # One selection per job: the extras sit on selections 1, PARITY_SHARD and N. + _, loads = shards.assignment(6, {}) + self.assertEqual(loads, [first, parity, 0.0, 0.0, 0.0, last]) + # Three per job: Prompt Parity runs after job 1's processes and the + # isolated processes after job 2's, so they load each selection there. + _, loads = shards.assignment(6, {}, processes=3) + self.assertEqual(loads, [first + parity, parity, parity, last, last, last]) + with self.assertRaisesRegex(ValueError, "do not make jobs"): + shards.assignment(5, {}, processes=3) + # Every listed test still runs in exactly one selection of a job plan + # (2 jobs of 2 processes: this fixture has 5 serial suites). + plans = {selection: shards.planned(self.tests, selection, ISOLATED, self.weights, 2) + for selection in ("parallel", *(f"{index}/4" for index in range(1, 5)))} + selected = [test for plan in plans.values() for test in plan] + self.assertEqual(len(selected), len(set(selected))) + self.assertEqual(set(selected), {test for test in self.tests if not re.search(ISOLATED, test)}) + def test_arguments_and_shard_validation(self): self.assertEqual(shards.arguments("parallel", ISOLATED, self.weights), ["--filter", shards.parallel_regex(), "--skip", ISOLATED]) @@ -193,6 +213,41 @@ def test_counts_read_both_frameworks_and_failures(self): with self.assertRaisesRegex(ValueError, "zero tests"): shards.counts("✔ Test run with 0 tests passed after 0.001 seconds.") + def test_each_job_audits_its_own_selections_and_the_last_the_whole_plan(self): + # Seconds well above the fixed extra seconds, so each of the 4 + # selections gets a suite. + weights = {"ProviderCoreTests.A": 300.0, "ProviderCoreTests.B": 250.0, "ProviderCoreTests.C": 200.0, + "ProviderCoreTests.D": 150.0} + tests = ["ProviderCoreTests.A/a()", "ProviderCoreTests.B/b()", "ProviderCoreTests.C/c()", + "ProviderCoreTests.D/x()", + "ProviderCoreTests.New/d()", "ProviderCoreTests.ProcessMemoryNativeIntegrationTests/e()", + "ProviderCoreFoundationTests.Pure/f()", "ProviderCoreTests.ProductionPromptParityTests/p()", + "ProviderCoreTests.NemotronTemplateParityLiveTests/n()"] + parity = [{"shard": "parity", "pattern": name, "swift_testing": 1, "xctest": 0} + for name in ("ProductionPromptParityTests", "NemotronTemplateParityLiveTests")] + + def own(selections, processes=2, **changed): + return [{"shard": selection, "pattern": ISOLATED, "processes": processes, "xctest": 0, + "swift_testing": changed.get(selection, len(shards.planned(tests, selection, ISOLATED, + weights, processes)))} + for selection in selections] + + # 2 jobs of 2 processes: job 1 runs the parallel class, 1/4, 2/4 and + # Prompt Parity (PARITY_SHARD 2); job 2 runs 3/4 and 4/4. + first, second = own(("parallel", "1/4", "2/4")) + parity, own(("3/4", "4/4")) + self.assertEqual(shards.audit_job(tests, first, ISOLATED, weights, 1, 2, 2), []) + self.assertEqual(shards.audit_job(tests, second, ISOLATED, weights, 2, 2, 2), []) + # A selection that ran one test too few, a missing one, parity in the + # wrong job, or a report planned for another process count fails. + self.assertTrue(shards.audit_job(tests, own(("3/4", "4/4"), **{"4/4": 0}), ISOLATED, weights, 2, 2, 2)) + self.assertTrue(shards.audit_job(tests, own(("3/4",)), ISOLATED, weights, 2, 2, 2)) + self.assertTrue(shards.audit_job(tests, second + parity, ISOLATED, weights, 2, 2, 2)) + self.assertTrue(shards.audit_job(tests, own(("parallel", "1/4", "2/4")), ISOLATED, weights, 1, 2, 2)) + self.assertTrue(shards.audit_job(tests, own(("3/4", "4/4"), processes=1), ISOLATED, weights, 2, 2, 2)) + # Every test is in exactly one plan, so the job audits add up to the + # full-suite audit over all of the reports. + self.assertEqual(shards.audit(tests, first + second, ISOLATED, weights, 2), []) + def test_audit_requires_every_shard_to_run_its_plan_and_the_sum_to_match(self): weights = {"ProviderCoreTests.A": 10.0, "ProviderCoreTests.B": 10.0} tests = ["ProviderCoreTests.A/a()", "ProviderCoreTests.A/b()", "ProviderCoreTests.B/c()", @@ -243,37 +298,107 @@ def test_weights_sum_xunit_cases_per_top_level_suite(self): '' '') self.assertEqual(shards.measured_weights([path]), {"ProviderCoreTests.A": 2.0}) + # A retried selection's first attempt never counts twice. + first = Path(temporary) / "attempt-1-shard-1-of-2.xml" + first.write_text(path.read_text()) + self.assertEqual(shards.measured_weights([path, first]), {"ProviderCoreTests.A": 2.0}) # XCTest classes have no serial xUnit report; they keep their old seconds. base = {"ProviderCoreTests.A": 7.0, "ProviderCoreTests.XCTestClass": 3.0} self.assertEqual(shards.measured_weights([path], base), {"ProviderCoreTests.A": 2.0, "ProviderCoreTests.XCTestClass": 3.0}) +_LOCK_SPEC = importlib.util.spec_from_file_location("swift_test_lock_retry", ROOT / "scripts/swift_test_lock_retry.py") +lock_retry = importlib.util.module_from_spec(_LOCK_SPEC) +_LOCK_SPEC.loader.exec_module(lock_retry) + + +class LockRetryTests(unittest.TestCase): + """Only a log whose every test passed, beside the lock message, runs again.""" + + LOCKED = ('error: unable to attach DB: error: accessing build database "/Users/runner/_work/d-inference/' + 'd-inference/provider-swift/.build/build.db": database is locked Possibly there are two ' + 'concurrent builds running in the same filesystem location.\n') + XCTEST = "\t Executed 54 tests, with 8 tests skipped and 0 failures (0 unexpected) in 7.575 (7.581) seconds\n" + PASSED = "\u2714 Test run with 940 tests in 126 suites passed after 164.700 seconds.\n" + + def test_lock_and_every_test_passed_runs_again(self): + # Run 41970825476, selection 1-of-6: the lock, then passing summaries. + self.assertTrue(lock_retry.only_locked(self.LOCKED + self.XCTEST + self.PASSED)) + self.assertTrue(lock_retry.only_locked(self.LOCKED + "Test run with 1 test passed after 0.1 seconds.\n")) + + def test_any_failure_or_missing_proof_does_not_run_again(self): + cases = { + "no lock": self.XCTEST + self.PASSED, + "no Swift Testing summary": self.LOCKED + self.XCTEST, + "an XCTest failure": self.LOCKED + self.XCTEST.replace("0 failures (0", "1 failure (1") + self.PASSED, + "an XCTest case failed": self.LOCKED + "Test Case '-[A b]' failed (0.1 seconds).\n" + self.PASSED, + "a Swift Testing issue": self.LOCKED + "\u2718 Test b() recorded an issue at A.swift:3:5\n" + self.PASSED, + "a failed run": self.LOCKED + "\u2718 Test run with 2 tests failed after 0.1 seconds with 1 issue.\n", + "a tripwire": self.LOCKED + self.PASSED + "::error::filter executed ZERO tests\n", + } + for name, text in cases.items(): + with self.subTest(case=name): + self.assertFalse(lock_retry.only_locked(text)) + + class RunnerTests(unittest.TestCase): """run-provider-tests.sh with a recording `swift` in place of the toolchain.""" - def run_tests(self, shard=None): + def run_tests(self, shard=None, processes=None, status=0, **stub): temporary = tempfile.TemporaryDirectory(prefix="provider-shard-runner-") self.addCleanup(temporary.cleanup) root = Path(temporary.name) - calls = root / "calls.jsonl" + calls, environments = root / "calls.jsonl", root / "environments.jsonl" swift = root / "swift" swift.write_text(textwrap.dedent("""\ #!/usr/bin/env python3 import json, os, sys with open(os.environ["STUB_CALLS"], "a") as calls: calls.write(json.dumps(sys.argv[1:]) + "\\n") - print("Test run with 2 tests in 1 suite passed after 0.1 seconds.") + with open(os.environ["STUB_ENVIRONMENTS"], "a") as environments: + environments.write(json.dumps({name: os.environ.get(name) for name in ( + "TMPDIR", "DARKBLOOM_STATE_FILE", "DARKBLOOM_LOADED_MODELS_FILE", + "DARKBLOOM_VERIFIED_WEIGHTS_FILE")}) + "\\n") + # STUB_LOCKED=once: the first run of each selection finds the build + # database locked, as SwiftPM reports it, passes its tests and + # exits 1. STUB_LOCKED=always: every run does. STUB_LOCKED=failed: + # the first run finds it locked and a test fails. + mode = os.environ.get("STUB_LOCKED") + report = sys.argv[sys.argv.index("--xunit-output") + 1] if "--xunit-output" in sys.argv else "" + seen = report + ".seen" + first = bool(report) and not os.path.exists(seen) + locked = mode == "always" or (mode in ("once", "failed") and first) + if report: + open(seen, "a").close() + open(report, "w").write(f"") + if locked: + print('error: unable to attach DB: error: accessing build database "/x/.build/build.db": ' + 'database is locked Possibly there are two concurrent builds running in the same ' + 'filesystem location.') + if locked and mode == "failed": + print('✘ Test "contended" recorded an issue at A.swift:1:1: Expectation failed') + print("✘ Test run with 2 tests in 1 suite failed after 0.1 seconds with 1 issue.") + else: + print("Test run with 2 tests in 1 suite passed after 0.1 seconds.") + sys.exit(1 if locked else 0) """)) swift.chmod(0o755) environment = {**os.environ, "PATH": f"{root}{os.pathsep}{os.environ['PATH']}", - "STUB_CALLS": str(calls), "TMPDIR": str(root)} + "STUB_CALLS": str(calls), "STUB_ENVIRONMENTS": str(environments), "TMPDIR": str(root), + "PROVIDER_TEST_START_GAP": "0", **stub} environment.pop("PROVIDER_TEST_SHARD", None) + environment.pop("PROVIDER_TEST_PROCESSES", None) if shard: environment.update(PROVIDER_TEST_SHARD=shard, PROVIDER_TEST_REPORT_DIR=str(root / "reports")) + if processes is not None: + environment["PROVIDER_TEST_PROCESSES"] = processes result = subprocess.run(["bash", str(ROOT / "scripts/run-provider-tests.sh")], cwd=root, env=environment, text=True, capture_output=True, timeout=60) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.returncode, status, result.stdout + result.stderr) + if status: + return result + self.environments = [json.loads(line) for line in environments.read_text().splitlines()] return [json.loads(line) for line in calls.read_text().splitlines()], root / "reports" def test_unsharded_run_is_one_serial_suite_and_every_isolated_process(self): @@ -307,5 +432,73 @@ def test_last_shard_runs_the_catch_all_and_every_isolated_process(self): self.assertNotIn("--filter", calls[0]) + def selection_of(self, call): + """The selection a recorded `swift test` call ran, from its xUnit report name.""" + return call[call.index("--xunit-output") + 1].rsplit("/shard-", 1)[1].removesuffix(".xml") + + def test_one_process_keeps_the_single_selection_command_line(self): + calls, _ = self.run_tests("2/4", processes="1") + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0][:4], ["test", "--skip-build", "--no-parallel", "--filter"]) + + def test_processes_run_their_selections_beside_each_other_with_their_own_files(self): + calls, reports = self.run_tests("1/2", processes="3") + # Job 1 of 2 with 3 processes runs selections 1 to 3 of 6, and selection + # 1's process also runs the parallel class; no isolated process runs. + self.assertEqual(sorted(self.selection_of(call) for call in calls), + ["1-of-6", "2-of-6", "3-of-6", "parallel"]) + for call in calls: + self.assertEqual(call[:3], ["test", "--skip-build", "--ignore-lock"]) + for name in ("1-of-6", "2-of-6", "3-of-6", "parallel"): + self.assertTrue((reports / f"shard-{name}.json").is_file(), name) + # Each process has its own TMPDIR and state files; the parallel class + # shares selection 1's, as it runs after it in the same slot. + directories = {environment["TMPDIR"] for environment in self.environments} + states = {environment["DARKBLOOM_STATE_FILE"] for environment in self.environments} + self.assertEqual(len(directories), 3) + self.assertEqual(len(states), 3) + for environment in self.environments: + self.assertTrue(environment["DARKBLOOM_STATE_FILE"].startswith(str(Path(environment["TMPDIR"]).parent))) + + def test_last_job_runs_its_selections_then_every_isolated_process_alone(self): + calls, reports = self.run_tests("2/2", processes="3") + self.assertEqual(sorted(self.selection_of(call) for call in calls[:3]), ["4-of-6", "5-of-6", "6-of-6"]) + catch_all = next(call for call in calls[:3] if self.selection_of(call) == "6-of-6") + self.assertNotIn("--filter", catch_all) + # The isolated processes and the exclusive GPU test run after all + # selections, one at a time, without the lock override. + self.assertEqual(len(calls), 3 + 9) + for call in calls[3:]: + self.assertNotIn("--ignore-lock", call) + self.assertEqual(len({environment["TMPDIR"] for environment in self.environments[3:]}), 1) + + def test_a_selection_that_finds_the_build_database_locked_runs_once_more(self): + # Beside other processes, SwiftPM's startup can find build.db locked; + # it runs the tests and exits 1. The selection runs once more. + calls, reports = self.run_tests("1/2", processes="3", STUB_LOCKED="once") + self.assertEqual(sorted(self.selection_of(call) for call in calls), + sorted(["1-of-6", "2-of-6", "3-of-6", "parallel"] * 2)) + # The first attempt's log and xUnit report stay beside the second's. + for name in ("1-of-6", "2-of-6", "3-of-6", "parallel"): + self.assertIn("database is locked", (reports / f"attempt-1-shard-{name}.log").read_text()) + self.assertIn("attempt 1", (reports / f"attempt-1-shard-{name}.xml").read_text()) + self.assertIn("attempt 2", (reports / f"shard-{name}.xml").read_text()) + self.assertNotIn("database is locked", (reports / f"shard-{name}.log").read_text()) + # A test that failed beside the lock fails the job: no second attempt. + result = self.run_tests("1/2", processes="3", STUB_LOCKED="failed", status=1) + self.assertIn("Expectation failed", result.stdout) + self.assertNotIn("running the selection once more", result.stdout) + # Only once: a second lock fails the job. + self.run_tests("1/2", processes="3", STUB_LOCKED="always", status=1) + # One process has no other process to meet: no retry. + self.run_tests("2/4", processes="1", STUB_LOCKED="once", status=1) + + def test_invalid_job_or_process_count_refuses_before_any_test(self): + for shard, processes in (("3/2", "3"), ("0/2", "3"), ("1/2", "0"), ("1/2", "10"), ("1/2", "x"), ("x", "1")): + with self.subTest(shard=shard, processes=processes): + result = self.run_tests(shard, processes=processes, status=2) + self.assertIn("PROVIDER_TEST_SHARD must be K/N", result.stderr) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/verified_download_cache.py b/scripts/verified_download_cache.py new file mode 100644 index 0000000000..f69139d44c --- /dev/null +++ b/scripts/verified_download_cache.py @@ -0,0 +1,28 @@ +"""A content-addressed cache of pinned downloads for the fixture scripts. + +`cached(fetch, cache, pin)` wraps `fetch(name)`. An entry is named by the +SHA-256 that `pin(name)` returns and is used only when its bytes still have +that digest; otherwise `fetch` runs and its bytes replace the entry only when +they have the digest. The caller still checks every result it receives. +""" + +import hashlib +import os + + +def cached(fetch, cache, pin): + def fetch_cached(name): + digest = pin(name) + entry = cache / digest + if entry.is_file() and not entry.is_symlink(): + data = entry.read_bytes() + if hashlib.sha256(data).hexdigest() == digest: + return data + data = fetch(name) + if hashlib.sha256(data).hexdigest() == digest: + cache.mkdir(parents=True, exist_ok=True) + temporary = cache / f".{digest}.{os.getpid()}" + temporary.write_bytes(data) + temporary.replace(entry) + return data + return fetch_cached