diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 0adbe70dfe..946862daf7 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -2,7 +2,7 @@ name: Provider CI Build description: Build full debug test products with lane-specific caches and source-matched Metal inputs: lane: - description: provider or sdk; each owns independent build outputs + description: provider, sdk or cluster; each owns independent build outputs required: true runs: using: composite @@ -13,7 +13,7 @@ runs: LANE: ${{ inputs.lane }} run: | case "$LANE" in - provider|sdk) ;; + provider|sdk|cluster) ;; *) echo "Unknown provider CI lane: $LANE" >&2; exit 2 ;; esac - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 @@ -41,13 +41,14 @@ runs: 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 }} - 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; do + for root in provider-swift/.build libs/mlx-swift-lm/.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 \ @@ -72,8 +73,14 @@ runs: swift package unedit --force mlx-swift >/dev/null 2>&1 || true swift package edit --path ../mlx-swift mlx-swift swift build --build-tests + - 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 - name: Record timestamps for successfully built sources - if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success') }} + if: ${{ !cancelled() && (steps.provider-build.outcome == 'success' || steps.sdk-build.outcome == 'success' || steps.cluster-build.outcome == 'success') }} id: timestamps shell: bash run: python3 scripts/provider-release-cache.py snapshot-mtimes @@ -84,6 +91,7 @@ runs: path: | provider-swift/.build libs/mlx-swift-lm/.build + libs/darkbloom-cluster/.build key: ${{ steps.keys.outputs.swift-key }} - name: Restore source-matched Metal cache id: metallib-cache @@ -99,11 +107,12 @@ runs: METALLIB_CACHE_DIR: ${{ runner.temp }}/metallib-cache run: | cmake --version - if [ "$LANE" = sdk ]; then - bin=$(swift build --package-path libs/mlx-swift-lm --show-bin-path) - else - bin=$(swift build --package-path provider-swift --show-bin-path) - fi + 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' }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d16d575f9c..e94669ff67 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,12 @@ jobs: 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.provider == 'true' && 1 || 0 }} + test-cluster-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-gpu-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-gpu-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} + test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.changes.outputs.provider == 'true' && 1 || 0 }} release-integrity: name: Release Integrity @@ -80,6 +86,7 @@ jobs: 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 @@ -737,6 +744,14 @@ jobs: DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS: '12' DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT: ${{ runner.temp }}/cluster-native-metadata run: bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh + # Builds the bootstrap product beside the capability runner's, in the same + # retained build, before the steps below record and save it. + - name: Run prefill schedule checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + env: + 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 - name: Record source timestamps for the cluster build if: ${{ !cancelled() && steps.capability-checks.outcome == 'success' && steps.cluster-build-cache.outputs.cache-hit != 'true' }} run: | @@ -767,10 +782,92 @@ jobs: 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.provider == '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.provider == '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.provider == '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 + run: python3 scripts/cluster-test-plan.py run focused 1 + provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 - needs: [changes, test-provider, test-provider-summary] + needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused] if: ${{ always() }} steps: - name: Require selected provider lanes or verified intentional skips @@ -779,6 +876,8 @@ jobs: PROVIDER_CHANGED: ${{ needs.changes.outputs.provider }} 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 case "$PROVIDER_CHANGED" in @@ -788,6 +887,8 @@ jobs: esac test "$UNIT_RESULT" = "$expected" test "$SUMMARY_RESULT" = "$expected" + test "$CLUSTER_RESULT" = "$expected" + test "$CLUSTER_FOCUSED_RESULT" = "$expected" cache-swift: name: Swift Build + Cache diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 6237619913..e88b79d945 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -145,6 +145,12 @@ local, starts at its installed default width ([Gemma pipeline lanes](#gemma-pipeline-lanes)); on a local pair this policy can still widen it. Explicit diagnostic mode or lane settings retain their choice. +A stage's resident prefix tier takes half the room that LOAD measures beside +its quote, in 256 MiB steps, up to a ceiling of a thirty-second of the Mac's +memory (`QwenStagePrefixCache.budget(roomBytes:maximumBytes:)`, and the idle +refresh `refreshBudget`). The ceiling is the Mac's own: `maximumBytes` +defaults to it. + Automatic replacement reads the installed plan helper's device profile and the current pair's recorded keyed-link costs and served-request history. It uses the same measurement readers as initial placement, so a supported TP batch diff --git a/docs/developer/test.md b/docs/developer/test.md index 94e1791500..34f8451e18 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-11-01 +> Last updated: 2026-11-03 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1174,13 +1174,16 @@ 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 five of them on every pull request that +Checks, `.github/workflows/ci.yml`) runs these runners on every pull request that changes provider code: `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 -last one runs the provisioning checks only. Its download cache-policy check +job `test-cluster-focused` (Cluster Focused Checks) runs 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 `F_NOCACHE` stayed resident. Run `run.sh` with no argument on a Mac for that @@ -1188,10 +1191,28 @@ check. The capability runner compiles with `DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS` jobs (4 by default; CI uses 12). CI keeps its build in `DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT` between runs and restores source timestamps only for unchanged files, so SwiftPM rebuilds only -what changed. The library's XCTest targets -(`swift test --package-path libs/darkbloom-cluster`) and 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. +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. + +CI runs the runtime test target (`DarkbloomClusterRuntimeTests`) on the +provider's Blacksmith macOS runners, 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 `MLX_QMV_BATCH_INVARIANT=1`, +as every cluster process does. + +| Selection | Job | Tests | +|---|---|---| +| Base | Cluster Runtime Tests (blocking) | Every test that needs no environment switch. The base selections pass `--skip` for the switched tests and the tests that need a model, so a test that skips there has a gate that the plan does not name | +| Opt-in | Cluster Runtime Tests (blocking) | The tests that one switch (for example `QWEN_TP_MTP_GPU=1`) enables and that pass on the CI runners | +| 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 +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`. Build the runtime tests once (`swift build --package-path libs/darkbloom-cluster -c release --build-tests --triple arm64-apple-macosx26.2 -Xcc -target -Xcc diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift index d6f585a0a3..13c685f3df 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Prefix/QwenStagePrefixCache.swift @@ -170,12 +170,13 @@ public final class QwenStagePrefixCache: @unchecked Sendable { var captureCost: QwenStagePrefixCaptureCost? { lock.withLock { measured } } /// The budget for `roomBytes` of admissible memory left beside the - /// serving context's charge: half of it, at most `maximumBudgetBytes`, - /// rounded down to 256 MiB so the idle refresh does not move it with - /// every small drift. The serving context is never reduced for the - /// cache; the other half stays for the desktop's own drift. - public static func budget(roomBytes: Int) -> Int { - max(0, min(maximumBudgetBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) + /// serving context's charge: half of it, at most `maximumBytes` (this + /// Mac's `maximumBudgetBytes`), rounded down to 256 MiB so the idle + /// refresh does not move it with every small drift. The serving context + /// is never reduced for the cache; the other half stays for the desktop's + /// own drift. + public static func budget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Int { + max(0, min(maximumBytes, roomBytes / 2) / budgetGranuleBytes * budgetGranuleBytes) } static let budgetGranuleBytes = 256 << 20 /// The room a memory-bound serving context leaves for the cache: one granule of budget (half the room). @@ -260,8 +261,8 @@ public final class QwenStagePrefixCache: @unchecked Sendable { /// directions, so a load during a memory dip does not keep it small for as /// long as the model stays loaded. Entries beyond a lower budget go now. /// True when the budget changed. - @discardableResult func refreshBudget(roomBytes: Int) -> Bool { - let target = Self.budget(roomBytes: roomBytes) + @discardableResult func refreshBudget(roomBytes: Int, maximumBytes: Int = QwenStagePrefixCache.maximumBudgetBytes) -> Bool { + let target = Self.budget(roomBytes: roomBytes, maximumBytes: maximumBytes) return lock.withLock { guard target != budget else { return false } budget = target; evictLocked(reserving: 0); return true diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift index 58cc1608a8..377e928158 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/LongContextLimitsTests.swift @@ -195,7 +195,7 @@ struct LongContextLimitsTests { chunkSize: min(512, context - 1)).conservativeStateAndBoundaryBytes let transient = try QwenResidentPrefillTransient.bytes(geometry: geometry, stageHasAttention: true, chunkTokens: min(512, context - 1), contextTokens: context) - let required = state + transient + QwenDenseStageLoadPolicy.loadingHeadroomBytes + let required = state + transient + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: os.physicalMemoryBytes) return try QwenDenseStageLoadPolicy.decide(os, requiredBytes: required, purpose: "test context \(context)", now: 1_100).admitted } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift index 7875afbd5b..a70b706329 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/PrefixCacheContractTests.swift @@ -21,6 +21,10 @@ private func state(_ frontier: Int) -> QwenStagePrefixState { @Suite("Prompt prefix reuse contracts (two-rank, no execution)") struct PrefixCacheContractTests { + /// The budget ceiling of a 128 GiB Mac. The budget checks use it, not + /// the ceiling of the Mac running the tests, which a smaller Mac lowers. + static let ceiling128GiB = QwenStagePrefixDiskPolicy.residentCeilingBytes(physicalBytes: 128 << 30) + @Test func plannedFramesStartAtTheReusedPrefixAndSplitTheLastToken() throws { let request = try QwenLayerStageGenerationRequest(profile: prefixProfile(), requestID: UUID(), promptTokenIDs: Array(0..<50), chunkSize: 16, outputCount: 3, stopTokenIDs: []) @@ -223,9 +227,12 @@ struct PrefixCacheContractTests { @Test func theBudgetComesFromTheRoomAndTheCaptureLimitFromTheMeasuredCost() { let gib = 1 << 30 #expect(QwenStagePrefixCache.budget(roomBytes: 26 * gib) == QwenStagePrefixCache.maximumBudgetBytes) - #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib) == 3 * gib) - #expect(QwenStagePrefixCache.budget(roomBytes: -1) == 0) - #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib + 300 << 20) == 3 * gib) + // A 128 GiB Mac's ceiling (4 GiB), whatever the memory of the Mac running the test. + let ceiling = Self.ceiling128GiB + #expect(QwenStagePrefixCache.budget(roomBytes: 26 * gib, maximumBytes: ceiling) == 4 * gib) + #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib, maximumBytes: ceiling) == 3 * gib) + #expect(QwenStagePrefixCache.budget(roomBytes: -1, maximumBytes: ceiling) == 0) + #expect(QwenStagePrefixCache.budget(roomBytes: 6 * gib + 300 << 20, maximumBytes: ceiling) == 3 * gib) let cache = QwenStagePrefixCache(entryLimit: 32, budgetBytes: 8 * gib) // Unmeasured: the budget is charged. #expect(cache.captureLimit(promptCount: 20_480, chunkSize: 512) == 8 * gib) @@ -394,21 +401,22 @@ struct PrefixCacheContractTests { /// both directions: a load during a memory dip does not keep the cache /// small (and prefix reuse off on the pair) for as long as it stays loaded. @Test func theIdleRefreshFollowsTheRoomInBothDirections() { - let mib = 1 << 20 + let mib = 1 << 20, ceiling = Self.ceiling128GiB // Loaded during a dip: 256 MiB. let cache = QwenStagePrefixCache(entryLimit: 32, budgetBytes: 256 * mib) - #expect(cache.refreshBudget(roomBytes: 4_096 * mib) && cache.budgetBytes == 2_048 * mib) + #expect(cache.refreshBudget(roomBytes: 4_096 * mib, maximumBytes: ceiling) && cache.budgetBytes == 2_048 * mib) // Drift within one 256 MiB step changes nothing. - #expect(!cache.refreshBudget(roomBytes: 4_096 * mib + 100 * mib) && cache.budgetBytes == 2_048 * mib) - #expect(cache.refreshBudget(roomBytes: 64 * 1_024 * mib) - && cache.budgetBytes == QwenStagePrefixCache.maximumBudgetBytes) + #expect(!cache.refreshBudget(roomBytes: 4_096 * mib + 100 * mib, maximumBytes: ceiling) + && cache.budgetBytes == 2_048 * mib) + #expect(cache.refreshBudget(roomBytes: 64 * 1_024 * mib, maximumBytes: ceiling) && cache.budgetBytes == ceiling) // Lowered with the room: entries beyond the new budget go at once. cache.insert(scope: "s", tokens: Array(0..<100), states: [sized(50, own: 300 * mib), sized(99, own: 300 * mib)], sharedBytes: 100 * mib) #expect(cache.bytesInUse == 700 * mib) - #expect(cache.refreshBudget(roomBytes: 1_024 * mib) && cache.budgetBytes == 512 * mib) + #expect(cache.refreshBudget(roomBytes: 1_024 * mib, maximumBytes: ceiling) && cache.budgetBytes == 512 * mib) #expect(cache.bytesInUse <= 512 * mib && cache.heldFrontiers == [99]) - #expect(cache.refreshBudget(roomBytes: 0) && cache.budgetBytes == 0 && cache.count == 0 && cache.bytesInUse == 0) + #expect(cache.refreshBudget(roomBytes: 0, maximumBytes: ceiling) && cache.budgetBytes == 0 && cache.count == 0 + && cache.bytesInUse == 0) } /// Finding F4: four rotating 8K documents, each captured with its split diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift index eb604889a8..b95b1bc231 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/RequestScopedRefusalTests.swift @@ -99,7 +99,8 @@ struct RequestScopedRefusalTests { fileBackedPages: fileBacked) let reserved = 7 * Self.gib + 921 * Self.mib let admission = try QwenDenseStageLoadPolicy.decide(observation, - requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes, purpose: "Resident request", now: Mac.now) + requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: observation.physicalMemoryBytes), + purpose: "Resident request", now: Mac.now) let running = try QwenDenseStageLoadPolicy.decide(observation, requiredBytes: reserved, purpose: "Resident request", now: Mac.now, floor: QwenDenseStageLoadPolicy.minimumTrulyFreeBytes) #expect(!admission.admitted && running.admitted) @@ -109,8 +110,8 @@ struct RequestScopedRefusalTests { let roundTwo = Mac.observation(freeBytes: 6 * Self.gib + 300 * Self.mib, anonymousGiB: 55, fileBackedPages: (46 * Self.gib + 819 * Self.mib) / ConstructedMac.page) #expect(try QwenDenseStageLoadPolicy.decide(roundTwo, - requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes, purpose: "Resident request", - now: Mac.now).admitted) + requiredBytes: reserved + QwenDenseStageLoadPolicy.loadingHeadroomBytes(physicalMemoryBytes: roundTwo.physicalMemoryBytes), + purpose: "Resident request", now: Mac.now).admitted) // Almost all allocated: a load or reservation floor (6 GiB) would refuse; continuing does not. let full = Mac.observation(freeBytes: 512 * Self.mib, fileBackedGiB: 5, anonymousGiB: 85, inactiveFileBackedBytes: 0) #expect(!(try QwenDenseStageLoadPolicy.decide(full, requiredBytes: 100 * Self.mib, purpose: "Resident request", diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index 52b0da0610..f73b1cf9e2 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -28,6 +28,7 @@ "scripts/run-paged-kernel-tests.sh", "scripts/run-provider-test-watchdog.py", "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", + "scripts/cluster-test-plan.py", "scripts/prepare-mimo-*-fixtures.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", diff --git a/scripts/cluster-test-plan.py b/scripts/cluster-test-plan.py new file mode 100755 index 0000000000..58c513f40a --- /dev/null +++ b/scripts/cluster-test-plan.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Which CI process runs each darkbloom-cluster test, and the runner for one job shard. + +The runtime target (`DarkbloomClusterRuntimeTests`) runs in selections, each in +a process of its own (docs/developer/test.md): the base selections run every +test that needs no switch, and each opt-in selection runs only the tests one +environment switch enables. Every selection goes through +scripts/run-nested-suite.sh, which fails on zero executed tests and on any +skip. The base selections pass `--skip` for exactly the switched tests, so a +test that skips there has a gate this plan does not name. `audit` checks that +the plan names exactly the gated tests in the sources and every focused +runner under libs/darkbloom-cluster/Tests. + +Lanes: `blocking` (Cluster Runtime Tests), `nonblocking` (Cluster GPU Tests, +reported but not failing the workflow) and `focused` (Cluster Focused Checks, +the model-free runner scripts). + +Subcommands: + run LANE SHARD run the selections of one shard, each in its own process + audit check the plan against the sources and the workflow +""" + +import argparse +from dataclasses import dataclass, field +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time + + +ROOT = Path(__file__).resolve().parent.parent +PACKAGE = ROOT / "libs/darkbloom-cluster" +RUNTIME_TESTS = PACKAGE / "Tests/DarkbloomClusterRuntimeTests" +WORKFLOW = ROOT / ".github/workflows/ci.yml" +NESTED_SUITE = ROOT / "scripts/run-nested-suite.sh" +MODULE = "DarkbloomClusterRuntimeTests" +LANES = ("blocking", "nonblocking", "focused") +# Every cluster process starts with this switch (ClusterQuantizedRowRouting); +# MLX reads it once per process. +PROCESS_ENVIRONMENT = {"MLX_QMV_BATCH_INVARIANT": "1"} + + +@dataclass(frozen=True) +class Selection: + name: str + lane: str + shard: int + environment: dict = field(default_factory=dict) + # Opt-in: the gated test functions the environment enables. + tests: tuple = () + # Base: these suites only, or every suite no other base selection takes. + suites: tuple | None = None + # Focused: a runner script under libs/darkbloom-cluster/Tests. + runner: str | None = None + + @property + def base(self): + return not self.tests and self.runner is None + + +QWEN_TP_MTP_GPU_TESTS = ( + "oneResidentAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation", + "nineBRatioAssistantSurvivesCreditJoinsRectanglesAndResumedSpeculation", + "finalNativeWindowStillPublishesEveryAcceptedTokenUnderSeparateCredits", + "concurrentRoundsKeepIndependentCreditsAndSurviveCohortRetirement", + "eligibleCohortCoexistsWithOrdinaryHistoryAndLogprobLanes", + "concurrentFinalWindowsDrainWithoutFurtherNativeWork", + "failedConcurrentDraftPublishesNothingAndRetainsAllRowsForCheckedRetirement", + "staggeredRowsVerifyAsOneCohortAndMatchTheirSoloRuns", + "aheadRowStopsCleanlyAndItsCohortContinues", + "batchedCohortDraftsMatchRowByRowDraftsWithOneHeadCallPerStep", + "exactDraftRowsEqualTheirSoloRunsAndThePlainTargetAtEveryWidth", + "unequalHistoriesAndKeepsDiscardRejectedSuffixesAndResumeBatchDecode", + "capturedGreedyChoicesAndContinuationMatchOrdinaryTargetColumns", + "oneProductOverManyRowsChangesQuantizedArithmetic", + "sharedWindowCallsKeepEveryRowsQuantizedArithmetic", + "everyRectangleRowEqualsItsOwnSingleRequestWindowBitwise", + "capturedCohortCannotBePartiallyFinalizedAndFaultRetiresAllRows", + "graphConstructionFailurePoisonsAllBoundRowsAndReturnsTheirStorage", + "laterDraftStepsForManyRowsEqualEachRowAlone", + "windowPositionsEqualPlainDecodeStepsBitwise", + "shortSettledWindowsEqualTheirPlainStepsBitwise", + "fusedResidualStepsKeepEveryOutputBitwise", + "decodeRowsEqualTheirSoloStepsBitwise", + "cohortHeadRowsKeepEachRowsOwnProduct", + "exactDraftProjectionsKeepEachRowsOwnProductAtQwen27Shapes", + "realAssistantAndTargetRoundsSettleBeforePublicationAndRetireAfterFault", + "boundedHistoryFlushKeepsTargetVerifiedOutputs", + "promptHistoryFlushesKeepDraftsAndBoundTheBacklog", + "capturedWindowsAllocateNoSecondHistory", + "actualHybridShardsCommitAndRetireCapturedWindows", + "pairedPrefixPreservesHybridSpeculationAndRejectsFailedDonors", + "pipelinedDraftsEmitTheSameTokensAndCollectives", + "oneRankFailingMidChainFailsBothAndRetires", + "deferredRangeCheckKeepsTheWindowAndItsHistory", + "wholeAndLayeredWindowsAreBitwise", +) + +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=( + "bothTilesGiveTheSameBytes", + "actualHybridShardsPreserveAttentionConvAndSSMRows", + "nineBRatioDenseShardsBatchExactly", + "routedExpertShardsBatchExactly", + "routedExpertNativeMixedSamplingKeepsRowsIndependent", + "warmHybridPrefixesPreserveConvSSMAndMixedPositions", + "ssdHybridPrefixesRestoreConvSSMAfterTheTiersReopen", + "deepRestoresEqualColdPrefillOnBothRanks", + "mergedStepTemporariesStayWithinTheirCharge", + "mergedFramesKeepEveryBit", + "executorRunsThePlannedMergedStep", + )), + Selection("qwen-tp-batch-gpu-paged", "blocking", 3, {"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=( + "declinesWhatItDoesNotCover", + "agreesWithTheDequantizedProduct", + "everyVectorEqualsItsOwnSingleVectorCall", + "everyLayoutGivesTheSameBits", + "swigluEqualsTwoProjectionsAndTheSwiGLU", + "swigluEqualsTheCompiledSwiGLUAtEveryGateValue", + "siluMultiplyEqualsTheUnfusedChain", + "sigmoidGateEqualsTheUnfusedChain", + "cachedGatedDeltaScalesEqualFreshOnes", + )), + Selection("qwen-tp-moe-gpu", "blocking", 3, {"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=( + "eachRankTimesItsShareAloneAndReleasesItsRequest", + "aRefusalOrAFailureGivesNoProbeAndKeepsNothing", + )), + Selection("glm53-prefix-ssd", "blocking", 3, {"GLM53_PREFIX_SSD": "1"}, tests=( + "aServingStageRestoresFromTheSSDExactly", + "aServingStageRestoresFromABalancedRecord", + )), + Selection("glm53-paged-kv", "blocking", 2, {"GLM53_PAGED_KV": "1"}, tests=( + "pagedRequestsDecideAndHoldWhatContiguousOnesDo", + "pagedMediaRequestsDecideAndHoldWhatContiguousOnesDo", + )), + Selection("glm53-row-invariance", "blocking", 2, {"GLM53_ROW_INVARIANCE": "1"}, tests=( + "roundsAreEachRequestsOwnRound", + )), + Selection("glm53-depth-invariance", "blocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( + "prefillIsTheSameWithAndWithoutTheSwitch", + "unpaddedLastRoundsStayOneRowWindows", + )), + Selection("glm53-window-census", "blocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( + "sublayerCensus", + "projectionRowCensus", + )), + Selection("tf32-off", "blocking", 2, {"MLX_ENABLE_TF32": "0"}, tests=( + "receiverCommitPrecedesProducerPublicationAndMatchesFullCachedForward", + )), + Selection("qwen-tp-real-geometry-gpu", "nonblocking", 1, {"QWEN_TP_REAL_GEOMETRY_GPU": "1"}, tests=( + "rowsEqualTheirSoloStepsAndWindowPositionsAtRealWidths", + )), + Selection("qwen-tp-mtp-gpu-wide-kernel", "nonblocking", 2, {"QWEN_TP_MTP_GPU": "1"}, tests=( + "wideKernelRowsEqualEachRowsOwnWindowCall", + )), + Selection("qwen-tp-aqv-gpu-fused-kernels", "nonblocking", 2, {"QWEN_TP_AQV_GPU": "1"}, tests=( + "residualRMSNormEqualsTheUnfusedOps", + "gatedDeltaConvolutionEqualsTheUnfusedOps", + "gatedDeltaQKNormEqualsTheUnfusedOps", + "cpuStreamSumIsBitwiseOnGPU", + "chainWithCPUHopsIsBitwiseOnGPU", + "transposedCPUSumWaitsBeforeTheCopyOnGPU", + )), + Selection("qwen-tp-batch-gpu-paged-transient", "nonblocking", 2, + {"QWEN_TP_BATCH_GPU": "1", "QWEN_TP_BATCH_KV": "paged"}, tests=( + "fullHistoryGatherIsOnePromptFramesTransient", + )), + Selection("glm53-depth-invariance-widths", "nonblocking", 2, {"GLM53_DEPTH_INVARIANCE": "1"}, tests=( + "everyDepthAndKeptPatternIsTheDepthTwoDecode", + "loadPolicyLanesAreEachRequestAloneAtDepthTwo", + )), + Selection("glm53-window-width-census", "nonblocking", 2, {"GLM53_WINDOW_CENSUS": "1"}, tests=( + "windowWidthCensus", + )), + Selection("paged-verify-bench", "nonblocking", 2, {"DARKBLOOM_PAGED_BENCH": "1"}, tests=( + "verifyAndPrefillAttention", + )), + Selection("qwen-tp-aqv-bench", "nonblocking", 2, {"QWEN_TP_AQV_BENCH": "1"}, tests=( + "throughputAgainstMLXCalls", + )), + Selection("qwen-tp-wide-bench", "nonblocking", 2, {"QWEN_TP_WIDE_BENCH": "1"}, tests=( + "wideKernelVariantThroughput", + )), + Selection("prefix-record-encode-bench", "nonblocking", 2, {"PREFIX_RECORD_ENCODE_BENCH": "1"}, tests=( + "encodingThroughputAtTheBetaShape", + )), + *(Selection(f"focused-{name}", "focused", 1, runner=name) for name in ( + "BootstrapChecks", "CapabilityChecks", "CheckpointChecks", "DeadlineChecks", "ExitChecks", + "GLMImageAdmissionChecks", "LinkControlChecks", "LinkWorkerChecks", "NativePairChecks", + "ObservabilityChecks", "PlacementChecks", "PrefixPolicyChecks", "PreludeChecks", + "ProcessChecks", "ProtocolChecks", "QwenMediaChecks", "RemoteChecks", "SSHChecks", + "SecurityChecks", "StageTransferChecks", "StillImageChecks", "TensorParallelPlanChecks", + )), +) + +# Gated tests that need a model directory, an artifact or its metadata. CI has +# none, so no selection runs them; the base selections skip them by name. +REQUIRES_MODEL = ( + "theRegisteredArtifactReproducesItsPinnedInventory", + "thePinnedSourceEqualsTheFileBackedSource", + "theRealModelsPerTokenCharge", + "aReservationsChargeDoesNotHashTheInventory", + "eigenLabs8841HeadersMatchExactPinsAndAllStructuralCuts", + "setupStepsOnTheRealMetadata", + "packedSharedExpertCollectiveIsBitIdenticalOnTheRealArtifact", + "cohortRoundPhasesByWidthAndDraftBatching", + "completeLoadQuoteByWidth", + "perRankDecodeCompute", + "exactAndMLXDraftsOnRealPromptsAreLosslessWithTheirAcceptance", + "routedExpertDecodeStepProfile", + "oneRowRoundPhasesByOwnerCapacity", + "cohortRowsEqualTheirSoloRowsOnTheRealArtifact", + "verifyWindowRoundsByRowCount", +) +REQUIRES_MODEL_SUITES = ("GLM5NextServingMetadataTests", "GLM5NextTensorParallelMediaTowerTests") +# Runners the Cluster Metadata Checks job runs with its retained native build. +METADATA_JOB_RUNNERS = ("GPTOSSStageChecks", "NemotronStageChecks", "PrefillScheduleChecks", "StageMetadataChecks") + + +def functions_regex(names): + return f"/(?:{'|'.join(sorted(names))})\\(" + + +def suites_regex(suites): + return f"^{MODULE}[./](?:{'|'.join(sorted(suites))})(?:[./]|$)" + + +def switched_regex(): + """Every test a base selection must not run: the switched and model-gated tests.""" + gated = [name for selection in SELECTIONS for name in selection.tests] + list(REQUIRES_MODEL) + return f"{functions_regex(gated)}|{suites_regex(REQUIRES_MODEL_SUITES)}" + + +def swift_arguments(selection): + """The run-nested-suite.sh arguments: the filter, then extra `swift test` arguments.""" + if selection.tests: + return [functions_regex(selection.tests), "--no-parallel"] + if selection.suites: + return [suites_regex(selection.suites), "--skip", switched_regex(), "--no-parallel"] + others = [suite for other in SELECTIONS if other.base and other.suites for suite in other.suites] + return [f"^{MODULE}[./]", "--skip", f"{switched_regex()}|{suites_regex(others)}", "--no-parallel"] + + +def command(selection, output): + if selection.runner is None: + return PACKAGE, [str(NESTED_SUITE), *swift_arguments(selection)] + directory = PACKAGE / "Tests" / selection.runner + if (directory / "run.py").is_file(): + return ROOT, ["python3", str(directory / "run.py"), "--output", str(output / selection.runner)] + return ROOT, ["bash", str(directory / "run.sh")] + + +# Variables the runtime tests read to change what they run; no selection +# inherits one from the runner. +TEST_SWITCH_PREFIXES = ("QWEN_TP_", "GLM53_", "DARKBLOOM_PAGED_BENCH", "PREFIX_RECORD_") + + +def environment(selection): + switches = {name for other in SELECTIONS for name in other.environment} + values = {name: value for name, value in os.environ.items() + if name not in switches and not name.startswith(TEST_SWITCH_PREFIXES)} + return {**values, **PROCESS_ENVIRONMENT, **selection.environment} + + +def shards(lane): + return sorted({selection.shard for selection in SELECTIONS if selection.lane == lane}) + + +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 = [] + 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 status: + level = "warning" if lane == "nonblocking" else "error" + print(f"::{level}::{selection.name} failed with exit status {status}", flush=True) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + with open(summary, "a") as handle: + handle.write(f"### Cluster {lane} shard {shard}\n\n| Selection | Result | Seconds |\n|---|---|---|\n") + for name, status, seconds in rows: + handle.write(f"| {name} | {'passed' if status == 0 else 'failed'} | {seconds:.0f} |\n") + return 1 if any(status for _, status, _ in rows) else 0 + + +def gated_in_sources(directory=RUNTIME_TESTS): + """(gated test functions, gated suites, function names defined more than once).""" + functions, suites, defined = set(), set(), {} + attribute = re.compile(r"@(Test|Suite)\(") + for path in sorted(directory.rglob("*.swift")): + text = path.read_text() + for match in re.finditer(r"\bfunc (\w+)\(", text): + defined[match.group(1)] = defined.get(match.group(1), 0) + 1 + for match in attribute.finditer(text): + depth, index = 0, match.end() - 1 + while True: + depth += {"(": 1, ")": -1}.get(text[index], 0) + if depth == 0: + break + index += 1 + if ".enabled(if:" not in text[match.start():index]: + continue + following = text[index + 1:] + if match.group(1) == "Test": + functions.add(re.search(r"\bfunc (\w+)\(", following).group(1)) + else: + suites.add(re.search(r"\b(?:struct|class|enum) (\w+)", following).group(1)) + repeated = {name for name, count in defined.items() if count > 1} + return functions, suites, repeated + + +def audit(): + errors = [] + planned = [name for selection in SELECTIONS for name in selection.tests] + for name in sorted({name for name in planned if planned.count(name) > 1}): + errors.append(f"{name} is in more than one selection") + named_once = planned + list(REQUIRES_MODEL) + functions, suites, repeated = gated_in_sources() + for name in sorted(functions - set(named_once)): + errors.append(f"Gated test {name} is in no selection or REQUIRES_MODEL") + for name in sorted(set(named_once) - functions): + errors.append(f"{name} is planned but is not a gated test in {RUNTIME_TESTS.relative_to(ROOT)}") + for name in sorted(set(named_once) & repeated): + errors.append(f"{name} is defined more than once; its name does not select one test") + if suites != set(REQUIRES_MODEL_SUITES): + errors.append(f"Gated suites {sorted(suites)} differ from REQUIRES_MODEL_SUITES {sorted(REQUIRES_MODEL_SUITES)}") + names = [selection.name for selection in SELECTIONS] + if len(names) != len(set(names)) or any(selection.lane not in LANES for selection in SELECTIONS): + errors.append("Selection names must be unique and every lane known") + for lane in LANES: + if shards(lane) != list(range(1, len(shards(lane)) + 1)): + errors.append(f"{lane} shards are not numbered 1 to N: {shards(lane)}") + runners = {path.parent.name for pattern in ("*/run.sh", "*/run.py") for path in (PACKAGE / "Tests").glob(pattern)} + focused = {selection.runner for selection in SELECTIONS if selection.runner} + if runners != focused | set(METADATA_JOB_RUNNERS) or focused & set(METADATA_JOB_RUNNERS): + errors.append(f"Runners {sorted(runners)} must each be in exactly one of the focused lane " + f"{sorted(focused)} and METADATA_JOB_RUNNERS {sorted(METADATA_JOB_RUNNERS)}") + workflow = WORKFLOW.read_text() + for runner in METADATA_JOB_RUNNERS: + if f"libs/darkbloom-cluster/Tests/{runner}/run." not in workflow: + errors.append(f"{runner} is not run by the workflow") + return errors + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + command_parser = commands.add_parser("run") + command_parser.add_argument("lane", choices=LANES) + command_parser.add_argument("shard", type=int) + commands.add_parser("audit") + args = parser.parse_args() + if args.command == "run": + return run(args.lane, args.shard) + errors = audit() + for error in errors: + print(f"::error::{error}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/provider-ci-cache.py b/scripts/provider-ci-cache.py index f52f8a57f1..521d57d1a2 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` after Metal toolchain setup. +Run `keys --lane provider|sdk|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 @@ -22,6 +22,7 @@ LANE_PURPOSES = { "provider": "provider-debug-tests", "sdk": "sdk-nested-debug-tests", + "cluster": "cluster-runtime-debug-tests", } MLX_SOURCE = "libs/mlx-swift/Source/Cmlx/mlx" SWIFT_WRAPPER = Path(__file__).resolve().with_name("provider-release-swift.sh") diff --git a/scripts/run-nested-suite.sh b/scripts/run-nested-suite.sh index 33688fda0f..9a79142f28 100755 --- a/scripts/run-nested-suite.sh +++ b/scripts/run-nested-suite.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # -# Run ONE swift-testing suite inside libs/mlx-swift-lm and fail if it executed -# zero tests. +# Run one `swift test` selection (a filter plus extra arguments) and fail if +# it executed zero tests or skipped one. # # THE TRIPWIRE IS THE POINT. `swift test` exits 0 even when the swift-testing # pass executes NOTHING — that is how the four paged suites sat dark for a @@ -64,9 +64,9 @@ fi # # A suite whose every case self-skips (XCTSkip on a missing fixture, a # .disabled/.enabled(if:) trait nobody meant to trip) asserts nothing — the -# same dark-gate failure mode, one layer up. Fail on ANY skip: these nested -# suites are hermetic by design (tiny models, no weights, no env gates), so a -# skip here means a precondition broke, not that skipping was intended. +# same dark-gate failure mode, one layer up. Fail on ANY skip: these +# selections are hermetic by design (every test they select is meant to run), +# so a skip here means a precondition broke, not that skipping was intended. if grep -qE '^[^A-Za-z0-9]*(Test|Suite) .+ skipped[.:]|with [1-9][0-9]* tests? skipped|skipped [1-9][0-9]* test' "$log"; then echo "::error::${filter} skipped one or more tests — a skipped gate gates" \ "nothing. If the skip is a broken precondition (missing metallib," \ diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index aa82c47eee..cbc7179bde 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -83,6 +83,7 @@ def test_selected_executable_dependencies_are_classified(self): "scripts/run-nested-suite.sh", "scripts/run-paged-kernel-tests.sh", "scripts/run-exclusive-native-gpu-test.sh", "scripts/provider-test-shards.py", "scripts/provider-test-shard-weights.json", + "scripts/cluster-test-plan.py", "scripts/run-provider-test-watchdog.py", "scripts/prepare-mimo-audio-fixtures.py", "scripts/prepare-mimo-provider-fixtures.py", "scripts/prepare-mimo-prompt-fixtures.py", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", @@ -275,7 +276,7 @@ def test_detector_has_full_history_no_credentials_or_api_truncation(self): def test_provider_aggregate_exhaustive_truth_table(self): jobs = workflow.job_blocks((ROOT / ".github/workflows/ci.yml").read_text()) gate = jobs["provider-test-gate"] - self.assertIn("needs: [changes, test-provider, test-provider-summary]", gate) + self.assertIn("needs: [changes, test-provider, test-provider-summary, test-cluster, test-cluster-focused]", gate) self.assertNotIn("test-provider-sdk", gate) self.assertIn("if: ${{ always() }}", gate) self.assertNotIn("continue-on-error:", gate) @@ -283,18 +284,20 @@ def test_provider_aggregate_exhaustive_truth_table(self): for name, expression in { "CHANGES_RESULT": "needs.changes.result", "PROVIDER_CHANGED": "needs.changes.outputs.provider", "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", }.items(): self.assertIn(name + ": ${{ " + expression + " }}", step) command = workflow.run_command(step) results = ("success", "skipped", "failure", "cancelled") # Prompt Parity runs in a provider shard, so UNIT_RESULT carries it. self.assertNotIn("PARITY_RESULT", step) - for detector, changed, unit, summary in itertools.product( - results, ("true", "false", ""), results, results): + names = ("UNIT_RESULT", "SUMMARY_RESULT", "CLUSTER_RESULT", "CLUSTER_FOCUSED_RESULT") + for detector, changed, *lanes in itertools.product( + results, ("true", "false", ""), *[results] * len(names)): result = subprocess.run(["bash", "-e", "-c", command], capture_output=True, timeout=5, env={**os.environ, "CHANGES_RESULT": detector, "PROVIDER_CHANGED": changed, - "UNIT_RESULT": unit, "SUMMARY_RESULT": summary}) - lanes = (unit, summary) + **dict(zip(names, lanes))}) expected = detector == "success" and ((changed == "true" and set(lanes) == {"success"}) or (changed == "false" and set(lanes) == {"skipped"})) self.assertEqual(result.returncode == 0, expected, (detector, changed, *lanes)) diff --git a/scripts/test-cluster-test-plan.py b/scripts/test-cluster-test-plan.py new file mode 100755 index 0000000000..06167456a2 --- /dev/null +++ b/scripts/test-cluster-test-plan.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Offline checks of the cluster test plan and the jobs that run it.""" + +import importlib.util +import os +from pathlib import Path +import re +import unittest +from unittest import mock + + +ROOT = Path(__file__).resolve().parent.parent +_SPEC = importlib.util.spec_from_file_location("cluster_test_plan", ROOT / "scripts/cluster-test-plan.py") +plan = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(plan) +_SPEC = importlib.util.spec_from_file_location("provider_workflow", ROOT / "scripts/test-provider-ci-workflow.py") +workflow = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(workflow) + + +def selected(selection, test_id): + """Whether `swift test` with this selection's filter and skip runs `test_id`.""" + filter_regex, *extra = plan.swift_arguments(selection) + skip = extra[extra.index("--skip") + 1] if "--skip" in extra else None + return bool(re.search(filter_regex, test_id)) and not (skip and re.search(skip, test_id)) + + +class ClusterTestPlanTests(unittest.TestCase): + def setUp(self): + self.jobs = workflow.job_blocks(plan.WORKFLOW.read_text()) + + def test_plan_names_every_gated_test_and_runner(self): + self.assertEqual(plan.audit(), []) + + def test_every_test_runs_in_exactly_one_selection_unless_it_needs_a_model(self): + module = plan.MODULE + swift = [selection for selection in plan.SELECTIONS if selection.runner is None] + cases = {f"{module}.AnySuite/{name}(sharded:)": name for selection in swift for name in selection.tests} + cases.update({ + f"{module}.QwenTensorParallelBatchSessionTests/actualShardsBatchIndependentHistories()": "base-batch-session", + f"{module}.QwenTensorParallelBatchSessionTests/Nested/plainCase()": "base-batch-session", + f"{module}.PrefixCacheContractTests/plannedFramesStartAtTheReusedPrefix()": "base", + f"{module}.QwenBatchCancellationTests/testAcceptedStartStaysCharged": "base", + f"{module}.QwenTensorParallelBatchSessionTestsMore/plainCase()": "base", + }) + for test_id, owner in cases.items(): + with self.subTest(test_id=test_id): + runs = [selection for selection in swift if selected(selection, test_id)] + self.assertEqual(len(runs), 1, [selection.name for selection in runs]) + runner = runs[0] + self.assertTrue(runner.name == owner or owner in runner.tests, runner.name) + needs_model = [f"{module}.AnySuite/{name}()" for name in plan.REQUIRES_MODEL] + needs_model += [f"{module}.{suite}/anyCase()" for suite in plan.REQUIRES_MODEL_SUITES] + for test_id in needs_model: + with self.subTest(test_id=test_id): + self.assertEqual([selection.name for selection in swift if selected(selection, test_id)], []) + + def test_every_selection_runs_through_the_zero_skip_wrapper_serially(self): + for selection in plan.SELECTIONS: + with self.subTest(selection=selection.name): + cwd, argv = plan.command(selection, Path("/output")) + if selection.runner is None: + self.assertEqual(cwd, plan.PACKAGE) + self.assertEqual(argv[0], str(ROOT / "scripts/run-nested-suite.sh")) + self.assertEqual(argv[-1], "--no-parallel") + else: + self.assertEqual(cwd, ROOT) + self.assertTrue(Path(argv[1]).is_file(), argv) + + def test_each_process_has_only_its_own_switches(self): + switches = {name: "1" for selection in plan.SELECTIONS for name in selection.environment} + switches.update({"GLM53_WINDOW_CENSUS_LONG": "1", "DARKBLOOM_PAGED_BENCH_CTX": "4096"}) + with mock.patch.dict(os.environ, switches): + for selection in plan.SELECTIONS: + with self.subTest(selection=selection.name): + environment = plan.environment(selection) + self.assertEqual(environment["MLX_QMV_BATCH_INVARIANT"], "1") + own = {name: value for name, value in environment.items() if name in switches} + # Only its own switches: also none of the other variables the tests read. + self.assertEqual(own, selection.environment) + + def test_jobs_run_every_shard_of_their_lane(self): + jobs = {"test-cluster": "blocking", "test-cluster-gpu": "nonblocking"} + for job_id, lane in jobs.items(): + with self.subTest(job=job_id): + job = self.jobs[job_id] + matrix = re.search(r"(?m)^ shard: \[([0-9, ]+)\]$", job).group(1) + self.assertEqual([int(shard) for shard in matrix.split(",")], plan.shards(lane)) + for shard in plan.shards(lane): + self.assertIn(f" {job_id}-{shard} macos_arm64 ", self.jobs["route"]) + steps = workflow.step_blocks(job) + build = next(step for step in steps if workflow.field(step, "uses") == workflow.BUILD_ACTION) + self.assertEqual(workflow.field(build, "lane", indent=10), "cluster") + run = steps[-1] + self.assertEqual(workflow.run_command(run), f'python3 scripts/cluster-test-plan.py run {lane} "$SHARD"') + self.assertEqual(workflow.field(run, "SHARD", indent=10), "${{ matrix.shard }}") + self.assertEqual(workflow.field(run, "if"), workflow.READY) + self.assertEqual(plan.shards("focused"), [1]) + focused = workflow.step_blocks(self.jobs["test-cluster-focused"]) + self.assertEqual(workflow.run_command(focused[-1]), "python3 scripts/cluster-test-plan.py run focused 1") + self.assertIn(" test-cluster-focused macos_arm64 ", self.jobs["route"]) + + def test_only_the_gpu_job_continues_after_a_failure_and_the_gate_requires_the_others(self): + self.assertIn("continue-on-error: true", workflow.step_blocks(self.jobs["test-cluster-gpu"])[-1]) + gate = workflow.field(self.jobs["provider-test-gate"], "needs", indent=4) + needs = [name.strip() for name in gate.strip("[]").split(",")] + for job_id in ("test-cluster", "test-cluster-focused"): + with self.subTest(job=job_id): + self.assertNotIn("continue-on-error:", self.jobs[job_id]) + self.assertIn(job_id, needs) + self.assertNotIn("test-cluster-gpu", self.jobs["provider-test-gate"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-darkbloom-route.py b/scripts/test-darkbloom-route.py index f7b72158bf..e2136cc6c6 100755 --- a/scripts/test-darkbloom-route.py +++ b/scripts/test-darkbloom-route.py @@ -52,6 +52,9 @@ "test-provider-summary": ("macos_arm64", MACOS_FALLBACK, PROVIDER), "test-provider-sdk": ("macos_arm64", MACOS_FALLBACK, SDK), "test-cluster-checks": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster-gpu": ("macos_arm64", MACOS_FALLBACK, PROVIDER), + "test-cluster-focused": ("macos_arm64", MACOS_FALLBACK, PROVIDER), }, "docs-impact.yml": { "commit-signatures": ("linux_arm64", LINUX_FALLBACK, None), @@ -68,7 +71,7 @@ "threat-model-review.yml", "bedrock-smoke.yml", "claude.yml", "codex.yml") # The plane grants a lane whole, so each shard of these jobs reads a lane of its # own, `-`, and gets a free sandbox even when the others fall back. -SHARDED = {"test-provider"} +SHARDED = {"test-provider", "test-cluster", "test-cluster-gpu"} # Master and dispatched warming feed release builds, so only PRs read the route. RUNS_ON = {"warm": "${{ github.event_name == 'pull_request' && " "fromJSON(needs.route.outputs.routes)['warm'] || 'blacksmith-12vcpu-macos-27' }}"} diff --git a/scripts/test-provider-ci-workflow.py b/scripts/test-provider-ci-workflow.py index 4ffd770041..bbd68e7628 100644 --- a/scripts/test-provider-ci-workflow.py +++ b/scripts/test-provider-ci-workflow.py @@ -235,7 +235,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]\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.assertNotIn("test-provider-sdk", job) self.assertIn(" if: ${{ always() }}\n", job) @@ -244,14 +244,15 @@ 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) - for unit, summary in (("success", "success"), ("failure", "success"), ("success", "failure"), - ("skipped", "success"), ("success", "skipped"), ("cancelled", "success"), - ("success", "cancelled")): - result = subprocess.run(["bash", "-e", "-c", command], - env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", "UNIT_RESULT": unit, - "SUMMARY_RESULT": summary}, - capture_output=True, timeout=5) - self.assertEqual(result.returncode == 0, unit == summary == "success") + lanes = ("UNIT_RESULT", "SUMMARY_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} + result = subprocess.run(["bash", "-e", "-c", command], + env={**os.environ, "CHANGES_RESULT": "success", "PROVIDER_CHANGED": "true", + **results}, + capture_output=True, timeout=5) + self.assertEqual(result.returncode == 0, failed is None, results) def test_each_lane_checks_out_recursive_sources_before_its_build(self): for job_id, lane in LANES.items(): @@ -670,6 +671,7 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertEqual(run_command(toolchain), "./scripts/prepare-provider-release-toolchain.sh") runners = { "Run worker capability checks": "bash libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh", + "Run prefill schedule checks": "bash libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh", "Run stage metadata checks": 'python3 libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py ' '--output "$RUNNER_TEMP/stage-metadata-checks"', "Run GPT-OSS stage checks": "bash libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh", @@ -685,13 +687,18 @@ def test_cluster_metadata_runners_run_every_runner_and_fail_on_any(self): self.assertEqual(field(step, "if"), "${{ !cancelled() && steps.toolchain.outcome == 'success' }}") self.assertTrue((ROOT / command.split()[1]).is_file()) # The capability build may use the whole dedicated runner. - capability = named["Run worker capability checks"] - self.assertEqual(field(capability, "DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS", indent=10), "'12'") - # Its release build is restored with timestamps only for unchanged - # sources, keyed by toolchain, manifests, submodule pins and paths. - self.assertEqual(field(capability, "DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT", indent=10), - "${{ runner.temp }}/cluster-native-metadata") + # The prefill schedule runner builds its bootstrap product in the same + # retained build, before that build is recorded and saved. + for name in ("Run worker capability checks", "Run prefill schedule checks"): + native = named[name] + self.assertEqual(field(native, "DARKBLOOM_CLUSTER_METADATA_BUILD_JOBS", indent=10), "'12'") + # Its release build is restored with timestamps only for unchanged + # sources, keyed by toolchain, manifests, submodule pins and paths. + self.assertEqual(field(native, "DARKBLOOM_CLUSTER_METADATA_BUILD_ROOT", indent=10), + "${{ runner.temp }}/cluster-native-metadata") order = [field(step, "name", indent=6) for step in steps] + self.assertLess(order.index("Run prefill schedule checks"), + order.index("Record source timestamps for the cluster build")) restore, timestamps, record, upload = (order.index(name) for name in ( "Restore cluster metadata build", "Restore unchanged source timestamps", "Record source timestamps for the cluster build", "Upload cluster metadata build cache")) @@ -747,6 +754,7 @@ def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): 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") @@ -756,9 +764,12 @@ def test_composite_action_cannot_bypass_build_and_metallib_on_cache_hits(self): 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, metallib): + for step in (provider, sdk, cluster, metallib): self.assertNotIn("--filter", step) self.assertNotIn("--skip", step) self.assertNotIn("cache-hit", step)