From c83f7b23ea646036f3392c8d3585ebe540f88984 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 6 Nov 2026 11:05:12 -0600 Subject: [PATCH 001/270] Sync dev into master: CI build-once, job sizes, memory sampler, fixture retries, and provider TP work (post-0.10.9) (#1837) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(provider): single-Mac serving that blocks a pair is named once, with `stop --solo`, never retried On 0.10.8 a pair's start looped "this Mac's part ended (exit 1: another update operation owns the lock (pid 9523, provider-instance))" on the leader while the follower's single-Mac provider (process 2282) refused its worker; the leader read the follower as "no error reported", and the guidance said `darkbloom stop`, which on a paired Mac stops the pair and leaves single-Mac serving running. - UpdateProcessLock names its owner: a single-Mac provider serving (with `stop --solo`), this Mac's part of the pair, an update, a rollback, a stop. - ProviderInstanceHolder tells a single-Mac provider from a pair part (argv and the parent's argv, no files read). - Each cluster service holds its part back while single-Mac serving runs (no exit-1 restart loop) and reports it in its status (`soloServing`, child lastError), so the other Mac's screen gives the real reason. - `darkbloom cluster` checks both Macs before starting the parts and during the wait: one ✗ naming the Mac and process with `darkbloom stop --solo`, and "Stop single-Mac serving on both Macs and start the pair" (new `stopSolo` command), acting only with consent. No Retry for this cause. - local_provider_running guidance and the worker's refusal say `stop --solo`. - `darkbloom update` on a Mac whose pair is started restarts the pair, not a leftover single-Mac job; the watchdog no longer revives that job there. Co-Authored-By: Claude Opus 5.5 * cluster: the leader publishes the start's progress and shows each Mac's part The owner asked that the Mac that joins a pair show progress at each step, "maybe a progress bar and so on". This is the half that does not touch the follow screen: the published fields, the leader publishing them, the leader's own per-Mac rows, and the shared step, bar and row components. - ClusterOnboardingStartProgress (new, optional everywhere) travels in the leading Mac's status reply (ClusterControlReply.start) and its setup record. It carries the phase (downloading, copying, stopping, loading, testing, registering; a later one reads as unknown), a copy's or download's bytes as the sending Mac counts them, and each rank's part (ready, loading, starting, ended with its restart), with its layer range. A mark fences it by the publishing process; a copy's, download's or load's figures count for 30 s. - The leader publishes bytes about once a second from the copy (either way) and the download, "stopping" before a model change drains both Macs, the parts on each readiness poll, then testing and registering. It clears them when the start ends. - ClusterServiceStatus.Session.readyRankList (optional) names the ready ranks. - The leader's load wait shows one row per Mac: "This Mac: ready (layers 0-46)", "The other Mac: loading its share (layers 47-93)". A row that does not fit drops its layers, then shortens; a plain window says each row once. The wait's ✗ counting still reads the line without the rows. - Shared components: the bar (real bytes only, never 100% before the last byte), the step rows with "Next: …", and the plain log that says each change once. All fit the room a live row has (the window less 6 columns). Onboarding checks: 1260 passed (the new plain-row checks failed 3 on the base with only the components present). Filtered swift test: 20 tests in 2 suites, including the wire tests (older shapes decode; later values read as unknown). docs-check OK. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the cable port removal undoes every port Darkbloom set up, service first, and says what is left R5-2 (pair-2, 2026-11-04): - `darkbloom uninstall` on the MacBook gave up with "More than one port qualifies (rdma_en2, rdma_en1, rdma_en6); choose one, for example … --device rdma_en2", naming a disconnected port, after it had already forgotten the pairing. - The restore wrote the port's bridge entry before it removed Darkbloom's service, which left en6 in saved bridge0 and in its own "Darkbloom Cluster Link (en6)" service ("not isolated: member of bridge0"). - The restore ran every command (joined with "; "), yet a failure said "the commands after it did not run". Fix: - ClusterLinkRepair.removeIsolation undoes every port Darkbloom set up (its records, and its own services whose record is gone) under one approval (ClusterLinkIsolationRequest.Purpose.restore takes them all; the prompt names them); `--device` still names one. The uninstall and `cluster link --remove` without `--device` never ask for a choice. - ClusterLinkIsolationRestore.commands: the keeper, Darkbloom's service, a leftover address, then the bridge entry, the services switched back on (which apply it) and the live bridge member. - A restore stops at the first failing command (`set -e`, as an isolation and the manual script). What is left is read per port: done ports are forgotten, the rest are named (ClusterLinkRepairResult .remaining, JSON `remaining`) in a message that now says truthfully the commands after the failure did not run. - The uninstall forgets the pairing before the cable step (it tells the other Mac over the cable); a failed cable step now says the pairing is already forgotten, that only the cable port setup is left, and that ` uninstall` again finishes it (ProviderUninstall.cableLeftNote). Not changed: the first version's address-only removal still asks for a port among several recorded aliases. Docs: two-mac-cluster.md (Uninstall) and cli-reference.md. Changelog: one bullet. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the member waits for the leader's setup after an update After the pair restarted into 0.10.8, the member started its part from the setup saved for 0.10.7 six times; each ended within a second with "Installed input identity or SHA-256 differs" until the leader synced the new setup (R5-4, about 2 min of the 2 min 33 s outage). ClusterService.supervise now compares the member's installed worker with its saved setup's pin before a cluster part starts. When they differ it starts nothing, rewrites nothing, and says once "waiting for the other Mac's setup for v". The part's own identity and SHA-256 checks are unchanged. The control leader, waiting for both Macs to answer with one build, checks again every 5 s instead of every 60 s. Co-Authored-By: Claude Opus 5.5 * fix(update): end `darkbloom update` once this Mac runs the new release On the M5 Ultra pair, Mac B's `darkbloom update` waited its full 600 s and ended "Still waiting after 600 s" although Mac B had restarted into 0.10.8 (R5-3). The command waited for its own request to reach `restarting`, but the restarted service had already published `idle` with no request, running 0.10.8. ClusterServiceUpdateRequest.restart now also ends, with a new `.restarted` outcome, as soon as the service's progress says this Mac runs the target release, and says so. Co-Authored-By: Claude Opus 5.5 * fix(cluster): `cluster stop --service` stops this Mac when the other is off On pair 2, the leader's `darkbloom cluster stop --service` failed (exit 1) once the MacBook's service was already off, and left the leader's service and login agent running (R5-1). Only `--local-only` finished it, and the error did not say so. OnboardingLive.localStop now marks the one failure where this Mac stopped serving and the other Mac did not answer (ClusterOnboardingFailure.otherMacUnanswered). Cluster.Stop.finishStop then still removes this Mac's service and login agent and says what happened on each Mac. A local drain that did not finish, and a stop forwarded to the leading Mac, still fail and keep the service. Co-Authored-By: Claude Opus 5.5 * terminal: every live line stays one row, its reason shortened, never wrapped A 0.10.8 leader started Gemma 4 26B tensor parallel next to an M4 Max. Its live line repeated end to end ("▗ Loading Gemma 4 26B on both Macs (starting; this Mac's part ended (exit 1: another update operation owns the lock (pid 952 ▖ Loading …"). The row was cut to a character count, but the terminal drew it wider (a petal or ellipsis shown two columns wide, a wide character, a control character in the reason). So it wrapped, and each turn of the petal climbed back only one row and left the wrapped start behind. The two shared renderers now draw every live row the same way: ClusterOnboardingTerminal, used by the cluster screens, and DarkbloomCommandLook, used by start, stop, restart and update. - ClusterOnboardingBrand.liveText fits a row to the room (width - 6). It counts wide characters as two columns and turns control characters into spaces. A row that ends with its time (" · 1 min 3 s") keeps the time and shortens the reason before it. - Line wrap is turned off for each redraw and back on in the same write (ESC[?7l … ESC[?7h), so a row the terminal counts wider is cut at the edge, never wrapped. The cluster console's signal handler turns wrap back on too. - DarkbloomCommandLook reads the window width at each redraw, as the cluster console already does. Download progress (ModelDownloadProgress) already re-reads the width, clips its ASCII line and prints only on change when plain, so it is unchanged. Onboarding checks: 1305 passed. They include the user's long line in a pty at 80 and 40 columns with the petal turning, and plain mode (NO_COLOR, TERM=dumb). Red on the previous commit with only the interface stubbed: 8 failed. swift test: DarkbloomCommandLookTests (a new 40-column test with a narrowed width), ClusterOnboardingPeerLabelTests, ClusterServiceStopReasonTests and ModelDownloadProgress: 63 passed. DarkbloomCommandLookRunTests has 5 issues with the dev identity ("darkbloom-dev start" against "darkbloom start"); the same 5 fail on the base. Co-Authored-By: Claude Opus 5.5 * docs: every live line is one row; changelog bullet The CLI reference now says how the live line stays one row: - it is fitted to the width at each redraw; - control characters become spaces; - a long reason is shortened and keeps its time; - line wrap is off while the row is drawn. The fragment gains the user-facing bullet. Co-Authored-By: Claude Opus 5.5 * cluster: the joining Mac shows the start's steps, bar and each Mac's part The owner asked that the Mac that joins a pair show progress at each step, not sit in the dark. On top of the follow screen's wait (merged), the joining Mac now reads the start's progress the leading Mac publishes (its status reply's `start`, carried in ClusterOnboardingLeaderStatus). - Once the start publishes a step, the joining Mac opens its own "4/4 Start" heading. Right under it the live rows show the step and its time, a bar of the real bytes during a copy or download, each Mac's part (this Mac first, with its layers), and what comes next. Each finished step is said once ("✓ Files (9 min 12 s)"). Every row fits the room a live row has (window less 6) at 80 and 40 columns. - A plain transcript says each step, each part change and a copy's bytes about every 10% and 30 s, once each, with no bar or escapes. - Each new step gets the follow's whole bound again, and copy bytes that still move reset the wait for the start, so a long copy no longer ends in a ✗. - With an older leading Mac (no `start`), the screen is unchanged. Onboarding checks: 1354 passed (the joining-Mac checks failed 22 before the wiring, with only the interface in place). Filtered swift test: 21 tests in 2 suites. docs-check and changelog-check OK. Co-Authored-By: Claude Opus 5.5 * fix(integration): the round 5 runners compile and the onboarding checks close each terminal once - OnboardingChecks: TerminalRun closed its pseudo-terminal in release() (follow-wait) and again in deinit (screen-sharing note); the second close hit a later run's reused descriptors, so random flows hung at "Checking the cable". Closed once now. - ClusterService: a comment named the DevNet display name literally, which test-provider-identity.py refuses outside the identity JSON. - ClusterLinkApproval.request(wiredLimit:) moves beside GLM5NextWiredLimitRequest, so the link runner compiles without the GLM memory closure. - run-flow.sh compiles ClusterOnboardingSoloServing.swift, as the other runners do. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a port whose only service is Darkbloom's: reconfigured in place, removed through SCPreferences R5-2 on pair-2's MacBook (macOS 27.0): `networksetup -removenetworkservice` refuses a port's last service ("You cannot remove Darkbloom Cluster Link (en6) because there aren't any other network services on Thunderbolt 2."). On a Mac whose Thunderbolt ports start in the Thunderbolt Bridge, Darkbloom's service is always the port's only one, so the restore stopped at its first command every time, and the setup's repair (remove, then create) failed the same way. - Setup (ClusterLinkIsolationPlan.commands): an existing Darkbloom service is reconfigured in place (switched on, -setmanual, -setdnsservers Empty, -setv6LinkLocal), never removed and made again. - Restore (ClusterLinkIsolationRestore, ClusterLinkLastService): where Darkbloom's service is the port's only one, it is removed through one `scutil --prefs` session (remove the service and its link in the current set, the IPv4 order without it, commit, apply), after PlistBuddy guards on its name and device and with a read-back that it is gone. The service ID, the set and the order are read before the prompt (`plutil -extract` of the world-readable preferences: new read-only tool commands); only validated IDs reach the commands, and every removal in one approval leaves all removed IDs out of the order. Unreadable preferences guess nothing (probeFailed). A port with other services keeps `networksetup -removenetworkservice`. - The AppleScript line now escapes backslash and double quote. - Kept: `set -e`, "Still to undo", `remaining`, one approval for every port, the service before the bridge. Proven by hand on p2-max as root with the same command shape: en6 (22:31:33Z) and en1/en2 (22:32:11Z) exit 0, no Darkbloom service left, macOS put en6 back into bridge0 live by itself, both Thunderbolt Bridge services enabled. Not run through the app's prompt there (Darkbloom is uninstalled on it). Docs: two-mac-cluster.md (Uninstall), cli-reference.md. Changelog: one bullet. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a service still there after the SCPreferences removal stops the restore; IDs are ASCII Review of bac9a58c4f (r5-2-lastservice-review.md): - Finding 1: `scutil --prefs` exits 0 even when its `commit` fails, and the read-back `! PlistBuddy … Print …` does not stop a `set -e` script, so the bridge entry and the services were still switched on beside Darkbloom's service: the port in both, R5-2's own bug, and "the commands after it did not run" untrue. The read-back is now `if PlistBuddy … Print …; then exit 1; fi`. - Finding 5: ClusterLinkLastService.isID accepts ASCII 0-9, A-F and a-f only (Character.isHexDigit accepted fullwidth digits). Check: the cluster link checks run the generated restore line in /bin/sh with stubs for PlistBuddy, scutil, networksetup and ifconfig (paths rewritten in the check's copy only): with scutil removing nothing it exits non-zero and no later step runs; with the service gone it runs to the end. A fullwidth digit is refused. Co-Authored-By: Claude Opus 5.5 * fix(integration): the runners compile the start progress, and the onboarding checks fit the merged flows - Control, installed-session, diagnostics, console and placement-flow runners compile ClusterOnboardingStartProgress.swift (member progress), which ClusterControlLeadership now uses. - The onboarding checks' own alarm is 600 s: with follow-wait, solo-serving and start-progress checks the run takes about 300 s, the old bound. - The plain start-progress check counts each row once per wait: a start through Darkbloom restarts both parts as cluster members after the registration, and that second wait shows the rows again, truthfully. - StartProgressChecks.swift ends without a blank line (git diff --check). Co-Authored-By: Claude Opus 5.5 * fix(integration): the GLM image admission runner compiles the start progress CI's Cluster Focused Checks (PR #1792, job 126919032698) failed to compile focused-GLMImageAdmissionChecks: ClusterOnboardingFlow.swift:1199 names ClusterOnboardingStartProgress, which fix/cluster-member-progress added in its own file. 888b43e041 added that file to five runners; this is the sixth that compiles ClusterOnboardingFlow.swift. Locally: exit 0, 40 CPU checks pass. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the pasted fallback runs as the script: one root shell under set -e Integration review of 6a3874827c: where no manual script could be written, the fallback printed each command behind `sudo `. Two of the SCPreferences removal's lines then failed when pasted: `sudo if …; then exit 1; fi` is a syntax error, and in `sudo printf … | scutil --prefs` only printf ran as root, so scutil's commit failed. ClusterLinkIsolationRequest.manualCommands is now one block: `sudo /bin/sh -e <<'DARKBLOOM_CLUSTER_LINK'`, the same commands one per line, and the delimiter. No generated line can be the delimiter (each starts with a path or a shell keyword). Setup's and every restore's fallback take the same form; the first version's single commands (ClusterLinkPrivilegedRequest) are unchanged. Check: the printed block, pasted in /bin/sh with the stubs of the 6a3874827c check and `sudo` passing through, runs exactly the script's steps and stops where it stops; setup's and the restore's blocks are one root shell with the commands unchanged. The removal's doc comment is rewrapped to 120 columns. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a Mac that stopped clustering serves normally again 0.10.8: a Mac left with a saved pair start (its other Mac no longer taking part) ran its pair part as a cluster member with no ordinary models: online, no traffic. Every ordinary way back (start, the app's Go Online, Autopilot enroll, restart, start --solo) acted on the pair or was refused, and 0.10.9's update and watchdog guards read the same stale start. - Whether the pair runs here comes from what runs (ClusterPairWatch): the saved start, the other Mac's real answers over the link, and whether the pair has served. The cluster service publishes the verdict (pairRunning, pairNotRunning); ClusterService.pairServesHere uses it, so update and the watchdog restart and revive single-Mac serving on a Mac whose pair doesn't run, and keep the existing protection where it does. A 0.10.8 service with no verdict is read by its control mode. - start --solo is never refused for a stale start: it stops the leftover part (clears the saved start, waits for the serving lock), then serves alone, saying so in one line. A script, the app's Go Online (start --model) and Autopilot enroll do the same; in a terminal, start offers "Serve on this Mac alone" (the default when the other Mac isn't answering) or "Start the pair". stop and restart act on what runs here. - The leftover part doesn't hold the Mac forever: after 15 minutes without an answer from the other Mac the service stops its part (freeing the lock) and says why with the command to serve alone; it starts the part again when the other Mac answers. A reboot of a few minutes keeps the pair. - status says the pair isn't running here and the one command to serve alone. Tests (red: the new suites don't compile on 8e931784cb): ClusterPairWatchTests, UnpairedMacServesNormallyTests, stale-pair command runs in ClusterPairCommandsTests, and the reboot/give-up check over the real lease exchange in ClusterControlChecks. Co-Authored-By: Claude Opus 5.5 * docs(cluster): going back to serving on one Mac, and the 0.10.8 workaround - two-mac-cluster.md: "Going back to serving on one Mac" (what "the pair runs here" means, start/stop/restart/update/watchdog on a Mac whose pair doesn't run, the 15-minute give-up, and the 0.10.8 steps: cluster pair --status, cluster pair --forget , start). - cli-reference.md: start, stop and restart while the pair doesn't run here. - agent-setup.md: rule 11 and a troubleshooting row for "online, no requests" after clustering stopped. - architecture/inference.md: ClusterPairWatch's verdicts and who reads them. - start's help text; changelog fragment unpaired-mac-serves-normally.md. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a loading pair is never stopped without asking A pair whose other Mac answers but that hasn't served in its first 15 minutes (notServing: a large first load, or the coordinator away after a pair restart) read as "not running here", so the app's Go Online or Autopilot enroll clicked by mistake, a script's start, restart, stop, and update with a leftover single-Mac job cleared the saved start and stopped the pair's part. - ClusterService.pairKeepsLock: update and the watchdog leave the serving lock to the pair while it runs here or its other Mac answers. - Start.pairStart, Restart.pairRestart and Stop.pairedStop: while the other Mac answers, only start --solo and the terminal's choice serve this Mac alone; the other forms act on the pair as while it runs (stop on a follower would otherwise be undone by the leader's next lease). A Mac whose other Mac is gone or whose pair is stopped is unchanged. Tests (red first): ClusterPairWatchTests.pairKeepsLockWhileTheOtherMacAnswers, UnpairedMacServesNormallyTests.loadingPairIsNotStoppedUnasked. Co-Authored-By: Claude Opus 5.5 * ci: the cold-retry test follows the two remaining build directories Co-Authored-By: Claude Opus 5.5 * fix(cluster): time asleep doesn't count toward the pair's 15-minute windows ClusterControlClock.seconds is CLOCK_MONOTONIC_RAW, which keeps counting while macOS sleeps, so a Mac waking after more than 15 minutes asleep could give up its part on the first tick, before the other Mac's next answer, and reload the model when it came back. - ClusterControlClock.awakeSeconds (CLOCK_UPTIME_RAW, paused in sleep). - ClusterPairWatch.tick(raw:awake:...): the windows run on the awake clock; each new answer from the lease clock is placed on it no earlier than the previous tick. ClusterService.watchPair uses it. A Mac whose other Mac stays gone still gives up 15 awake minutes after its last answer. Tests (red: tick(raw:awake:) doesn't exist): ClusterPairWatchTests .sleepDoesNotCount and .startWindowSkipsSleep. Co-Authored-By: Claude Opus 5.5 * fix(cluster): serving alone on the following Mac says the leader may start its part again A following Mac records its leader's start from the leader's next accepted lease, so the start that serving alone clears there comes back while the leading Mac keeps the pair started; its part then waits for single-Mac serving to stop. The line said only "its saved start is cleared". - ClusterPairSummary.servingAloneLine on the following Mac adds: while the other Mac leads with the pair started, it may start this Mac's part again once single-Mac serving stops here; `darkbloom stop` on it stops the pair. - two-mac-cluster.md and the changelog fragment state it as a known limitation (and that sleep doesn't count toward the 15 minutes). The proper fix (the follower declines the leader's start after the person's choice, with a reason both screens show) is left for a follow-up. Tests (red first): UnpairedMacServesNormallyTests.followerServingAloneIsTruthful. Co-Authored-By: Claude Opus 5.5 * ci: test each tree once, one plan routes every job, no audit-only Macs - provider-plan.yml (new, shared by CI (dev) and CI (master)): the classifier, the tested-tree lookup (scripts/ci-tested-tree.py) and the run's one route request, with the caller's Linux lanes. A run whose tree a completed, successful run of the same workflow file from this repository recorded (artifact ci-tested-tree-, uploaded by the gate) selects no component; any doubt tests. - provider-tests.yml takes the plan as inputs. Pull requests and pushes run the same jobs; only pushes save caches. A push of a tested tree runs one build-only job, Refresh build caches, for the components it changed. - The classifier selects pushes by their diff like pull requests (no full-run rule for default branches, no push-only cluster rule). - Cluster GPU Tests run whenever the cluster jobs run. - Provider Unit Tests Summary is folded into the shards: each audits its own selections against `swift test list` of its own build (provider-test-shards.py audit-job; the last shard checks that the plans cover the list once) and reports its own coverage. - Cluster Metadata Checks run first in Cluster Focused Checks. - Release Integrity and Docs Lint read their Linux lanes of the plan's route. Only the lookup, the component choice and the gate stay GitHub-hosted. - CI (dev) pushes are no longer collapsed: each push runs, and a tested tree costs only the plan. Co-Authored-By: Claude Opus 5.5 * ci: a third Swift build cache tier keyed on the toolchain and the MLX pins Keys nest MLX tier > dependencies > recipe > commit (v3), so a restore key matches each tier by prefix. The MLX tier binds the toolchain, the checkout path and the libs/mlx, libs/mlx-swift and libs/mlx-swift-lm gitlinks (nested ones included); restore-mtimes keeps SwiftPM to rebuilding what changed, and a failed build over it builds once from nothing. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a pair Mac follows the other Mac forward to a newer release at once The pair's coordinated update moved an older Mac only at the shared 30-minute slot, and only the rollback was followed between slots. A Mac whose partner updated alone (single-Mac updater, watchdog, manual update, asleep at the slot) stayed behind, and after R5-4 the newer member waits quietly for a leader setup the older leader never makes. The minute's follow check now also returns .otherMacNewer when the other Mac runs a strictly newer release that is not quarantined here; with automatic updates on the supervisor runs the pair's cycle at the next tick (once per release, then the slots), which finds the other Mac ready (ClusterPairUpdate.partnerState: running == target). With them off it logs the version and `darkbloom update`. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the start's ✗ names a version split, the Mac behind and `darkbloom update` The start-wait ✗ read the other Mac's whole service status but never compared its version (pairUpdate.running, published by supervisors from 0.10.7 on) with this Mac's, so a pair split across releases looped on 'its service reports its part running and no error…'. errorLines now leads with both versions and the command on the Mac that's behind, in either direction; one version or an unknown one keeps the lines as before. Co-Authored-By: Claude Opus 5.5 * fix(cluster): Connect's first line says "Allow macOS permissions." The owner asked to rename "allow macOS password" to "allow macOS permissions". ClusterOnboardingDriver.approvalsLine now reads "Allow macOS permissions." and, over SSH, "Allow macOS permissions here and on this Mac's screen (Screen Sharing if headless)." The lines that say what each prompt literally asks are unchanged. The onboarding checks and a ProviderCore test assert both lines word for word; the docs that quote the line and the 0.10.9 Screen Sharing changelog fragment are updated. Co-Authored-By: Claude Opus 5.5 * test(cluster): two idle M5 Ultra 256 GB split GLM's pipeline about evenly The M5 Ultra pair's mode question offered GLM-5.3-Flash's pipeline as "this Mac 1 layer / the other Mac 44 layers". On the recorded M5 Ultra, both Macs sampled idle, the forced pipeline is cut 24 (24 / 21 layers), both ranks loading now and admitting 65,536 tokens: a split that degenerate comes from a Mac whose sample admitted about 10 GB, not from the planner's arithmetic. This check pins the even split on idle Macs. Co-Authored-By: Claude Opus 5.5 * test(provider): a pair's lanes go on, and are counted, while a request reserves (red) A pair's reservation holds the engine queue until both ranks answer at their next step boundary. Every running lane's token is answered on that queue, and rank 0 waits a bounded time each step for those answers, so a reservation stalls every lane. And a request reserving, or waiting to, is counted nowhere: the heartbeat advertises its lane as free, the coordinator sends one more, and the engine refuses it for capacity. Four checks, red on this base: - a running lane's token waits for another request's reservation; - a capacity read counts neither the request reserving nor the one queued behind it (`waitingRequests` 0); - a request beyond the lanes waits for that reservation before it is refused; - the heartbeat's `num_waiting` is 0 while a request is being reserved. Co-Authored-By: Claude Opus 5.5 * fix(cluster): single-Mac serving blocking the pair is said on both screens, and nothing loops on it 0.10.9 DevNet, pair-2 (f1): with single-Mac serving (process 68099) on the joining MacBook, the leader showed the block, but the joining Mac said "registering with the coordinator" for minutes; `cluster status` said "Both Macs keep trying by themselves"; and the leader's part ended and restarted every 38 s. - The joining Mac's window reads single-Mac serving on both Macs before each look of the leader and shows the same ✗, naming its own provider, `darkbloom stop --solo`, and that the leading Mac offers the stop. The leader's block line is the block (`followed` .soloBlocked), never an offered pair to wait on. It follows the start by itself once single-Mac serving stops. - Each Mac's status reports single-Mac serving whenever no part of its own holds the lock, not only once a part is wanted, so the leader sees it before starting; it also publishes `heldBack`, why its part can't start. - The leader's service reads the member's held-back reason at each sync and doesn't start its part while the other Mac reports one (`ClusterControlPartChoice. waitsForOtherMac`): no 38-second start-and-end loop. Serving alone never waits. - `next` says what to run on both Macs; a scripted `darkbloom start` ends its wait at once for this reason (`isFinalReason`). Co-Authored-By: Claude Opus 5.5 * fix(provider): the usage history's warning goes to the running identity's log subsystem It named production's `dev.darkbloom.provider` in every build, so a DevNet app's `darkbloom-dev logs` never showed it. Co-Authored-By: Claude Opus 5.5 * fix(cluster): each mode's line fits the window as it is now, and redraws on resize R6-2 (M5 Ultra pair, DevNet branch.81): each mode's line in the mode question was cut at 120 columns ("… the other Mac 44 layers) · ser…"), losing how many requests the mode serves at once, and a window widened to 220 columns never redrew it: the list fitted its rows once, to the width it opened at. - ClusterOnboardingConsole.chooseFitting: options asked for their text at every draw with the room a row has then (nil: the whole line). The default (and a plain terminal) shows the whole lines. - The colour list (pick) reads the width at every draw, redraws when it changes (checked between keys, every 100 ms), turns wrap off while it draws (ESC[?7l … ESC[?7h), and climbs back by the rows a narrower window shows each drawn row on, as the live rows do since 1693f0c70a. Lists of plain strings keep their cut, now counted in display columns. - ClusterOnboardingDriver.modeLine(_:recommended:room:): too wide, a line loses the split, then what each Mac does, then the long words ("106 tok/s", "serves up to 8 at once", "recommended"), as the recommendation's line does. The mode's name and how many requests it serves at once are never cut: where one row cannot hold them they take two. The mode question uses it. Onboarding check modeLinesFitTheWindowAsItIsNow: GLM-5.3-Flash's two modes in a colour pty at 220, 120, 80 and 40 columns, and one list resized 120 -> 220 -> 80 -> 40 -> 120 while open: redrawn each time, every row within the window, no mode row cut, each mode's name and concurrency whole, the whole pipeline line where it fits; plain at 40 columns prints the whole lines. Red on the previous commit with only modeLine(room:) stubbed: 47 of 71 failed. Co-Authored-By: Claude Opus 5.5 * docs(cluster): the mode question's lines fit the window (inference.md, changelog) Docs Impact on PR #1797 asked for the canonical inference doc; this documents d3d2e76911's fitting and adds the changelog bullet. Co-Authored-By: Claude Opus 5.5 * cluster: the joining Mac ends with the leading Mac's outcome, never its own verdict 0.10.9 DevNet, pair-2 (f2, 00:23:20Z): 6 s after its part registered with the coordinator, the joining Mac's window ended with "✗ Not serving: This Mac isn't verified by Apple yet …" and "Choose Retry on the other Mac". The leading Mac kept waiting and showed "✓ Serving Qwen 3.8 27B through Darkbloom on both Macs" 41 s later. On an offered status the joining Mac had run its own pairServing wait and ended on its own App Attest state. - A state that clears by itself keeps the joining Mac waiting: Apple's verification, the coordinator's pairing, registering, the leader still deciding. The live row reads "Waiting for Apple to verify this Mac (Darkbloom retries by itself) · n of 15 min"; plain output says it once. Offered is its own stage with the whole bound, as the leader's wait. followPair is gone and the joining Mac never calls pairServing. - Its final ✓/✗ is the leader's. ✓ comes from the leader's status. The leader's screen ✗ is published as ClusterOnboardingStartProgress.failed (title, lines, retry) in ClusterControlReply.start, each Mac's name kept as a token, so the joining Mac shows the same ✗ named from its side. It counts for 30 minutes after the leader's screen ends; a new step published by a leader screen clears it. A later phase reads as unknown on an older Mac. - "Choose Retry on the other Mac" appears only under that ✗, when the leader's screen shows Retry: no longer mid-start, nor in the joining Mac's timeout. - An older leader publishes no outcome: the joining Mac waits until the stage's bound, then "✗ Not serving: The other Mac (…) didn't say how its start ended within 15 minutes.", the last state, and where to look. - The joining Mac's own blocking reasons (a different build) still end it at once; the single-Mac serving path is untouched (fix/solo-block-both-screens). Onboarding checks: 1540 passed, 0 failed. FollowFinalChecks failed 20 on the base with only the data interface present (the f2 run printed the field's exact ✗); seven older checks that encoded the old verdict were rewritten to these rules. Filtered swift test (ClusterOnboarding), sandboxed away from ~/.darkbloom*: prod 28 tests in 2 suites + 1, dev the same. docs-check and changelog-check OK. Co-Authored-By: Claude Opus 5.5 * fix(cluster): only the leading Mac waits on the other Mac's held-back reason The leader keeps the other Mac's reason (`peerHeldBack`) in memory and refreshes it only while it leads and runs the cluster (`syncMembers`). If control moved to the other Mac, that reason stayed, and this Mac's part, now a member, never started: the new leader's part then waited for its missing follower and ended every 38 s, the loop the rule exists to stop. `waitsForOtherMac` now takes `leads`, and the service passes `leadsAndRunsCluster()`. Red: ClusterControlChecks failed to compile (no `leads`), and the new check "no longer leading: never waits". Green: 682 passed, 0 failed. Docs: the rule and the status fields in docs/architecture/inference.md, the block's `reason`, `next` and exit 3 in docs/provider/cli-reference.md (Docs Impact), and a missing full stop in the agent-setup troubleshooting row. Co-Authored-By: Claude Opus 5.5 * fix(cluster): single-Mac serving steps aside for a started pair unless chosen; blocked ends never set the approval aside From "none of the steps worked" (solo-steps-failed.md §3–§5): - Self-heal for the 0.10.8 → 0.10.9 rollout: when the pair is started and wants this Mac's part ("cluster:" key) while single-Mac serving holds the lock, and no choice of single-Mac serving stands (`ClusterSoloChoice`), the cluster service runs `stop --solo` once per process, logs it and leaves a note `darkbloom status` shows. `start --solo` / "Serve on this Mac alone" record the choice; an explicit pair start here (onboarding serve, `start` → pair) and `stop --solo` clear it; a Mac updated from 0.10.8 has none, so the pair wins. Never when no part or only the degraded server is wanted, so it never fights #1793's "pair isn't running → serve alone". - Ends caused by the held lock (either Mac held back, or the lock's words) don't count toward the local-only fallback; when the blocker clears (step aside, offer, or the other Mac's held-back reason gone) the count resets and a `failing` set-aside approval is dropped, so the pair is offered to Darkbloom again at once. - The version split is said before the single-Mac ✗ (`blockApplies`). Co-Authored-By: Claude Opus 5.5 * fix(cluster): a version split is named everywhere, ends the wait at once, and single-Mac updates bring the pair along - ClusterOnboardingVersionSplit: both versions, the Mac behind and the build's own command (darkbloom-dev on DevNet). The leader's start reads it before the parts start, every few polls of the wait (before single-Mac serving), and before a Retry; it offers Check the versions again / Leave, never a Retry loop. The joining Mac's wait ends at once on it, from its own side. - The status line both Macs show carries a Mac-neutral reason; darkbloom status / cluster status --json read it as notServing with a final reason, and next names the Mac to update for each window. - The R5-4 member wait line and the leader's same-build wait line name the other Mac's version and the command (asked over the cable, at most every 30 s). - The follow check also follows a partner that is updating to a newer release. The provider's background updater, on a Mac whose pair actually runs there (ClusterService.pairServesHere), asks the cluster service to restart into the release with the other Mac; the watchdog never installs under a running pair. A Mac whose pair is gone simply updates. - Docs (two-mac-cluster.md: pair owners' top line, different versions) and the changelog fragment. Co-Authored-By: Claude Opus 5.5 * fix(cluster): a pair the coordinator's catalog won't pair says why DevNet 2026-11-05 (0.10.6-dev.branch.81): a Gemma 4 26B tensor-parallel pair offered under devnet/gemma-4-26b-qat-4bit/s1 sat on "waiting for the coordinator to pair both Macs" (cluster status: loading, exit 3) for 11+ minutes. The coordinator refused it on every one-second pass with `serves_model`: its pair check needs a model-catalog row for each member's model (modelAllowedByCatalogLocked), and DevNet's catalog has no Gemma, though its pair-approval catalog does. The coordinator tells neither Mac. The member registration was not the cause: a member already sends an empty ordinary inventory and exactly its setup's model in cluster_models (ClusterMemberRegistrationTests cover it). - An offered part reads the coordinator's public /v1/models/catalog once after it registers; when the catalog doesn't list its model it writes "Notice: The coordinator does not pair Macs for : its model catalog does not list it" (ClusterLocalServing.catalogRefusal). An unreadable catalog says nothing; the part keeps running. - The service reads that notice as the part's current one; the setup screens on both Macs end at once with it (pairLook, pairServing), and cluster status reports not serving with it instead of loading (ClusterPairSummary.ownState). Tests (red first): ClusterLocalServingTests.aPartOfferedForAModelTheCoordinatorsCatalogDoesNotListSaysSo, ClusterPairCommandsTests.ownState. Co-Authored-By: Claude Opus 5.5 * fix(cluster): `stop --solo` on the wrong Mac stops it on the other Mac; a blocked pair's `start` never serves alone - `stop --solo` where nothing runs here asks the other Mac (its status) and, with consent or `--yes`, stops single-Mac serving there (`.stopSolo`); declined, it says where to run it and exits 1. Its "nothing to stop" line no longer suggests plain `stop` (solo-steps-failed.md §3.3). - #1793 coordination: while single-Mac serving blocks a started pair whose other Mac answers, `start` goes to the pair (`.openScreen` / `.startPair`), never `.choose` or serve-alone (pinned by a test); "set up" means the job is loaded (`LaunchAgent.singleMacSetUp`), not that the plist exists. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the version split's hunks sit apart from the single-Mac and follow-final branches The joining Mac reads the versions on its own cadence at the top of its wait loop, the final-reason check is its own line, and the checks file is listed beside the onboarding sources, so this branch merges cleanly with fix/solo-block-both-screens and fix/follow-final-outcome. No behavior change. Co-Authored-By: Claude Opus 5.5 * fix(cluster): an orphaned pair part is never single-Mac serving; a check proves the stop sticks - `ProviderInstanceHolder.singleMacServing` excludes the part this Mac's cluster service recorded, even once launchd adopted it (its arguments read like `start --local`), so nobody is told to `stop --solo` what it can't stop. - `SoloStopSticksTests`: after the stop, a watchdog tick doesn't revive it, an update restarts the pair and not it, and a login or 0.10.8's updater that starts it anyway meets the step aside while the pair's blocked ends never cost its approval. - Docs: the step aside, the recorded choice, the reset of the fallback, and `stop --solo` on the wrong Mac. Co-Authored-By: Claude Opus 5.5 * docs(cluster): the agent's troubleshooting row says single-Mac serving steps aside by itself Co-Authored-By: Claude Opus 5.5 * fix(provider): a pair's lanes stream while it reserves, and count what is being admitted A GLM-5.3-Flash tensor-parallel pair on branch.81 decoded at 7.5 tok/s (min 2.7) under DevNet's soak and refused 6 dispatched requests for capacity. Two causes in DistributedCBv2Engine, both on the pair's one serial queue: - A reservation ran on the engine queue and held it until both ranks answered at their next step boundary. Every running lane's token is answered on that queue, and rank 0 waits a bounded time each step for those answers, so a reservation stalled every lane and the step that answers it. Since R4-9 the bridge awaits admissions, so several queue back to back. Reservations now wait on `admissionQueue`, one after another; the engine queue only checks, holds a lane and completes the admission. - A request waiting for its reservation, or in it, was counted nowhere: the published capacity said its lane was free, the coordinator sent one more, and the lane check refused it. A submission now holds a lane from acceptance (`holdLane`, `admitting`): the lane check counts it and `capacity()` reports it as `waitingRequests` (heartbeat `num_waiting`). A cancel of another request now lands at once; a cancel of a request in its reservation, or waiting for it, stops it once admitted; a shutdown waits for a reservation in flight and stops its request. The R4-9 check that pinned a cancel waiting for another request's reservation now pins it landing at once. Co-Authored-By: Claude Opus 5.5 * cluster: the joining Mac never ends on an earlier start's published ✗ Review of #1798. The leading Mac's ✗ (ClusterOnboardingStartProgress.failed) counts for 30 minutes regardless of its process, and a new pairing keeps the record; only the new screen's first step clears it. The joining Mac's follow read it on its first look, so pairing again within 30 minutes of a ✗ that was left ended the joining Mac at once with that ✗ and "Choose Retry on the other Mac", before the leading Mac had chosen a model (its first step comes after its own service start). A ✗ now counts as this start's outcome only once this follow saw the leading Mac's screen publish a step (which clears any earlier ✗ in the same write); before that it is not shown, not even as the 4/4 heading. Red: the new check ended with "✗ Not serving: This Mac isn't verified by Apple yet." and Retry; onboarding checks 1557 passed, 2 failed. Green: 1559 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): notServing's doc comment back on notServing #1798 split the ✗ block out of notServing (notServingBlock) and left notServing's comment stacked above the new function's. Comments only. Co-Authored-By: Claude Opus 5.5 * fix(cluster): GLM on 128 GB Macs: offer only what loads; gpu-limit step or "needs more memory" Owner: "ensure it only shows the option that is possible, i.e. for there only pipeline is possible as an option" (a user's M4 Max 128 + M5 Max 128 could not load GLM-5.3-Flash). - One rule for the Macs whose GPU limit Darkbloom raises: ClusterGPUMemoryLimit.raisedByDarkbloom (M5 Macs with 128 or 256 GB, by the chip's own name). GLM5NextGPULimitEligibility delegates to it, and ClusterDeviceProfile.withGPUMemoryLimitRaised is nil on any other Mac, so the memory verdict never counts a raise on an M4 Max that gpu-limit refuses. - The model row, when nothing fits as the Macs are: plans again with the eligible Macs raised; if a placement fits, the row is blocked with the `darkbloom cluster gpu-limit` step (the Mac, its part's GPU need, macOS's limit, the raised limit); otherwise "Needs more memory" with the reason (the GPU limits, or the model's size) instead of "Too large ... even with every application closed". Nothing loads before. - The mode question is unchanged: GLMPairOfferChecks pins exactly the modes it offers on M4 Max + M5 Max, M5 Max x 2, M3 Ultra + M5 Max and M5 Ultra x 2, default and raised, and that each offered placement fits every Mac's GPU limit and its memory at rest. Red first: 5 placement checks and 3 provider tests fail without the fix. Co-Authored-By: Claude Opus 5.5 * fix(integration): the cluster runners compile ClusterOnboardingBrand.swift The mode lines' fit (#1797, d3d2e76911) measures rows with ClusterOnboardingBrand.textColumns in ClusterOnboardingFlow.swift; the control, installed-session, diagnostics, console and placement-flow runners compile that file without it and stopped at "cannot find 'ClusterOnboardingBrand'". Co-Authored-By: Claude Opus 5.5 * refactor(provider): publish a pair's capacity once its admission is settled `releaseLane` published the capacity on its own, so `complete` published a snapshot with the admitted request's lane free and not yet in `actives`, and published again a moment later. The caller now publishes once: `complete` on return (as it already did), the refused reservation after its release. The same queue turn, so the lane check and every count are unchanged. Also the bridge's comment on `submitAwaitingQueue` no longer says a reservation holds the pair's queue. Co-Authored-By: Claude Opus 5.5 * fix(cluster): two Macs of the same hardware are planned at the same speed, so the first pipeline offer is the split that loads R6-3 (M5 Ultra pair, DevNet branch.81): with nothing serving, right after production's pair stopped, the mode question's first offer for GLM-5.3-Flash's pipeline was "this Mac 1 layer / the other Mac 44 layers"; 24 / 21 loaded, and every later offer said 24 / 21 (R3-3, R4-7 and R4-13 saw the same flip). Why: until a model has served on the pair, ClusterHardwarePrior.absolute gives each Mac the rates of its own device index, about a second of GPU work sampled when the profile is read (and slow beside other GPU work, such as another app's pair unloading). A pipeline's time is each Mac's layers at that Mac's rate, so between two identical Macs any difference moves the whole cut to one end. In a placement check on two M5 Ultras 256 GB with GLM and the keyed link measured, an index 0.1% lower on one Mac turns 24 / 21 into 1 / 44. Once the pair has served, speeds are keyed by chip and OS build, the same for both, and the cut is balanced: the later offers. No cached plan or stale memory sample was involved; the adopted plan is still the one shown (83bc9b9480). Fix: ClusterHardwarePrior.sameHardwareIndex. Macs with the same chip, GPU cores and OS build take the fastest index any of them measured with the same benchmark, as the speed estimator already takes their ratio as 1. Other hardware keeps its own index. Order-independent, so both Macs compute the same plan. Checks: placement check "glm first offer" (indices equal: 24 / 21; this Mac's 0.1% or 3% lower, the other Mac's 0.1% or 10% lower: the same 24 / 21 and one rate; fewer GPU cores keep a slower rate). Red without the fix: 8 of 1586 failed (1 / 44 and 44 / 1). Two DistributedAutomaticBatchPlannerTests modelled a faster Mac by its index alone on the same hardware; their faster Mac now has more GPU cores. Changelog: cluster-mode-question-and-local-network-row.md. Co-Authored-By: Claude Opus 5.5 * cluster: each paired Mac names its part at the top, "Leading Mac" or "Joining Mac" The owner, 2026-11-05: "at the top of the Dark Bloom logo, if it's darkbloom cluster, put lead and or member … So the user always knows which machine is the leader, and which is the member." - A paired Mac's opening (darkbloom cluster, and the screen start, stop, restart and update open in a terminal) is titled "Darkbloom cluster · Leading Mac" or "Darkbloom cluster · Joining Mac" (ClusterOnboardingDriver .title(_:)), the screens' own words for the two Macs. Beside the mark it is the second row; without room for the mark, the heading line; in plain output, the first line, once. It is read from the saved role at each run, so a lead that moved is named as it is now. - A first setup, before the two Macs pair, keeps "Darkbloom cluster" alone; the pairing's own line then says which Mac leads. - Rendering only: no screen's text below the title changes. Onboarding checks: 1589 passed, 0 failed (the new role checks, both Macs at 80 and 40 columns and plain, failed 12 on the base; one older check updated to the new title). Filtered swift test (ClusterOnboarding|ClusterPairCommands| DarkbloomCommandLook), sandboxed: prod 28 + 105 tests passed. Dev: 28 passed; ClusterPairCommands has 72 issues in dev identity, the same 72 on the base without this change (its expectations name `darkbloom`, the dev build says `darkbloom-dev`). docs-check and changelog-check OK. Co-Authored-By: Claude Opus 5.5 * feat(cluster): gpu-limit on every Apple silicon Mac with 128 GB or more Owner, 2026-11-05: "yes widen, why wouldn't we". - ClusterGPUMemoryLimit.raisedByDarkbloom is capability-based: Apple silicon of any M generation (the chip's own name, no generation allowlist) with 128 GB or more. GLM5NextGPULimitEligibility delegates to it and gives the plain refusal (not Apple silicon; under 128 GB); the command prints it and exits 2. The planner's memory verdict counts an M4 Max's (or M3 Ultra's, M2/M1 Ultra's, M3 Max's) raise where it makes a split fit, so the model row names `gpu-limit` on that Mac first. - The values are the planner's ceiling (memory less 16 GiB, a sixteenth from 512 GB) and 95% wire limits; GLM5NextWiredLimitRequest still refuses any other value. - A Mac that does not report iogpu.wired_limit_mb or a wire limit is never changed: refused with the setting's name before any question. - Consent, macOS's administrator prompt, the boot job, the read-back before ✓ and --undo are unchanged; the prompt's "leaving macOS N GB" is computed. - Wording everywhere: "Apple silicon Macs with 128 GB or more". Red first: 5 placement checks and 3 of 20 provider tests fail on the M5-only rule. Co-Authored-By: Claude Opus 5.5 * fix(cluster): ✓ through Darkbloom only for a pair the coordinator serves publicly DevNet 2026-11-05 (0.10.6-dev.branch.82): a Gemma 4 26B tensor-parallel pair committed under the model approval devnet/gemma-4-26b-qat-4bit/s1 and both screens said "✓ Serving … through Darkbloom", cluster status `serving`, while every public request got 429 `cluster_not_public … (unqualified)`. The coordinator serves a session to any account only under a promotable parity qualification of its approval and mode family. Qualifications attach only to a build-pinned approval and a release derives them only for the models it declares public (ClusterPublicModels), so a model approval or a pair approval saved by hand serves its owner only. Branch.82's release block had no Gemma (DevNet's catalog lacked it when it was published), so the Macs could only take the hand-posted model approval. - ClusterPublicServingCheck.ownerOnlyReason applies that rule to the saved approval and the setup's mode family; each offered part writes the reason to its log after it registers (ClusterMemberPreparation.ownerOnlyReason). - pairLook and ClusterPairSummary.ownState: a pair that serves with that notice is "Not serving publicly: the coordinator paired both Macs but doesn't send public requests to this pair (…)", with what to do (ClusterOnboardingNotServing.notPublicRemedy), never ✓. The provider still can't see the coordinator's other public checks (account, data plane, member verification). Tests (red first): ClusterPublicServingCheckTests (DevNet's own approval entries), ClusterPairCommandsTests.ownState. Onboarding checks: 1508 passed. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the coordinator's wait says only what the Macs report, can be left, ends on a stop; the joining Mac follows a model change DevNet pair-2 (branch.81/82, 2026-11-05): - The 15-minute ✗ blamed Apple verification on two authorized Macs (the coordinator refused serves_model): pairServing kept the first reason it ever saw. ClusterOnboardingPairWait decides look by look; at the bound with nothing reported it says the coordinator didn't pair both Macs within 15 minutes (its own reason when known, e.g. #1799's catalog refusal). A trust word on Macs that report their authorization is the coordinator's, never Apple's. - q/Esc did nothing in the coordinator's wait: awaitPairServing now leaves on them, saying the pair keeps trying and to check with `darkbloom status`. A `cluster stop` from anywhere ends the leader's wait at once (its saved start is off) and the joining Mac's once the leader's status stays Stopped 20 s: 'Stopped (by `darkbloom cluster stop` on one of the Macs) …'. - R5-8: `darkbloom cluster` on the joining Mac follows a start the leading Mac publishes (a model or mode change, a Retry) instead of 'This Mac runs its part by itself … Close'. Onboarding checks (WaitHonestChecks.swift) failed first: 8 behaviour failures against 88740bd446's flow, the pure checks by compile. Co-Authored-By: Claude Opus 5.5 * docs(cluster): the coordinator's wait, leaving it, a stop, and the joining Mac following a model change Co-Authored-By: Claude Opus 5.5 * cluster: a color screen folds each finished step to one line; the whole flow goes to a log The owner, 2026-11-05: "Is there any way to also capture all of the flow in one space, instead of the next line keeps dragging down … instead of keep dropping down a million lines in the CLI." In a color terminal at least 40 columns wide (ClusterOnboardingTerminal only): - When the next step's heading comes, the step that finished folds to one line, "✓ 2/4 Pair (1 min 12 s)", above the lines that stay: the question before each choice with the answer taken (the pairing code among them) and any outcome block. The last step and the outcome stay whole. - It folds only when all of the step is still in the window (its rows, counted at the window's width now, under the window's height now): rows that scrolled off can't be redrawn, so a taller step is left as it is. A step that showed a ✗, or during which another command wrote to the terminal (sudo, darkbloom login, through `suspended`), never folds. - Each run's whole flow, plain and line by line, goes to ~/.darkbloom/cluster-setup/screens/screen-Z-.log (owner-only, the 20 newest kept). Its path is the last line ("Full log: …"); a ✗ block names it instead. - Plain output (pipes, NO_COLOR, TERM=dumb, narrower than 40 columns) is byte for byte unchanged, and writes no log. - Both Macs; the role title (2d702ae1d9) and the joining Mac's progress rows are unchanged. No screen text changes, so other branches' text merges. Onboarding checks: 1630 passed, 0 failed. The new fold checks (leading Mac at 80 and 40 columns and through a resize, joining Mac at 80, a step taller than the window, plain unchanged and no log, the ✗ block's log line), checked on a small terminal emulator of the raw output, failed 14 on the base with only the interface; one older check's bloom test now matches the bloom's own redraw. Filtered swift test (ClusterOnboarding|ClusterPairCommands|DarkbloomCommandLook), sandboxed: prod 28 + 105 passed. Dev: 28 passed; ClusterPairCommandsTests keeps its 72 dev-identity issues, as on the base (`darkbloom` vs `darkbloom-dev`). docs-check and changelog-check OK. Co-Authored-By: Claude Opus 5.5 * test(provider): a pair's batch replan that cannot be swapped in is proposed again and again (red) Pair-2 (M3 Ultra + M5 Max, Gemma 4 26B tensor parallel served locally) logged proposal lanes=8 -> prepared -> rollback_prepared every ~35 s, each cycle draining the lane and reloading the old setup (~15 s). Gemma has no tensor-parallel batch quote, so queued demand priced an 8-lane pipeline. The local server swaps in only a session with the same endpoint contract, and Gemma captures committed-token logprobs in tensor parallel only, so the swap fails after the drain, and nothing remembers the failure. Four checks, red against stubs that keep today's behaviour: - the planner's endpoint predicate allows a tensor-parallel Gemma generation to be replaced by a pipeline; - it disagrees with the session profiles the server compares; - a replacement that failed after release is allowed again at once; - the factory proposes a width that just failed. Co-Authored-By: Claude Opus 5.5 * fix(provider): a pair's batch replan keeps the API's features and remembers a failed width Pair-2 (M3 Ultra + M5 Max, Gemma 4 26B tensor parallel served locally) repeated proposal lanes=8 -> prepared -> rollback_prepared every ~35 s. Each cycle drained the lane, adopted a setup on both Macs, failed, and reloaded the old setup (load_ns ~15 s), so queued requests waited minutes (4 at once: 118 s; a health request: 412 s). - Gemma has no tensor-parallel batch quote, so its batch scope prices only the pipeline, and the planner proposed an 8-lane pipeline. The local server swaps in only a session with the same profile, and Gemma captures committed-token logprobs in tensor parallel only, so `prepareGeneration` refused it (`replacementIdentityChanged`) after the drain. The planner now refuses a width whose mode changes the endpoint contract before anything drains (`keepsEndpointFeatures`; `cluster.batch_replan refused`, `reason=endpoint_features`). - Nothing remembered a replacement that failed after release. The factory now records it when the host asks for the restore (`cluster.batch_replan failed`), and proposes that setup and width again only after 2 minutes, doubling per repeat, at most 30; a changed setup is tried at once (`DistributedAutomaticBatchFailures`). The memory-based width choice is unchanged: only widths both Macs admit now are proposed. The logprobs rule, the factory's Gemma eligibility and the binding check date from 8197ff922e (v0.10.6), not 0.10.9. Co-Authored-By: Claude Opus 5.5 * docs(cluster): a Gemma TP pair serves one request at a time, and a cancel in its prompt keeps that lane Option (a), pricing a Gemma tensor-parallel batch width, is not safely possible in this window. Gemma's TP runtime does run batched lanes (`Gemma4TensorParallelLaneReservation`, `pagedHost(lanes:)`, the lane contract), but nothing prices them: there is no Gemma tensor batch quote (`ClusterPlacementTensorBatchQuote.runtimeModelIDs` is Qwen only), no saved `batchLanes` for Gemma TP (`ClusterConfiguration`), and the TP-to-TP replacement path (incumbent shares) is Qwen only. The wording was already truthful: the mode question and the setup's lanes come from `DistributedInstalledPlan.batchLanes`, which gives Gemma TP its default of one. Two guard checks pin it (green on this base; no source changes here), and the docs now state the known limitation: at one lane a cancel during the prompt is a clean stop at the first token, so the lane is held until the prompt is read (~68 s for 15.8K tokens on pair-2), as on a GLM pipeline. Co-Authored-By: Claude Opus 5.5 * Provider toolchain: build and release with Xcode 27.2 (SDK 27.2, Swift 6.4.2) The Darkbloom Sandbox macOS CI base moved to Xcode 27.2 (27B52), which has no SDK 27.0. prepare-provider-release-toolchain.sh accepted only SDK 27.0, so every provider CI job failed in its first step. - DARKBLOOM_PROVIDER_TOOLCHAIN=release (release-provider.yml, provider-signing-validation.yml, master and dispatched release preparation) accepts SDK 27.2 and Apple Swift 6.4.2 only. - The default, qualification (ci.yml, pull-request release preparation, the sandbox base check), accepts SDK 27.2 or 27.0 and Swift 6.4.x. SDK 27.0 stays while production runs the Xcode 27.1 base (issue 1790). - The step tries the image's Xcode, then each installed Xcode, newest first, and takes the first with SDK 27.2. It exports DEVELOPER_DIR when it selects another Xcode, so Metal, xcodebuild and signing match. - PROVIDER_SDK_VERSION is the selected SDK. The older-macOS smoke and the release resume expect 27.2. - The signing validation workflow uses the same step and wrapper. - mise pins Swift 6.4.2. Docs and a changelog fragment follow. Co-Authored-By: Claude Opus 5.5 * Provider toolchain: refactor pass on Xcode selection Behavior-preserving cleanup of the 27.2 toolchain step: - One path for an explicit toolchain root and an image CLT; the Xcode candidate search is the select_xcode function. - The Applications folder is read once. - No ticket number in the script, build docs or changelog fragment; the removal condition for SDK 27.0 stays stated. - The toolchain tests share one GITHUB_ENV reader. Accepted SDK and Swift versions, modes, outputs and messages are unchanged. Co-Authored-By: Claude Opus 5.5 * CI: route the macOS jobs through Darkbloom again (Blacksmith fallback); reverses #1733 part 1 (#1771) * ci: route the macOS CI jobs through Darkbloom again (Blacksmith fallback) Reverses only part 1 of #1733, which pinned the macOS jobs of ci.yml to blacksmith-12vcpu-macos-27. The route job again requests a Darkbloom lane for each macOS job that will run, and each job runs on its lane's decision: - test-provider-1..3 (one per shard), test-provider-summary - test-provider-sdk - test-cluster-checks, test-cluster-1..3, test-cluster-gpu-1..2, test-cluster-focused This is dev's wiring from just before #1733 (per-shard lanes from #1691, cluster lanes from #1737) with today's matrices and conditions: 3 provider shards (#1749) and the cluster component gate. The fallback label, the shard matrices, SAVE_CACHES and #1752's .git and SwiftPM caches are unchanged. A lane that the plane does not grant, including one missing from its approval, keeps Blacksmith. shards that never got a runner. #1752's lighter checkouts and master/dev-only cache saves, the images' zstd and CONNECT retry, and the add-on's local cache address them. The route, provider CI, cluster plan and component-path tests pin the lane lines to each job's matrix and condition again; build.md and test.md describe the routed macOS jobs. * ci: refactor pass: call the shard lane test-provider-; reflow two wraps Comment and Markdown wrapping only; no workflow behaviour changes. The test-provider comment called its lane test-provider-K, while scripts/test-darkbloom-route.py and build.md write -; the test.md paragraph kept a one-phrase line from the routing-link edit. * Provider toolchain: build with Xcode 27.1 / SDK 27.0 again (revert #1801) SDK 27.2 declares Foundation's `Date.>=` and `Date.<=` as `@backDeployed(before: macOS 27.2)`. Swift 6.4.2 therefore compiles every `date >= date` and `date <= date` in our code as an availability check: on macOS 27.2 or later it calls Foundation's symbol through a weak import, and on older systems it runs an inline fallback. macOS 27.2 seeds that predate the SDK (26B5091g) pass the check, but their Foundation does not export these two symbols. The weak import binds to NULL and the call jumps to address 0. DevNet branch.87, the first build with #1801, crashed 11 times in 20 minutes on a Mac Studio running 26B5091g: - the cluster service, in `ClusterService.syncMembers` called from `checkForUpdate`; - the CLI, in `ClusterProductModelStore.updateClusterStore`. The same build runs on macOS 27.0 and 27.0.1 without crashing, because the fallback runs there. The guarded calls are in at least 21 functions, including app attest, shadow keys, schedules and the cluster code. A single Mac on such a seed crashes too. About 11 connected production providers run pre-release 27.2 builds, and 8 more report 27.2 without a build number. 0.10.8 and DevNet branch.81 through .85, built with SDK 27.0, do not import these symbols, and they run on the same seeds. Nothing in our code needs SDK 27.2. Before SDK 27.2 lands again: - rewrite the `Date` comparisons, or add a release check that fails on these weak imports; - run a build on a released 27.2 Mac (26B123). This reverts merge 219523dfd2 (#1801). The workflow, script, test and mise.toml files match dev before #1801 byte for byte. #1803's doc changes stay. Co-Authored-By: Claude Opus 5.5 * ci: drop the KEPT_APART shard pin KEPT_APART kept NemotronSuperManagedSlotTests and Qwen4PagingPrefixIntegrationTests on different shards after a process that ran both crashed with SIGBUS. PR #1753 fixed the root cause (the Qwen4 paging fixture now evaluates its weights). No other pair used the mechanism, so this removes the pair, the mechanism, its test and the note in docs/developer/test.md (an exact revert of a7ccf0afa). Co-Authored-By: Claude Opus 5.5 * ci: refresh EnrollmentRecoveryTests' shard weight The weights file listed ProviderAppAttestTests.EnrollmentRecoveryTests at 22.2 s. Green dev CI run 41951852307 (c85e01133), shard 1: 22 cases, 0.017 s summed. The provider-test-shard-weights artifact cannot refresh it: the suite is XCTest in the parallel process, no xUnit report covers it, so the artifact carries the checked-in value forward. The value comes from that job's log, summed per case as `weights` sums xUnit cases. No other entry changes. Co-Authored-By: Claude Opus 5.5 * test(cluster): MiMo tensor-parallel plans prefill serially MiMoTensorParallelChecks now asserts, with the real planner on the registered layout, what GemmaTensorParallelChecks asserts for Gemma: the layout lists serial and one-chunk lookahead; the forced tensor parallel, tensor parallel placed first without the choice, tensor parallel chosen on served requests and the assessment's best tensor-parallel candidate are planned serial; the speculative pipeline chosen on the slower served split keeps the lookahead. From closed PR #1746's MiMo checks. Co-Authored-By: Claude Opus 5.5 * cluster tp-check: refuse mimo run --mode full with --mtp-depth up front Since SDK #381, MiMoV26TextModel.forwardVerifyWindow throws on a whole model ("a verify window runs only on a tensor-parallel rank"), so `mimo run --mode full --mtp-depth D` loaded the model and then failed in the first round. The tool now refuses that pair with the other argument checks, before the deadline, the request and the load. The MiMo oracle runner's mtp matrix requires the refusal (the message, no report, no load line). Co-Authored-By: Claude Opus 5.5 * ci: the Release Integrity pin allows its one condition, !cancelled() Co-Authored-By: Claude Opus 5.5 * cluster tp-check: run the full + --mtp-depth refusal check once The refusal needs no model, so the oracle runner checks it once on the kernel-mtp checkpoint instead of per variant. Clearer usage wording. Co-Authored-By: Claude Opus 5.5 * ci: the entry-point test sets the per-shard audit and coverage steps aside Co-Authored-By: Claude Opus 5.5 * ci: the per-job audit test gives each of its 4 selections a suite Co-Authored-By: Claude Opus 5.5 * fix(cluster): read MiMo tensor-parallel shard runs that share pages together MiMo-V2.6-Flash tensor parallel never became ready on two M5 Ultra 256 GB Macs (DevNet branch.87): each rank's part ended "exit 1: deadline" at the pair's startup deadline (about 634 s for the 172.9 GB artifact). Its verified shard load reads only the rank's byte runs, one uncached aligned read per run. The expert down_proj is divided on its inner axis, so each of its 94 tensors is 1,048,576 runs of 512 or 32 bytes, each a whole 16 KiB uncached read: measured 43.7 us per run on the M5 Ultra, about 46 s per tensor and over an hour per rank. A selection of one range on a divided axis is now read as strided runs: runs less than an alignment page apart are read together, as many as one 8 MiB scratch request holds, and copied out exactly; runs farther apart are read one at a time as before. Same bytes, same selected-byte accounting, same scratch allowance. Measured on the real down_proj tensor: 129 reads, 0.21 s instead of about 46 s. Test: CheckpointStridedReadCheck (CheckpointChecks/run.sh and the swift-testing suite): bytes equal the per-row slices for both ranks, at most 4 reads for 20,001 runs that share pages, one read per run a page apart, EINTR retry, short-read and out-of-range refusal. It does not compile before this change (no strided read existed). Co-Authored-By: Claude Opus 5.5 * cluster: the joining Mac follows the registration's hand-off, never a false ✗ (R7-1) DevNet branch.87, M5 Ultra pair (GLM tensor parallel 03:19:56Z, Gemma tensor parallel ~03:40Z): right after "✓ Load (58 s)" the joining Mac's window ended with "✗ Not serving: not offered to Darkbloom (no cluster approval is attached to its setup)" and "Choose Retry on the other Mac". The leading Mac went on to its test, registered the pair (03:20:22Z), started both parts again as cluster members and showed ✓ through Darkbloom (committed 03:20:52Z). Cause: between its local test and the registration's restart the leading Mac's status reads " is not serving yet: not offered to Darkbloom …" (the pair serves on its local API, no approval attached yet). The follow window took that status (FollowedStart.notOffered) as the start's final outcome and ended at once. - A not-offered status is the outcome only when the leading Mac's start is over: while it still publishes its start's step (ClusterControlReply.start), the joining Mac keeps following it. The leading Mac's own ✗, published as `failed` when its screen shows it, ends the window with the same ✗ and Retry. With no start running, the status stays the outcome, as before. - A published ✗'s words keep a parenthesis that isn't a Mac's name ("on this Mac (no Darkbloom traffic)" lost it when named from the joining Mac's side). NoFalseCrossChecks (the branch.87 hand-off at 80 columns and plain, the leader's ✗ after "not offered", a not-offered pair with no start running): 7 failed / 8 passed before the fix, 15 passed / 0 failed after. Onboarding checks 1793 passed, 0 failed; control checks 682 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 * ci: component-path tests follow the per-push concurrency and read jobs only Co-Authored-By: Claude Opus 5.5 * fix(cluster): a pipeline is never predicted faster than a share its Mac measured R7-2 (two M5 Ultras 256 GB, DevNet branch.87): the mode question recommended Gemma 4 26B's pipeline, "about 183 against 107 tokens/s, predicted"; through DevNet the pipeline served 59.9 tok/s and tensor parallel 105.1. Why: a single pipeline stream decodes one whole step across both Macs, each its layers at its whole-model rate, plus the hop. Gemma was never measured whole on these Macs, so that rate was the device index's estimate (ClusterHardwarePrior.absolute): the bytes a step reads over the bytes a second the index moved, the weights' read time alone with no per-token floor. On an M5 Ultra that is 5.5 ms a Gemma step (181 tok/s), while the same Mac's tensor-parallel half step was measured at about 7 ms (share probe, served requests): tensor parallel was priced on measurements, the pipeline on a floorless estimate. After a TP load the estimate even reads as `.measured` (the served record carries it beside its measured shard rates). Fix: ClusterDeviceSpeed.wholeModelEstimated marks whole-model rates that are not a measurement of this model on this Mac (the index's, and those a tensor-parallel served record carries). For such a Mac the planner's pipeline step (wholeStepSeconds) is at least the largest measured share step plus the rest of the divided weights at the index's rate: a larger share never steps faster. A whole-model measurement is used as it is; nothing depends on a chip or a model. Check (PlacementChecks, Gemma QAT 4-bit, the M5 Ultra's index, the pair's 29 us keyed link): with a 7 ms half step, and after tensor parallel served at 105 tok/s, tensor parallel is predicted faster (pipeline 100 / 95, tensor parallel 111 / 105); index only, unchanged (170); a measured whole model (90 tok/s) is kept. Red without the planner change: 2 of 1631 failed (pipeline 170). The served-record helper keeps a constructed whole-model measurement one, as the flow merges it. Left: the pipeline's per-step cost between the Macs is still two small link records (about 0.36 ms), so it predicts ~95-100 tok/s where 60 was served. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): name the measured share steps in wholeStepSeconds The pipeline step bound's share points use ClusterMeasuredStep (fraction, seconds) as ClusterDecodeSplit does, in place of an unnamed tuple; the plain whole step is `whole` (it is an estimate only past the guard) and the share-divided weight time `divided`. No behaviour change. Co-Authored-By: Claude Opus 5.5 * ci: CI (dev) has the plan and the tests jobs Co-Authored-By: Claude Opus 5.5 * fix(cluster): read runs together only for a rank's part of a divided axis The strided read now serves only a selection of one range that is less than the whole axis: a tensor-parallel rank's part, which today only MiMo's tensor-parallel verified load asks for. A whole-axis selection (Qwen's fused gate/up expert rows, read part by part) keeps one read per run, so every other model's load reads exactly as before. The changelog fragment says plainly that MiMo tensor parallel now loads in time, and why. Validated: the package's DarkbloomClusterRuntimeTests build (swift build, MLX), and CheckpointStridedReadTests, TensorVerificationTests, TensorDescriptorScopeTests, CheckpointPayloadCacheTests, MiMoTensorParallelTests and the two MiMo verified-load tests pass. Co-Authored-By: Claude Opus 5.5 * docs(inference): MiMo tensor parallel reads its shard's runs together Co-Authored-By: Claude Opus 5.5 * cluster: an earlier start's published ✗ never hides a not-offered outcome (R7-1 review) The review of aaaf49e275 (B1): the hand-off guard read the raw published start, so the leading Mac's ✗ from an earlier start, published for 30 minutes, kept the joining Mac following a start that wasn't running until the 15-minute bound, instead of the true "not offered" ✗ at once. The guard now reads the filtered start (`current`: an earlier screen's ✗ counts only once a leader screen is seen). - New check: an earlier ✗ published, no step from the leader, status "not offered": the true ✗ at once. On aaaf49e275: 3 failed; after: passes. - Nit 4: the no-start check asserts the ✗ comes at once (under 10 s). - Nit 2: a start that ends not serving no longer publishes nil before its ✗, so the joining Mac never reads the status' ✗ without its next step in between. - Nit 5: the doc says the joining Mac keeps following until the leading Mac shows ✓ or ✗, and that the 15-minute bound still applies. - Left: nit 1 (a Retry doesn't set the pending mark again; follow-up) and nit 3 (the capital-letter name heuristic). NoFalseCrossChecks 20 passed. Onboarding checks 1798 passed, 0 failed (one earlier full run had 3 timing failures in WaitHonestChecks' q check under load average 15-21; that check passes alone 3 of 3 and in the rerun). Control checks 682 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 * fix(cluster): cluster status gives a retrying load's part end as its reason R7-4 (0.10.9 DevNet, MiMo tensor parallel): for 12 minutes the leading Mac's part ended "exit 1: deadline" and started again while `cluster status` and `cluster status --json` said `loading` with `reason: null` on both Macs. The leading Mac's status lines ("Starting ." and "Loading : N of 2 parts ready.") now carry each part that keeps ending, in the start screen's words (OnboardingLive.endedClause, which readinessOnce now uses too): "; this Mac's part ended (exit 1: deadline) and starts again by itself". ClusterPairSummary.state(ofStatus:) gives that clause as the loading state's reason; the plain status line says "loading: " and `next` says both Macs keep trying by themselves. The member asks the leader for the same lines, so both Macs say it. Test: ClusterStatusPlainTests "a load whose part keeps ending gives that end as the reason" passes (swift test, DarkbloomCLITests). Before this change it does not compile (no endedClause) and state(ofStatus:) returns no reason for a loading line. Two existing tests in the suite fail on this debug build because they expect the production CLI name `darkbloom` where the build says `darkbloom-dev`; unrelated to this change. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): give endedClause and endShown their own doc comments b2cad18e95 put endedClause between endShown and its doc comment, so endShown's comment documented endedClause. Comments only; names localStatus, where cluster status reads it. Co-Authored-By: Claude Opus 5.5 * test(cluster): a divided-axis tensor read matches one read per run Through TensorDescriptor.read, uncached: each rank's half of a U32 [2, 4096, 256] tensor (MiMo's expert down_proj shape, ending the file off a page) and of an odd-sized BF16 tensor at an offset off a page are byte-identical to one aligned read per run, in fewer reads. Whole-axis and several-range selections still take one read per run. Test only. Co-Authored-By: Claude Opus 5.5 * ci: darkbloom-watchdog.yml, darkbloom-sandbox's GitHub-side watchdog, copied unchanged From darkbloom-sandbox public/darkbloom-actions/.github/workflows/watchdog.yml at 31236c54. Every 10 minutes it cancels a run of this repository whose Darkbloom-labelled job waited DARKBLOOM_WATCHDOG_MINUTES with no runner, then re-runs its route job and dependents on the fallback, once per run. Token: actions: write and checks: write, this repository only; no secrets, no actions, no checkout. Release and signing workflows carry no Darkbloom label, so it never touches them (pinned by test-darkbloom-route.py). Co-Authored-By: Claude Opus 5.5 * fix(cluster): the single-Mac block on a stopped pair is said on the joining Mac and in both statuses 0.10.9 DevNet build C (R8-1, pair-2, 04:17Z): the leader's start of a stopped pair hit the single-Mac block (✗ and offer on its screen), but the pair was never started, so `localStatus` said "Stopped" on both Macs (state `stopped`, no reason) and the joining Mac's resume screen said "Stopped … Close". Round 2's fix covered only a started pair. - The leader records the block (`ClusterSetupRecord.soloBlockedAt`, set when the ✗ is shown, cleared by a serve or stop); while it stands and single-Mac serving still runs, `localStatus` gives the block's not-serving line and remedies, so both Macs' `cluster status` say `not_serving` with the reason and `next`. - The joining Mac's resume screen reads single-Mac serving on both Macs first and shows the same ✗, naming its own provider, with the leader's offer. - Onboarding check pins the stopped switch to Darkbloom keeping its saved mode. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): markSoloBlocked's doc no longer takes stopSoloServing's The new operation was inserted between stopSoloServing's doc comment and its declaration, so the doc attached to markSoloBlocked. Comment order only; no behaviour change. Co-Authored-By: Claude Opus 5.5 * ci: bind tested-change records, full master selection, plan checks on dev - A tested-change record names its tree, the event's base and head and the components that ran. A run skips only on a record of its own change that covers every component it selects, from a successful run of that head; a merge push finds the pull request's record through its two parents. - Pushes to master and pull requests into master select every component. - CI (dev) runs for pull requests into any branch but master. - The Provider Tests gate audits the cluster plan and runs the CI plan self-tests on every run. - CI (master) restores only the strict build-cache tier. - Docs and changelog fragments match. Co-Authored-By: Claude Opus 5.5 * ci: run a selection once more when SwiftPM finds build.db locked Run 41970825476: provider selections 1 and 5 passed every test but exited 1 with "unable to attach DB: ... database is locked": SwiftPM's startup in one process met another's on the build database. The provider processes now start PROVIDER_TEST_START_GAP (15) seconds apart, and a provider or grouped cluster selection that reports the locked database runs once more. Co-Authored-By: Claude Opus 5.5 * ci: retry a locked-build.db selection only when every test passed A test that fails only under contention fails in the attempt that also printed SwiftPM's lock message; a second attempt could pass and overwrite the evidence. A provider selection or grouped cluster selection now runs again only when its first log shows the lock and proves every test passed (scripts/swift_test_lock_retry.py: a passing Swift Testing summary, XCTest summaries with 0 failures, no failed test, issue or tripwire). The first attempt's log and xUnit report stay beside the second's (attempt-1-shard-.*, uploaded); the cluster job log prints both. Co-Authored-By: Claude Opus 5.5 * ci: the gate checks the CI plans even after a failed test job Run 41973436945's gate stopped at its requirement step, so the plan checks never ran. They now run unless the run was cancelled; the record steps keep their implicit success(). Co-Authored-By: Claude Opus 5.5 * fix(cluster): share probe budget bounds the timed rounds, not setup The share probe measured its 1.5 s budget from before admission, so the prefill, the warm-up rounds and first-use kernel compile in the worker process counted against the timed rounds. A cold first probe then gave fewer than three timed rounds and skipped=budget, in CI and on a real load alike, and a skipped probe leaves no share evidence for the fastest-only tensor-parallel families. Each phase's timed rounds now run for the budget from their first timed round. A separate 8 s limit, inside the 10 s deadline margin, bounds the whole probe including prefill and warm-up (skipped=limit). The Qwen and Gemma 4 probes share the round loop (QwenTensorParallelShareProbe.rounds), tested on the CPU with a constructed clock. Co-Authored-By: Claude Opus 5.5 * ci: run the share probe in cluster shard 1 after base; weights skip attempt-1 reports The share probe times each rank's share against a 1.5 s budget. Right after the concurrent GPU groups of shard 2 it failed (run 41973436945); on dev's layout it passed in each of the last 6 dev runs. It now runs in shard 1, after base, alone, and a plan test keeps it out of any shard with groups. measured_weights ignores attempt-1-shard-*.xml, the kept first attempt of a retried selection, so a retried selection never counts twice. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): share probe rounds report what stopped them Review pass on the share probe budget fix. The round loop returns its timed rounds and whether the limit stopped them, so the skip reason (budget or limit) is the loop's own and not a clock read afterwards. The check before the one-chunk prefill could not fire in production and is removed with LimitReached. The GPU budget case steps the clock by just over half the budget, so it stops on the budget again and not on the limit. The docs say what the limit does: no round starts after it. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the mode question recommends without quoting tok/s The owner (2026-11-05): "it should not show tok/s". Pair-2's Gemma question read "Pipeline, faster here (about 56 against 52 tokens/s, predicted)". - ClusterOnboardingModeAdvice.advise: the speeds (measured, else predicted) still rank the modes, but the reason is words only: "faster here", "serves up to 8 requests at once and is faster here" / "... and is as fast here" (that last case used to call an equal-speed mode faster). - modeLine: a mode's row drops "N tok/s measured" / "not measured on these Macs yet"; it keeps the split, requests at once and the marker. - OnboardingLive: the choice line a re-plan quotes ("Planned in the mode chosen: ...") no longer carries the planner's predicted speed. - The model list keeps its measured served speeds (unchanged). Checks: provider-swift/Tests/ClusterOnboardingChecks red 23 on the base (1795 pass) -> 1818 pass, 0 fail. Co-Authored-By: Claude Opus 5.5 * ci: test the CI workflows' pull_request filters from their on: blocks The text match in test_every_pull_request_runs_exactly_one_ci_workflow took ci-dev.yml's push filter (branches: [dev]) for a pull_request filter and failed run 41977316006's plan checks. The test now reads each on: block event by event: CI (dev)'s pull_request has only branches-ignore [master, main], CI (master)'s only branches [master, main]. Co-Authored-By: Claude Opus 5.5 * ci: fix two plan self-test pins found on a Linux run of the gate's checks - test-ci-component-paths: only the plan and tests jobs must not read github.base_ref; Release Integrity reads it for the build default. - test-provider-ci-workflow: provider-tests.yml has 7 CHECKOUT_SPARSE checkouts now, the gate's among them. All 7 plan-check commands pass on refactor-gobox (Python 3.12, Linux). Co-Authored-By: Claude Opus 5.5 * fix(cluster): the mode question trusts a measured mode over a predicted one Two M5 Ultras on DevNet build D (2026-11-05 07:24Z): Gemma tensor parallel had served at 111 tok/s, the pipeline not yet. The advice compared the planner's predictions (pipeline 152, tensor parallel 133) and recommended the pipeline, which then served at 64. MiMo likewise: "Speculative pipeline" over tensor parallel measured at 55. ClusterOnboardingModeAdvice.advise: when some open modes are measured and some are not, the fastest measured mode is recommended ("the only one measured on these Macs so far" / "the fastest measured ..."; brief "measured here"). Through Darkbloom a mode that serves more at once still wins first (no speed needed). All-measured and all-predicted cases are unchanged. No hardware or model rule. Checks: ClusterOnboardingChecks red 6 on the base -> 1823 pass, 0 fail. Stacked on #1811 (same function). Co-Authored-By: Claude Opus 5.5 * Provider toolchain on dev: build and release with Xcode 27.2 again (re-apply #1801, port of #1791) Reverts #1804 (73ecb2bc7), which reverted #1801. The SDK 27.2 crash that #1804 found (back-deployed Date >= / <= on macOS 27.2 seeds) is fixed by the port of #1807 in the next commits. Co-Authored-By: Claude Opus 5.5 * fetch-metallib: use the metal-cpp archive the Darkbloom sandbox image carries MLX's configure downloads metal-cpp_26.zip from developer.apple.com with FetchContent, which does not try again; through Darkbloom's sandbox egress the download ended early in macOS jobs (Layr-Labs/darkbloom-sandbox#299). The macOS sandbox payload disk now carries the archive, pinned by SHA-256 (Layr-Labs/darkbloom-sandbox#301). When it is the archive the nested MLX core names and its digest matches, the script unzips it into the build directory and passes -DFETCHCONTENT_SOURCE_DIR_METAL_CPP; anywhere else, FetchContent downloads it as before. Co-Authored-By: Claude Opus 5.5 * Provider on dev: no back-deployed Date >= / <=; refuse them in source and release binaries (port of #1807) Ports #1807 (head 8c6b57b9d) to dev: - The 26 Date >= / <= comparisons in 10 provider files become a.timeIntervalSince(b) >= 0 / <= 0, as on master. The hunks apply to dev unchanged. Dev adds no other Date >= / <= since DevNet build 0.10.6-dev.branch.87 (814268cfd), whose binaries #1807 read. - scripts/check-date-comparisons.py and scripts/check-provider-weak-imports.py with their tests, unchanged. - Dev has no ci.yml. The source check runs in the Provider Tests gate of provider-tests.yml (every CI (dev) and CI (master) run) and in ci-master.yml Release Integrity, where master's ci.yml runs it. test-provider-ci-workflow.py pins the gate step. - The binary check runs in the release lane of provider-release-build, as on master: release-provider.yml (release-dev-branch.yml, release-swift.yml) and SDK 27 release preparation. - Docs and the changelog fragment as in #1807, with dev's CI file names. Co-Authored-By: Claude Opus 5.5 * fetch-metallib: match MLX's metal-cpp archive by its fixed name; the build still fetches MLX's GitHub dependencies Review: a local copy named by MLX_METAL_CPP_ARCHIVE was used only when its file name was metal-cpp_26.zip, because the check grepped MLX's CMakeLists for the copy's basename. It now looks for the fixed name, so any copy with the pinned digest works. build.md said the build makes no download; MLX's configure still fetches json, fmt and gguflib from GitHub: it makes no download from developer.apple.com. Co-Authored-By: Claude Opus 5.5 * Date comparison check: a Date followed by a member is not a Date CI (dev) run 42025284502 failed the source check on dev's ClusterOnboardingFlow.swift:1973 and 1979: `let waited = Date().timeIntervalSince(started)` binds a TimeInterval, but the file-wide evidence (_DATE_VALUE) took every value that starts with `Date(` as a Date. A Date initializer or Date.now/distantPast/ distantFuture now counts only when no member follows it. `Date().addingTimeInterval(...)` still counts, by its own pattern. Shipped source has 29 such `timeIntervalSince` bindings and 26 `addingTimeInterval` ones; only the first kind changes, and each is a TimeInterval. Master's source has no comparison that this changes. The test adds both forms to the allowed source. Co-Authored-By: Claude Opus 5.5 * CI (dev): build each lane once on a large Mac, test on small ones - Build cluster test products and Build provider test products build each lane once on blacksmith-12vcpu-macos-27 and upload the debug products (scripts/ci-test-products.py, .github/actions/provider-ci-products). The test jobs need their lane's build job, download its products and run them with swift test --skip-build; they compile no package and refuse products of another commit or toolchain. - The jobs of the products work at one fixed path, /private/tmp/dinf: their first step links the workspace to it, because SwiftPM's products hold absolute paths and Blacksmith and Darkbloom check out to different paths. - Cluster Release Build Checks runs the capability and prefill release compiles on a large Mac, in a job no test job waits for; the gate requires it. Refresh build caches is gone: the build jobs refresh the caches of a tested push. - Cluster Runtime Tests: 3 shards; the Gemma 4 base suites run alone on shard 3. Cluster Focused Checks: 2 shards. Provider shard weights measured again from run 42029278469; the last shard's audit warns about unweighted suites. - Only the 7 blocking test lanes ask Darkbloom; the build jobs, the release build checks and Cluster GPU Tests stay on Blacksmith. - Every macOS job samples memory and CPU (scripts/ci-resource-sampler.py, report-only) and prints the peaks; the hand-off prints archive sizes and transfer times. Co-Authored-By: Claude Opus 5.5 * CI products: compare only the compiler line of swift --version The Target line names the host's macOS version, which differs between runner images without changing the products. Co-Authored-By: Claude Opus 5.5 * CI products: refuse another toolchain version, warn on another build Run 42037827790: the Blacksmith image builds with Xcode 27.2 build 27B5038j (Swift 6.4.2.1.4, SDK 26B5110a); the Darkbloom image has the release build 27B52 (Swift 6.4.2.1.9, SDK 26B118). The versions are equal, so the test job runs the products and warns; another Swift, Xcode or SDK version or another commit still fails the job. Co-Authored-By: Claude Opus 5.5 * CI: both focused shards route through the approved lane test-cluster-focused The approval lists the lane names of the earlier layout (test-cluster-1 to -3, test-cluster-focused), so test-cluster-3 routed and test-cluster-focused-1 and -2 fell back as lane_not_enabled. A route request may ask for several jobs on one lane (count, granted whole), so both shards now read test-cluster-focused, requested for 2 jobs. No approval change. Co-Authored-By: Claude Opus 5.5 * SSHChecks: bound a renewal's lateness by this host's wake latency Run 42046597342 ran Cluster Focused Checks on a Darkbloom VM for the first time; OwnerWriterWakeTests failed with "Renewal interval drifted: 5016.940 ms". The writer waits on a semaphore until the renewal is due and schedules the next one from its send time, so each interval is 5 s plus one timer wake latency; the test allowed a fixed 15 ms, which is Blacksmith's latency, not the writer's. A probe now measures, during the same window, how late this host wakes a thread waiting on a semaphore at the writer's priority; a renewal may be late by that worst wake plus 5 ms, at least 15 ms, and the allowance must stay below the 50 ms idle bound, so a writer that rested a whole idle wait is still told apart. Co-Authored-By: Claude Opus 5.5 * Refactor pass: tidy the test products hand-off - ci-test-products.py: one helper each for the commit lookup, the MiB size text and the upload or download clock; `uploaded` gets its own function like the other subcommands; `stream` precedes its callers. Output text, manifest and checks are unchanged. - provider-tests.yml: keep the fixed-path explanation once, in build-cluster, and point to it from the other four jobs; Prompt Parity now runs against the downloaded provider products, not the shard's own build, so its comment says so. - ci-resource-sampler.py: list the internal `run` subcommand in the docstring. Co-Authored-By: Claude Opus 5.5 * Speed records name how a request was served and whether Qwen's tensor assistant decoded it A served speed record now carries the way the request reached the pair (through Darkbloom or the leader's local API) and whether the setup decoded with Qwen's resident tensor assistant. Planning, the setup screen's served figures and the router take only the records served the way they will serve, and served calibration never credits the assistant's rounds to a Mac as its one-token rate. Pair-2's Qwen served tensor parallel at 34-36 tok/s locally with the assistant and 14-20 through Darkbloom without it; under one key, the served race (read at the fast end) gave the Darkbloom plan the local assistant's figure. Co-Authored-By: Claude Opus 5.5 * A public tensor assistant may verify admitted cohorts, and its evidence is the tensor-parallel qualification A declared assistant names when it was qualified, may declare either verification (the local automatic policy verifies admitted cohorts), and a release's facts give the model's tensor-parallel parity qualifications the assistant's evidence digest and instant, so the qualification a coordinator derives names the speculative decoding it covers. The refusal beside an approval is shortened to fit the other Mac's 240-character relay. Co-Authored-By: Claude Opus 5.5 * Lock-retry guard: match both wordings of SwiftPM's locked build database Run 42057277814: Cluster Runtime Tests shard 2 failed on both attempts with every test passed; SwiftPM printed `error: error: accessing build database "...build.db": database is locked`, without the `unable to attach DB:` prefix the guard matched, so it did not run the selection again. LOCKED now matches either wording. The rule is unchanged: run once more only when attempt 1 shows the lock and every test passed. Co-Authored-By: Claude Opus 5.5 * Declare Qwen3.8-27B's tensor assistant public, with its parity evidence Pairs that serve Qwen3.8-27B in tensor parallel through Darkbloom now plan and keep the model's resident assistant (depth 3, admitted cohorts, the registered artifact's head inventory 6bf428ca...), the policy local clusters plan by themselves. The evidence report records same-request speculative and plain decodes on one pair (build 0.10.7-dev.branch.95): 12 of 12 greedy prompts identical at 200 and 1,024 tokens, 4 of 4 seeded sampled rows, the tool call and the image row identical; logprobs rows run the plain path. The model's tensor-parallel parity qualifications in a release's facts rest on that report. Co-Authored-By: Claude Opus 5.5 * CI: caches of the fixed-path jobs in /private/tmp/dinf-ci; stagger shard 2's groups - actions/cache stores each path relative to the workspace and unpacks it with `tar -C `. In the jobs whose workspace links to /private/tmp/dinf, the metallib cache (runner.temp) unpacked to /private/_temp and failed ("Cannot mkdir"), and SwiftPM's repositories (home) unpacked under /Library, where SwiftPM never reads. The metallib, MiMo metadata and codec caches and SwiftPM's repositories now live in /private/tmp/dinf-ci, whose only common ancestor with a workspace is `/`; ~/Library/Caches/org.swift.swiftpm/repositories links there. Restores and push saves use the same paths. A self-test refuses a runner.temp, home or expression cache path in those jobs. - Cluster runtime shard 2 found SwiftPM's build database locked at its two groups' startup in every run (runs 42041608780 to 42065297991). Each later group now starts CLUSTER_TEST_START_GAP seconds (default 15) after the one before, as the provider shards' processes do; the lock-retry guard stays the backstop. Co-Authored-By: Claude Opus 5.5 * Qwen TP decode: submit every 8 layers, not every layer A tensor-parallel decode step was submitted to the GPU after every decoder layer (decodeLayerStride = 1): 64 commits and GPU wake-ups a 27B token. On two M5 Ultra 256 GB over JACCL (sealed sums, synthetic 64-token prompt) a width-one step took 21.4 ms at stride 1 and 20.2-20.3 ms at 8-16 (25.1 vs 19.9-20.4 ms with the host loaded), width four 35.4 vs 29.5-29.9 ms; 32 is slower again (21.2 ms). Every stride retired the same tokens on both ranks. The stride moves to QwenTensorParallelLaunch.decodeLayerStride (8, inside the measured flat band, divides 32 and 64 layers) with decodeSubmissions, checked by the model-free TensorParallelPlanChecks. qwen-decode takes --backend jaccl and --layer-strides (default: the product's stride). Co-Authored-By: Claude Opus 5.5 * Check a discovered assistant against the declared or automatic policy in two flat guards `requireDiscoveredQuote` nested the declared and automatic checks in an if/else of guards. The same two conditions now throw the same errors from two flat checks; behavior is unchanged. Its two doc comments say "verification" instead of "singleton verification": a declaration may name either policy, and this build declares admitted cohorts. Co-Authored-By: Claude Opus 5.5 * Correct comments that predate the Qwen3.8-27B public assistant declaration - `ClusterPairRequestTelemetry.serving`: a record without it is read as served either way (`Setup.servedAs`), and `servedBy` already leaves it out; it said "neither way". - `ClusterPlacementFlow.decide`: an assisted setup is offered to the coordinator where the build declares the assistant, not "never". - `ClusterPublicTensorAssistantTests`: this build declares Qwen3.8-27B's assistant. - configuration reference: the declared assistant's depth and verification (it is admitted cohorts). Comments and docs only. Co-Authored-By: Claude Opus 5.5 * ci: per-job macOS sizes for Darkbloom routing, gated by DARKBLOOM_JOB_SHAPES Each macOS lane of CI's one route request can name a size, x. The route job checks every size against the plane's grammar and fails on a bad value before it sends anything. Sizes are sent only when the repository variable DARKBLOOM_JOB_SHAPES is exactly `on`. While it is off, the request is byte for byte the request without sizes and every job keeps its runner. The lane table in provider-plan.yml is the one place that names each job's lane and size. While sizes are on, the 7 blocking test jobs ask for 4x24, and build-cluster, build-provider, cluster-release-checks and test-cluster-gpu (count 2) ask for 12x32. These four are `required`: while sizes are off they keep blacksmith-12vcpu-macos-27 without asking and take no place under the DARKBLOOM_MACOS_LANES cap. The test lanes stay first in cap order. A sized lane uses a grant only when its labels end in the qualified label (darkbloom-macos-arm64-4x24); the job runs on that runs_on as sent. The route log and summary show the size asked and each decision with its reason. Co-Authored-By: Claude Opus 5.5 * ci: print the route request body in the route job's log The log now shows the exact request the route job sends, so a run proves what it asked for: no size while DARKBLOOM_JOB_SHAPES is off, each lane's size while it is on. The self-test pins the line to the request bytes. Co-Authored-By: Claude Opus 5.5 * Gemma TP: build greedy steps one ahead (GLM's step order) Gemma's request loop read each step's agreed token on the host before it built the next step, so the GPU and the collectives idled while the host read, answered the owner and committed. GLM tensor parallel builds step k+1 on step k's lazy token first (12.0 vs 13.4 ms a step on two M5 Ultras). - TensorParallelOneTokenLoop: GLM5NextTensorParallelStepLoop's order and stop rules, MLX-free, with the agreement as (token, flags), the commit given its step, and agreedStep for a collective every rank takes (greedy logprobs). - CBv2OwnedRequestState.submit: run's step submitted (asyncEval) and committed on host-held facts (paged native hosts only). - Gemma4TensorParallelPagedSession.submitDecode: the step on the previous selection's lazy agreed token. - Gemma4TensorParallelRequestLoop runs on the loop; greedy requests without logprobs pipeline, others read then build as before. - TensorParallelPlanChecks: 14 two-rank cases (order, collectives, endings, equality with read-then-build). Co-Authored-By: Claude Opus 5.5 * ci: cover the plane's `unavailable` fallback reason for sized lanes The plane falls back with `unavailable` when it cannot read its image catalog. The route job already logs any plane reason per lane with the size asked; the self-test now covers `unavailable` beside the other reasons, and the docs and changelog name it. Co-Authored-By: Claude Opus 5.5 * Gemma TP: build sampled steps one ahead too Rank 0's draw is the product's CBv2DefaultSampler, which advances its penalty counts with each drawn token on the device and its keyed step index with each draw; QwenStageTokenSampler.selected only configures it at the first draw. A draw built before the previous token is read is therefore the draw at its output index with the history up to it. Each step keeps its own lazy logprob gather (takePendingStepLogprobs), read after its token is agreed. Greedy requests asking for logprobs still read each step first (their top-k gather is a host-evaluated collective). Tests: pipelines() covers sampled requests (red on #1822: 2 failures); SamplingSelectionTests draws one step ahead and matches step-by-step tokens and logprobs (CPU); a GPU suite compares sampled build-ahead with read-then-build on two ranks. Co-Authored-By: Claude Opus 5.5 * Through Darkbloom a refused assistant quote plans plain tensor parallel and says why; only the serial qualification cites the assistant Review findings on the Qwen3.8-27B public assistant: - A failed or mismatched assistant quote no longer blocks a pair served through Darkbloom: it plans the ordinary target, as before the declaration, and the plan's one-line reason shows under the model on the screen and in `darkbloom cluster status` (kept with the adopted plan). A local cluster's refusal still stands. - Only the serial-schedule tensor-parallel qualification cites the assistant's evidence: the assistant needs serial prefill, so one-chunk-lookahead pairs decode plain and keep the model's evidence. - The evidence report says the 2.3x figure compares different layer splits; its digest is pinned again. Co-Authored-By: Claude Opus 5.5 * Changelog: the plain fallback and the serial qualification Co-Authored-By: Claude Opus 5.5 * Onboarding checks: a run's reader stops before its terminal closes TerminalRun's reader thread polled the master every 20 ms and stopped one poll after the run ended, but finish() returned at the run's end and release() closed both ends at once. The next run's openpty then reused the same descriptor numbers, and the old reader read the new terminal: on the master it took the next run's first lines ("role, before pairing: the title alone", run 42057277814), on the blocking slave end it took the next typed key ("coordinator q: left at once", run 42082393871). The reader is now in a DispatchGroup. finish() returns once the reader read the last byte and stopped; release() waits for it before closing. The run's end is read before the poll, so an empty read after it is the end of the text. A new harness check asserts that the reader has stopped when finish() returns and that no byte arrives after it. Co-Authored-By: Claude Opus 5.5 * ci: refactor pass for per-job macOS sizes - darkbloom-route.yml: give every lane record an explicit `held: false`, so the record's fields are named in one place; call the held lane a `required` lane in the header, as the `lanes` input does. - test-darkbloom-route.py: lane_jobs reads a count through evaluate_counts instead of a second copy of the count pattern. - build.md: say that a 12x32 job keeps its fallback without asking while job sizes are off; reflow a short line. No change to the request bytes, the routes or the summary. Co-Authored-By: Claude Opus 5.5 * tp-check gemma run: --layer-stride to measure Gemma's decode stride Gemma tensor parallel submits each decode step after every layer (decodeLayerStride = 1, "not yet measured for Gemma"). Qwen's pair measured 21.4 -> 20.2 ms per step at stride 8 (#1820). This adds the bench option that measures Gemma's stride on a pair before the product default moves: Gemma4TensorParallelModel.withLayerStride and gemma run --layer-stride N (paged path; full, shard or tp), bound into the ranks' workload digest, with a step p50 line. layerSubmissionKeepsEveryBit now also covers strides 5 and 8; a CPU test pins the wrapper's scope. Co-Authored-By: Claude Opus 5.5 * Gemma TP: one decode forward for decode and submitDecode; one select in the loop's step decode and submitDecode built the same forward (stride, decode frame, last row) twice; it is now decodeRow, so the built-ahead step is the read-then-build step's graph by construction. The request loop's step closure builds its select once for both orders. No behaviour change. Co-Authored-By: Claude Opus 5.5 * Gemma TP build-ahead: assert the late-stop stream; docs and changelog nits Review of #1822 (nits 1-3): the model-free check now asserts rank 0's stream against the agreed result in every case: exactly the result, or exactly one token more when built ahead and rank 1 stops on its own or runs out of pages (its flag rides one step later; the request errors on both ranks then), and never a token past a stop token. The docs say so instead of "the tokens are the read-then-build path's" unconditionally; the changelog names logit bias and penalties. Co-Authored-By: Claude Opus 5.5 * Gemma TP sampled build-ahead: changelog and test-hook nits Review of #1824 (nits 3 and 5): the changelog names greedy requests with logit bias or penalties (they draw through the sampler and are built ahead) and the one late-stop stream edge; the buildsAhead TaskLocal is marked tests-only. Co-Authored-By: Claude Opus 5.5 * Planning skips a served record it cannot evaluate; a blocked approved model says why A pair of M5 Ultras served Qwen 3.8 27B in tensor parallel with 7 prompts of 71,545 to 94,423 tokens (2026-11-05, 10:06-10:22Z). Their prompt plus answer is over the 65,536-token context the 27B's tensor-parallel request allowance covers, so every later plan of the 27B on that pair threw ("Tensor-parallel request allowance does not cover the requested context and chunk", from `ClusterPlacementPlanner.evaluate`) while calibrating the served records. The plan failed, the setup list keeps only choices without a blocker, and the 27B, tensor parallel only on that pair, left `darkbloom cluster` without a word; `darkbloom start` could not start it either. - `ClusterServedCalibration.measurements(entries:)` never fails the plan on a record: when a setup's calibration throws, each pair request the planner cannot evaluate on that placement is skipped, and the rest are calibrated as before (a setup that still cannot be calibrated is skipped whole). The skipped are counted in one plain line under the plan's served speeds. A setup whose calibration does not throw is calibrated exactly as before. The skip sits inside the calibration, so it holds whichever way the worker build filter (`servedBy`) ran first: an earlier build's records are left out before they are evaluated, the same build's (an update that kept the worker) are evaluated and skipped. - `darkbloom cluster` names each approved model it cannot offer, with its reason, in one line above the model list ("Qwen 3.8 27B: not offered on these two Macs: "), instead of hiding it. Tests: PlacementChecks plans the 27B (its product layout with the tensor-parallel allowance, saved as Golden/served/qwen38-27b-tensor-parallel-priced-layout.json) on the pair's anonymized records (Golden/served/m5ultra-pair-qwen-over-limit-2026-11-05.json: token counts, durations and modes as served; members, builds and request IDs synthetic); PlacementSetupCheck runs the provider's own decision on them; OnboardingChecks shows a blocked approved model with its reason. Co-Authored-By: Claude Opus 5.5 * tp-check gemma run: refuse --layer-stride in simulated mode Review of #1827 (nit 6): simulated runs both ranks on the local pair's own threads, which never see the TaskLocal stride, so the product stride ran while the log said stride=N. Gemma4TensorParallelModel .benchLayerStrideApplies(mode:) names the modes a stride reaches (full, shard, tp); the tool refuses any other, and the CPU test pins it. Co-Authored-By: Claude Opus 5.5 * Onboarding: name a blocked approved model without force-unwrapping its blocker Behaviour-neutral: the same line for the same choices, read through if-let. Co-Authored-By: Claude Opus 5.5 * ci: sample macOS job memory by class; bound update hash memory The resource sampler's "memory in use" (active + wired + compressed) mixed file cache into app memory and missed inactive anonymous pages, and its largest-RSS figure missed Metal memory. Sizes were picked from it. Sampler (report-only, never fails a job): - vm_stat classes: app (anonymous less purgeable), wired, file cache, compressed, used = app + wired + compressed; swap in use. - Per-process physical footprint from proc_pid_rusage (includes IOAccelerator memory) with lifetime peaks; the top three, their sum. - /usr/bin/footprint breakdown at new 2 GiB highs, at most twice a job. - Busy vCPUs from host CPU ticks instead of the ps %cpu averages. - Selection marks from run-provider-tests.sh and cluster-test-plan.py, so each large process and the peak name their test selection. - summary.json, and the sampled time scaled to 4 and 8 vCPUs. Provider (production change, memory only): UpdateAtomicFilesystem's sha256(file:) and treeHash(root:) read each 1 MiB chunk in its own autorelease pool, as WeightHasher does. On a Swift concurrency thread the autoreleased chunks otherwise stay resident: "Update rollback end to end" hashes the debug CLI many times and its test process held 15 GiB (provider shard 1, run 42041608780). The hashes are unchanged. Co-Authored-By: Claude Opus 5.5 * Qwen decode bench: one call site for the caller's layer stride QwenTensorParallelDecodeBench.pair ran the same run(...) call twice, with and without a layer-stride scope. One scope that keeps the current stride when the caller gives none does the same. The verify-window doc no longer says "layer by layer": windows submitted by layer (diagnostic) now use the decode stride, 8. Behaviour unchanged. Plan checks PASS; Qwen TP CPU suites 25/25. Co-Authored-By: Claude Opus 5.5 * Qwen TP stride 8: changelog and doc carry the re-measured gain Review of #1820: the quieter slot (2026-11-05 19:58Z) measured -15 % for one request and -13 % for four, replacing the first window's 6 %/16 %/20 %. Co-Authored-By: Claude Opus 5.5 * Qwen TP batch driver: build-ahead protocol (gated, off in the product) The driver can build a plain decode step before it reads the step before it, so the GPU and the collectives run while the host reads, publishes and answers (window 1 measured ~1.9 ms of GPU idle at each token boundary). - Every folded step's selection sum also carries two decision words (each rank's barrier flag) for the step two later. With no barrier and the unread step decoding the same lanes, both ranks build that step on the unread step's selection rows (executor submitDecode/readDecode, new, default unsupported). - Any event that needs a plan (owner stop or the answer to an ending token, join, idle lane, cancel or deadline, ended lane, output count, more than four held tokens) is a barrier: both ranks read every submitted step and the next plan is made and exchanged with nothing in flight, as today. - Held tokens are a queue (one published per answer); a decision that reads a stop marks the lane leaving and keeps the answer for the plan. - An EOS read after the next step was built discards that one forward; the generation schedule accepts one declared discarded forward after an EOS (a length finish still none). - Gate: QwenTensorParallelBatchSettings.buildsAhead adds qwen-tp-batch-build-ahead-v1 to the load agreement. Off: the native executor does not submit decode steps yet, so the product is unchanged. Tests: six two-rank fake-executor cases (steady decode at widths 1/2/4, EOS, owner stops at once and late, late credits, joins + prompts + cancellation, ranks that disagree failing closed), the gate, the schedule's EOS rule. With the build-ahead path disabled 3 fail; with it all pass, and every existing driver case is unchanged. Co-Authored-By: Claude Opus 5.5 * Served speeds: say an uncredited speed-up, plain skipped line, plain plan failure (#1828 nits) Completes #1828 for 0.10.9 (review: ship with nits). - The pipeline speculative credit that #1828 stopped failing the plan on (`crediting`) is no longer dropped silently: the plan says in one line, beside the skipped-records line, which Mac's served speed-up was not credited. Without it that pipeline is predicted at its plain decode, so the plan may choose another mode where the speculative pipeline served faster. - The skipped-records line is plain, with thousands separators: "Skipped 7 speed records longer than the 65,536 tokens planning covers (the longest was 94,522); the other records still count". Records skipped for another reason read "Skipped N speed records the plan could not evaluate on this model (the longest was N tokens)". - A model whose plan threw reads "not offered on these two Macs: the plan for it failed ()" instead of "Planning failed ()." - Tests: the whole-setup fallback (a setup that cannot be calibrated even after its unevaluable requests are skipped), the credit and its line, the line's wording and separators, and the not-offered line at 40 columns. - The fixture's `finishedAt` / `updatedAt` are rounded to the minute. Co-Authored-By: Claude Opus 5.5 * Qwen TP native executor: submit and read decode steps in two phases PR6 part a (stacked on #1830's driver protocol). The native batch executor can submit a plain decode rectangle without reading it, on the host's tokens or the previous rectangle's unread selection, and read it later: - CBv2OwnedRequestState.submitBatch: runBatch's frame submitted (asyncEval) and committed on host-held facts (a paged host's frontiers; a contiguous host reads them from the device, exact without overlap). - QwenTensorParallelBatchSession.submitDecode: decode's forward on lazy int32 tokens (one decodeResult body for both). - Selection split into buildSelection (graph nodes, each sampled row's lazy logprob gather kept with its step; a submitted step defers the gathered rows' finiteness check to its read) and readSelection (checks, then sampler history and logprobs on rank 0). select = build + read, the read-then-build order unchanged. - submitDecode/readDecode on the executor; buildsAhead is an init option, off by default, so the product is unchanged until part c. Test: buildAheadDecodeTakesTheReadThenBuildTokensAndLogprobs (two ranks, greedy, sampled with penalties and bias, and logprob rows, widths 1/2/4): build-ahead tokens, logprobs and folded control words equal the read-then-build cohort's. Passes on the CPU; with the old one-slot logprobs it fails (2 issues). GPU run queued (QWEN_TP_BATCH_GPU=1, paged host). Co-Authored-By: Claude Opus 5.5 * qwen-decode --build-ahead 0,1: measure the driver's build-ahead PR6 part c, measurement half. QwenTensorParallelDecodeBench takes buildsAhead modes beside the control modes (build-ahead with folded control only) and runs each through the real driver and native executor, after one warm run; every run of every mode must retire the same tokens, so the bench also checks build-ahead against read-then-build on real ranks. The log line carries build_ahead=0|1. The product still keeps it off. Co-Authored-By: Claude Opus 5.5 * Qwen TP build-ahead: review fixes (gate = behaviour, drain on failure, tests) Review of #1830: - The runtime passes QwenTensorParallelBatchSettings.buildsAhead (the load agreement's value) into the driver, so the gate and the behaviour are one value. - On a failure, a submitted unread step is drained before retireAll. - Decisions see the peer's reported cancellations (no publish, barrier). - The schedule accepts exactly one discarded forward after an EOS. - After a barrier the next step carries its successor's plan again, so only one step runs read-then-build instead of two. - Tests: the build-ahead path is asserted in the EOS, owner-stop and late-credit cases; disagreement in both directions fails both ranks at the first folded step; a corrupted decision word fails both; the held bound; an assisted row beside plain rows; a failure while a step is pending retires every lane. Harness bounds tightened to the driver's. With the build-ahead path disabled, 9 tests fail; with it, all 30 pass. Co-Authored-By: Claude Opus 5.5 * Native executor: the runtime passes the agreed buildsAhead into it too Review of #1830 (must-fix 1), executor half: QwenTensorParallelBatchSettings .buildsAhead now reaches both the driver and the native executor. Co-Authored-By: Claude Opus 5.5 * Onboarding checks: the reader reads the run's end through code, its bytes under withLock The reader read exitCode through its own copy of the code accessor and appended under a bare lock/unlock pair. It now uses code and lock.withLock, as PipeRun's reader does. The end is still checked before each poll; the comment says checked, not read, so it no longer reads as a byte read. Co-Authored-By: Claude Opus 5.5 * Retry cut prompt fixture downloads; keep integrity failures final prepare-prompt-fixtures.py tried each artifact once. On Darkbloom sandbox VMs an outbound connection sometimes ends early (darkbloom-sandbox issue 299), which failed Provider Unit Tests shard 1 with an SSL EOF or a short body reported as "size or SHA-256 mismatch". download() now retries only a cut or failed transfer: OSError (TLS, socket, connection, timeout), URLError, IncompleteRead, a body shorter than size_bytes, and HTTP 5xx. It makes at most 3 attempts per artifact with 1 s and 3 s backoff inside the existing 120 s deadline, and removes the partial file before each retry. A full-size wrong SHA-256, an oversize body, a Content-Length mismatch, a cross-origin redirect or response, another non-200 status, an output it did not create and the deadline fail at once. The short-read case is split from the SHA-256 mismatch so the two are told apart. prepare-mimo-prompt-fixtures.py had the same single-attempt urlopen and gets the same rule; a short body is detected against Content-Length. Co-Authored-By: Claude Opus 5.5 * Run the fixture download self-tests on dev; retry cut image fixture transfers The Provider Tests gate (ubuntu-24.04, every run, dev included) now runs test-prepare-prompt-fixtures.py and test-prepare-mimo-prompt-fixtures.py offline; dev CI ran neither, and no workflow ran the MiMo one. test-provider-ci-workflow.py pins the new step. Master keeps its run. prepare-mimo-image-http-fixtures.py made one curl attempt. It now applies the same rule: up to 3 attempts with 1 s and 3 s backoff inside a 120 s deadline per file. curl's exit code decides: a cut or failed transfer (6, 7, 16, 18, 28, 35, 52, 55, 56, 92), HTTP 5xx or a body shorter than its pin retries; an oversize body (63), any other curl failure, another non-200 status and a wrong digest fail at once. Plain --retry skips 18 and 56, and --retry-all-errors would retry 4xx and 63, so the rule is applied in Python. Co-Authored-By: Claude Opus 5.5 * Qwen TP build-ahead: tidy the submitted-decode input and a misplaced doc comment Behaviour-neutral: - QwenTensorParallelBatchSession.DecodeInput gains `rows`; the read tokens' vocabulary check runs once before the per-session loop (it checked every token once per session, before any page was reserved either way), and `submitted` is set in the same switch as the input. - CBv2OwnedRequestState: validateBatchRow's doc comment had ended up above submitBatch's; it is back on its function. Co-Authored-By: Claude Opus 5.5 * Qwen TP build-ahead: drain the newer step when a read fails (N1) Review of #1830-#1834, N1: in the continuation branch a failing read of the previous step left pending pointing at it, so the cleanup read it a second time and never drained the step already built ahead (probe: submit 4, read 3, read 3). pending now becomes the newer step before the read. Tests: aReadFailureWhileTheNextStepIsBuiltDrainsTheNewerStepOnce (red before: step 6 read twice, step 7 never; green after); the pending-failure test now checks every submitted step is read exactly once and the failed one never (N2); a built-ahead EOS leaves exactly one discarded forward (N4). Co-Authored-By: Claude Opus 5.5 * Native build-ahead: retire after a built-ahead EOS; paged submit reads no device frontier Review of #1830-#1834, N5 and the device-read gap: - aNativeLaneRetiresAfterABuiltAheadEOS: a native lane whose EOS is read after its next step was built retires as a clean EOS with exactly one discarded forward; red without the schedule's EOS rule. - CBv2StageKVHost.submittedDeviceFrontierReads counts the frontier checks a submitted frame reads from the device; the token-identity suite asserts none on a paged host (GPU) and that the counter is live on a contiguous one. Co-Authored-By: Claude Opus 5.5 * Refactor pass: state the retry classifier's order; name the curl attempt cap - prepare-prompt-fixtures.py, prepare-mimo-prompt-fixtures.py: drop urllib.error.URLError from the retryable tuple. It is an OSError subclass, so the result does not change. Say why HTTPError (and FileExistsError) must be tested before the OSError catch-all. - prepare-mimo-image-http-fixtures.py: name the 60 s curl --max-time cap ATTEMPT_SECONDS. - docs/developer/test.md: the two MiMo scripts do not apply the exact prompt-fixture rule. State the differences: they follow a redirect to a different HTTPS host, the MiMo prompt script has no total deadline, and the image script has a 120 s deadline for each file. Co-Authored-By: Claude Opus 5.5 * ci: say where Metal memory counts in the sampler's classes Run 42105290034 showed the GPU lane's Metal buffers as app (anonymous) memory: 35 GiB app against 12 GiB wired, with a 34 GiB IOAccelerator footprint. The sampler's text, the build doc and the changelog said wired held the GPU memory. Co-Authored-By: Claude Opus 5.5 * ci: refactor pass for the memory-class sampler - The sampler parses the marks file in one place (read_marks); a row with a bad time or pid is skipped by both readers, so a torn row can no longer stop the report. The capture threshold is named captured_bytes. - run-provider-tests.sh names the exclusive GPU filter once. - UpdateAtomicFilesystem calls autoreleasepool directly, as the rest of ProviderCore does; the hashed bytes and digests are unchanged. - build.md gives the measured per-class peaks (runs 42105290034 and 42123224100) in place of the old 21.5 / 18.8 / 32.8 GiB figures, and says when a footprint capture runs. Co-Authored-By: Claude Opus 5.5 * provider: release each chunk of a chunked file read On Darwin, FileHandle.read(upToCount:) and readData(ofLength:) return autoreleased storage. A Swift concurrency thread drains no autorelease pool between jobs, and a Dispatch block drains none before it returns, so a loop that reads a file or a pipe in chunks kept every chunk resident until its thread went idle: memory grew with the bytes read. FileHandle.readDrained(upToCount:) (ProviderCoreFoundation) runs each read in its own pool and is otherwise read(upToCount:). The chunked loops now use it: ManifestBuilder.hashOne, SpecDecStore .digestRegularFile, the metallib snapshot copy, SSDBlockStore .readExactly (the streamed KV restore), LiveContext.workerSHA256, MTPBenchmarkDigest.sha256(file:), DesktopWorker and SandboxChildProcess. sha256Digest(of:) keeps readData(ofLength:) inside a pool, and WorkerCodeIdentity, which cannot depend on ProviderCoreFoundation, pools its reads inline. Digests, copied bytes, errors and cancellation are unchanged. Tests read 256 MiB sparse files (or child output) through each site and check the known digest and less than 64 MiB of footprint growth. Co-Authored-By: Claude Opus 5.5 * ci: size each Darkbloom macOS lane from its sampled memory The per-job sizes of #1821 asked 4x24 for every test lane and 12x32 for the build, release-check and GPU lanes. Size each lane from the memory #1829's sampler recorded (runs 42105290034 and 42123224100): the smallest signed size that holds 1.25 times the job's used memory (app + wired + compressed) and makes it at most 5% slower. - provider-plan.yml: test-provider-1, test-cluster-1, test-cluster-focused and cluster-release-checks ask for 4x16; test-provider-2 and test-cluster-3 for 4x24; test-cluster-2 (29.3 GiB, GLM-5.3 paged KV Metal memory) and build-provider for 12x32; build-cluster for 8x16. Rewrite the stale "peak at 21.5 GiB" comment. - The test-cluster-gpu lane is gone: GPU shard 2 uses 42 GiB, which no signed size holds, and one lane carries one size for both shards. Both GPU shards run on blacksmith-12vcpu-macos-27, as before #1821. - While DARKBLOOM_JOB_SHAPES is off, the request bytes and every runner are unchanged; the `required` lanes and the cap order stay. - Self-tests: the size table, the exact variable-off request pinned as literal bytes, the cap cases for 10 jobs, and the unrouted GPU job. - Docs: Build Once, CI Runner Routing and Job sizes in build.md, the cluster CI notes in test.md, and the changelog fragment. Co-Authored-By: Claude Opus 5.5 * provider: keep desktop and sandbox output tails compact DesktopOutputBuffer kept its last 32 KiB as `data.suffix(_:)` and SandboxOutputTail as `removeFirst(_:)`. Both make a slice of the same storage, and each later append grows that storage, so the tail held every byte the child wrote. ChildOutputReadMemoryTests found it: 256 MiB of output left 258 MiB resident with drained reads. Each tail is now a copy of its last bytes; the text it gives is unchanged. Co-Authored-By: Claude Opus 5.5 * ci: ask 8x16 for the release build checks; state the unsized lane size - provider-plan.yml: cluster-release-checks asks for 8x16, not 4x16. Its 4x16 basis came from reused builds only. A cold release compile runs 12 parallel jobs at 11.4 busy vCPUs (p95, run 42041608780) and takes 26% longer on 4 vCPUs, 5.5% on 8: the case of build-cluster. - build.md: a lane without a size gets the approval's pinned image size, which measured 12 vCPU / 32 GiB on 2026-11-05 (run 42105290034, attempt 1), not a fixed 4 vCPU / 16 GiB default. - The route self-test's size table and the changelog fragment follow. Co-Authored-By: Claude Opus 5.5 * test(cluster-api): a stream rejected mid-generation before the pair retires Red on dev 240794646b: the cluster's SSE writer drops the shared pipeline's own failure frame when the pair has not yet retired the cancelled request, and the stream ends after the role delta. This is the intermittent `tool-choice-named-stream` difference in ClusterAPIParityTests: the harness pair acknowledges retirement at once, so the native terminal usually wins the race. - DistributedHTTPVisibleContentTests: the product failure frame ends the stream whether the native terminal came first or not (fails with `missingTerminal` when it did not). - ClusterAPIParityTests: the named tool choice stream, for the five families whose fixture output is a forced-call violation, with the fabricated pair's retirement acknowledgment held until the client has the answer; the cluster answer must equal the single-Mac answer. - ClusterAPIParityHarness: `drive` takes an optional retirement gate; without one it behaves as before. Locally on this commit: 20 of 20 runs fail both tests (1 writer issue, 5 family issues each). Co-Authored-By: Claude Opus 5.5 * fix(cluster-api): end a rejected stream with the single-Mac error chunk before the pair retires When the shared pipeline rejects a streamed chat completion mid-generation (a forced tool choice answered with text, a streamed call that fails validation), it cancels the request and frames its own error chunk. A pair publishes the cancellation's native terminal only once both ranks retired the request, and `DistributedHTTPEventStream.consume` asked `failureFrame(for:upstreamFailed:identity:)` first, which throws `missingTerminal` without one. The product's error chunk, already held in `trailing`, was dropped and the body aborted after the role delta: the client saw the stream stop with no error chunk and no clean end of the chunked transfer. The writer now sends the pipeline's own failure frame whenever it framed one, and consults the native terminal only for failures it must frame itself. Native ownership, retirement and cancellation are unchanged; no terminal or usage is fabricated. This was the intermittent `tool-choice-named-stream` difference in ClusterAPIParityTests. The forced-order tests added in the previous commit now pass 20 of 20 runs. Co-Authored-By: Claude Opus 5.5 * provider: keep the BoundedProcess stderr tail compact StderrTailBox trimmed with removeFirst(_:), which slices: each later append grew the shared storage, so the tail kept all of a child's stderr. It now keeps a copy of its last bytes; the reported text is unchanged. The readabilityHandler's availableData read runs in its own autorelease pool, as the other chunked reads do. BoundedProcessStderrMemoryTests runs a real child that writes 256 MiB to stderr and checks the footprint while it runs, then its exit status and tail. Co-Authored-By: Claude Opus 5.5 * ci: tighten the job size comment and the size self-tests Refactor pass for the measured job sizes. No lane, size, count or runner changes. - provider-plan.yml: state the size rule and its two real exceptions (cluster runtime shard 2 at 12x32, the 8x16 builds); Build provider test products follows the rule. Point to build.md for each job's memory. - test-provider-ci-workflow.py: one LANE_SIZE pattern instead of two line-end patterns. - test-darkbloom-route.py: the size test names routed macOS jobs, since Cluster GPU Tests are not routed. - test.md: rewrap the lines this PR touched. Co-Authored-By: Claude Opus 5.5 * test(cluster-api): pin cancellation and freed places in the forced-order test; review nits Review nits on #1839: - The forced-order test now requires, after the error chunk and before retirement, that the pipeline cancelled the pair's request (the fabricated lease takes no clean stop), that its acquisition and HTTP response hold are free while the lease is still held and its lane still counted, and, after retirement, that the lease is released and the lane freed. - The single-Mac failure precondition is a `#require`, so a fixture that stops failing cannot pass silently. - Plainer changelog and docs wording: what a client saw before (HTTP 200, the chunks already sent, then the connection closed with no error chunk), and "while the pair is still finishing the cancelled request". Co-Authored-By: Claude Opus 5.5 * provider: share the compact output tail as Data.keepLast DesktopOutputBuffer, SandboxOutputTail and StderrTailBox each trimmed their tail with the same copy-not-slice step and the same comment. One ProviderCoreFoundation helper, Data.keepLast(_:), now holds that step and its reason; the bytes kept and the truncation flag do not change. Also: the inference doc names the worker digest key's modification time (st_mtimespec), not change time, and WorkerCodeIdentity says why its read pool is inline. Co-Authored-By: Claude Opus 5.5 * test: disable the flaky GLM video readiness test Disable GLM5NextMediaRoutingTests.openRouterReadinessVideosReachTheEngineInsteadOfInvalidMedia with a Swift Testing .disabled trait, on David's ruling of 2026-11-06. The MP4 readiness clip (input-video-url.mp4) sometimes fails with "GLM media input: video decoding failed" on a Darkbloom macOS VM (run 42135729166, job 127627938752). Issue #1847 tracks the cause. The test body and its assertions do not change. Refs #1847 Co-Authored-By: Claude Opus 5.5 * Revert #1848: run the GLM video readiness test again David, 2026-11-06: "don't disable, put in a fix for it". The test runs again; the root-cause fix for the intermittent "video decoding failed" (issue #1847) follows in its own PR. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: jonathan308 <5055076+jonathan308@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Jonathan Spangler Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> --- .github/actions/provider-ci-build/action.yml | 23 +- .../actions/provider-ci-products/action.yml | 71 + .github/workflows/darkbloom-route.yml | 75 +- .github/workflows/provider-plan.yml | 50 +- .github/workflows/provider-tests.yml | 572 +++++-- changelog.d/chunked-read-memory.md | 6 + changelog.d/ci-build-once.md | 10 + changelog.d/ci-macos-job-sizes.md | 9 + changelog.d/ci-true-memory.md | 4 + ...-stream-failure-frame-before-retirement.md | 3 + ...nsor-parallel-builds-greedy-steps-ahead.md | 3 + ...sor-parallel-builds-sampled-steps-ahead.md | 3 + .../metal-cpp-from-the-sandbox-image.md | 4 + changelog.d/qwen27-public-assistant.md | 22 + ...allel-decode-submits-every-eight-layers.md | 3 + docs/architecture/inference.md | 125 +- .../architecture/security/identity-binding.md | 5 +- docs/developer/build.md | 222 ++- docs/developer/test.md | 119 +- docs/provider/direct-mode.md | 13 +- docs/reference/configuration.md | 14 +- docs/reference/model-registry-format.md | 6 +- docs/reference/ssd-kv-cache.md | 4 +- .../2026-11-05-qwen27-public-assistant.md | 105 ++ docs/reports/README.md | 3 +- .../TensorParallelCheck/GemmaCheck.swift | 87 +- .../TensorParallelCheck/QwenDecodeCheck.swift | 46 +- .../ClusterServedSpeed.swift | 36 +- .../ClusterServedSpeedRule.swift | 10 + .../ClusterPairTelemetry.swift | 14 +- .../Gemma4TensorParallelPagedSession.swift | 54 +- .../Gemma4TensorParallelRequestLoop.swift | 141 +- .../ClusterPlacementTool+Served.swift | 9 +- .../QwenLayerStageGenerationSchedule.swift | 9 +- .../Generation/QwenStageTokenSampler.swift | 19 +- .../QwenTensorParallelBatchDriver.swift | 323 +++- .../QwenTensorParallelBatchSession.swift | 63 +- .../QwenTensorParallelBatchSettings.swift | 6 + .../QwenTensorParallelBatchWire.swift | 6 + .../QwenTensorParallelDecodeBench.swift | 37 +- .../QwenTensorParallelLaunch.swift | 23 + .../QwenTensorParallelMTPTarget.swift | 5 +- ...wenTensorParallelNativeBatchExecutor.swift | 132 +- ...nTensorParallelResidentRuntime+Batch.swift | 4 +- .../QwenTensorParallelResidentRuntime.swift | 11 +- .../TensorParallelOneTokenLoop.swift | 99 ++ .../State/CBv2OwnedRequestState.swift | 113 ++ .../State/CBv2StageKVHost.swift | 4 + .../Gemma4TensorParallelRuntimeTests.swift | 69 +- ...pendentHistoryBatchDriverTestSupport.swift | 7 +- .../QwenTensorParallelBatchDriverTests.swift | 336 ++++- .../QwenTensorParallelBatchSessionTests.swift | 209 ++- ...QwenTensorParallelBatchSettingsTests.swift | 5 + .../SamplingSelectionTests.swift | 44 + .../SSHChecks/OwnerWriterWakeTests.swift | 56 +- .../Tests/SSHChecks/README.md | 5 +- .../OneTokenLoopCheck.swift | 209 +++ .../TensorParallelPlanCheck.swift | 20 + .../Tests/TensorParallelPlanChecks/run.sh | 7 +- .../Worker/WorkerPeerIdentity.swift | 17 +- .../MTPBenchmarkDigest.swift | 3 +- .../Config/ClusterConfiguration.swift | 18 +- .../ClusterRuntimeApprovalFacts+Release.swift | 2 +- .../Config/ClusterRuntimeApprovalFacts.swift | 28 +- .../ClusterSetupWizardLiveOperations.swift | 34 +- .../Console/ClusterSetupWizardPlanning.swift | 41 +- .../Console/ClusterSetupWizardState.swift | 4 + .../Console/ClusterSetupWizardStore.swift | 3 + .../Installed/ClusterPublicModels.swift | 80 +- .../DistributedInstalledNativeStart.swift | 15 +- ...DistributedInstalledPairServingGrant.swift | 17 +- .../DistributedInstalledSession.swift | 3 +- .../Installed/DistributedSessionFacts.swift | 15 +- .../ClusterApprovalAttachment.swift | 7 +- .../Observability/ClusterObservability.swift | 3 +- .../DistributedPairTelemetryRecorder.swift | 11 +- .../Onboarding/ClusterOnboardingLive.swift | 7 +- .../Placement/ClusterPlacementFlow.swift | 8 +- ...terPlacementTensorAssistantSelection.swift | 57 +- .../ClusterRequestRoutingBasis.swift | 11 +- .../Engine/Bridge/EngineV2Bridge+MTP.swift | 5 + .../KVCacheSSD/SSDBlockStore.swift | 4 +- .../ProviderCore/Process/BoundedProcess.swift | 9 +- .../ProviderLoop+ClusterPairServing.swift | 5 +- .../ProviderLoop+ClusterPairSlot.swift | 7 + .../ProviderCore/Security/BinaryHasher.swift | 10 +- .../DistributedHTTPEventStream.swift | 13 +- .../DistributedLocalServer+Startup.swift | 3 +- .../ProviderCore/SpecDec/SpecDecStore.swift | 4 +- .../Update/UpdateAtomicFilesystem.swift | 22 +- .../Data+KeepLast.swift | 16 + .../FileHandle+DrainedRead.swift | 20 + .../ManifestBuilder.swift | 6 +- .../darkbloom/ClusterPairSummary+Live.swift | 1 + .../darkbloom/ClusterPairSummary.swift | 3 + .../darkbloom/Desktop/DesktopWorker.swift | 7 +- .../Sandbox/SandboxChildProcess.swift | 5 +- .../OnboardingChecks.swift | 34 +- .../ChildOutputReadMemoryTests.swift | 100 ++ .../ClusterPairCommandsTests.swift | 13 + .../ChunkedReadMemoryTests.swift | 188 +++ .../ClusterRuntimeApprovalFactsTests.swift | 7 +- .../ClusterPublicTensorAssistantTests.swift | 255 ++++ .../ClusterObservabilityTests.swift | 54 +- .../ClusterOwnerServingTests.swift | 12 +- ...istributedAutomaticBatchPlannerTests.swift | 115 +- .../BoundedProcessStderrMemoryTests.swift | 80 + .../ProviderLoop/ClusterPairSlotTests.swift | 25 +- .../Distributed/ClusterAPIParityHarness.swift | 9 +- .../Distributed/ClusterAPIParityTests.swift | 52 + .../DistributedHTTPDeliveryTestSupport.swift | 11 + .../DistributedHTTPVisibleContentTests.swift | 23 + .../Update/UpdateFileHashMemoryTests.swift | 55 + scripts/ci-component-paths.py | 2 + scripts/ci-resource-sampler.py | 494 ++++++ scripts/ci-test-products.py | 226 +++ scripts/cluster-test-plan.py | 100 +- scripts/docs-impact-rules.json | 2 +- scripts/fetch-metallib.sh | 28 +- scripts/prepare-mimo-image-http-fixtures.py | 56 +- scripts/prepare-mimo-prompt-fixtures.py | 45 +- scripts/prepare-prompt-fixtures.py | 47 +- scripts/provider-test-shard-weights.json | 1322 +++++++++-------- scripts/provider-test-shards.py | 21 +- scripts/run-provider-tests.sh | 17 +- scripts/swift_test_lock_retry.py | 9 +- scripts/test-ci-component-paths.py | 31 +- scripts/test-ci-resource-sampler.py | 280 ++++ scripts/test-ci-test-products.py | 158 ++ scripts/test-cluster-test-plan.py | 98 +- scripts/test-darkbloom-route.py | 329 +++- .../test-prepare-mimo-image-http-fixtures.py | 79 + scripts/test-prepare-mimo-prompt-fixtures.py | 79 + .../test-prepare-mimo-provider-fixtures.py | 2 +- scripts/test-prepare-prompt-fixtures.py | 127 +- scripts/test-provider-ci-workflow.py | 313 +++- scripts/test-provider-test-shards.py | 37 +- 137 files changed, 7715 insertions(+), 1436 deletions(-) create mode 100644 .github/actions/provider-ci-products/action.yml create mode 100644 changelog.d/chunked-read-memory.md create mode 100644 changelog.d/ci-build-once.md create mode 100644 changelog.d/ci-macos-job-sizes.md create mode 100644 changelog.d/ci-true-memory.md create mode 100644 changelog.d/cluster-stream-failure-frame-before-retirement.md create mode 100644 changelog.d/gemma-tensor-parallel-builds-greedy-steps-ahead.md create mode 100644 changelog.d/gemma-tensor-parallel-builds-sampled-steps-ahead.md create mode 100644 changelog.d/metal-cpp-from-the-sandbox-image.md create mode 100644 changelog.d/qwen27-public-assistant.md create mode 100644 changelog.d/tensor-parallel-decode-submits-every-eight-layers.md create mode 100644 docs/reports/2026-11-05-qwen27-public-assistant.md create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/TensorParallelOneTokenLoop.swift create mode 100644 libs/darkbloom-cluster/Tests/TensorParallelPlanChecks/OneTokenLoopCheck.swift create mode 100644 provider-swift/Sources/ProviderCoreFoundation/Data+KeepLast.swift create mode 100644 provider-swift/Sources/ProviderCoreFoundation/FileHandle+DrainedRead.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/ChildOutputReadMemoryTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/ChunkedReadMemoryTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterPublicTensorAssistantTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Process/BoundedProcessStderrMemoryTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Update/UpdateFileHashMemoryTests.swift create mode 100755 scripts/ci-resource-sampler.py create mode 100755 scripts/ci-test-products.py create mode 100755 scripts/test-ci-resource-sampler.py create mode 100755 scripts/test-ci-test-products.py diff --git a/.github/actions/provider-ci-build/action.yml b/.github/actions/provider-ci-build/action.yml index 03d9a2f83a..cce52ba09e 100644 --- a/.github/actions/provider-ci-build/action.yml +++ b/.github/actions/provider-ci-build/action.yml @@ -45,13 +45,26 @@ runs: # 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)" + # The jobs of the test products run in a workspace linked to + # /private/tmp/dinf. actions/cache stores each path relative to the + # workspace, so a path that shares more than `/` with the workspace + # (runner.temp, the home directory) would be unpacked under the link's + # target instead; every cache outside the workspace lives in + # /private/tmp/dinf-ci. SwiftPM reads its repositories from the home + # directory, through this link. + - name: Link SwiftPM's repository cache into the CI cache directory + shell: bash + run: | + mkdir -p /private/tmp/dinf-ci/swiftpm-repositories "$HOME/Library/Caches/org.swift.swiftpm" + rm -rf "$HOME/Library/Caches/org.swift.swiftpm/repositories" + ln -s /private/tmp/dinf-ci/swiftpm-repositories "$HOME/Library/Caches/org.swift.swiftpm/repositories" # 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 + path: /private/tmp/dinf-ci/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 @@ -139,20 +152,20 @@ runs: 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 + path: /private/tmp/dinf-ci/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 with: - path: ${{ runner.temp }}/metallib-cache + path: /private/tmp/dinf-ci/metallib-cache key: ${{ steps.keys.outputs.metallib-key }} - name: Validate and stage matched Metal for the actual test products id: metallib shell: bash env: LANE: ${{ inputs.lane }} - METALLIB_CACHE_DIR: ${{ runner.temp }}/metallib-cache + METALLIB_CACHE_DIR: /private/tmp/dinf-ci/metallib-cache run: | cmake --version case "$LANE" in @@ -165,5 +178,5 @@ runs: 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 + path: /private/tmp/dinf-ci/metallib-cache key: ${{ steps.keys.outputs.metallib-key }} diff --git a/.github/actions/provider-ci-products/action.yml b/.github/actions/provider-ci-products/action.yml new file mode 100644 index 0000000000..bda15696c1 --- /dev/null +++ b/.github/actions/provider-ci-products/action.yml @@ -0,0 +1,71 @@ +name: Provider CI Products +description: Hand one lane's debug test products from its build job to its test jobs at the fixed build path +inputs: + lane: + description: provider or cluster + required: true + direction: + description: "upload (the build job, after provider-ci-build) or download (a test job, before its tests)" + required: true +runs: + using: composite + steps: + - name: Validate the lane and direction + shell: bash + env: + LANE: ${{ inputs.lane }} + DIRECTION: ${{ inputs.direction }} + run: | + case "$LANE/$DIRECTION" in + provider/upload|provider/download|cluster/upload|cluster/download) ;; + *) echo "Unknown test products lane or direction: $LANE/$DIRECTION" >&2; exit 2 ;; + esac + - name: Pack the test products + if: inputs.direction == 'upload' + shell: bash + env: + LANE: ${{ inputs.lane }} + run: python3 scripts/ci-test-products.py pack "$LANE" "$RUNNER_TEMP/test-products/$LANE.tar.zst" + # The archive is zstd already; the artifact store keeps it as it is. + - name: Upload the test products + if: inputs.direction == 'upload' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: ${{ inputs.lane }}-test-products + path: ${{ runner.temp }}/test-products/${{ inputs.lane }}.tar.zst + compression-level: 0 + if-no-files-found: error + overwrite: true + retention-days: 1 + - name: Report the upload time + if: inputs.direction == 'upload' + shell: bash + env: + LANE: ${{ inputs.lane }} + run: python3 scripts/ci-test-products.py uploaded "$RUNNER_TEMP/test-products/$LANE.tar.zst" + # The test job runs the products under the build job's toolchain, which + # the unpack step checks; it needs no CMake and no Metal toolchain. + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + if: inputs.direction == 'download' + with: + python-version: '3.12.10' + - name: Select SDK 27 provider toolchain + if: inputs.direction == 'download' + shell: bash + run: ./scripts/prepare-provider-release-toolchain.sh + - name: Start the download clock + if: inputs.direction == 'download' + shell: bash + run: python3 scripts/ci-test-products.py stamp + - name: Download the test products + if: inputs.direction == 'download' + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: ${{ inputs.lane }}-test-products + path: ${{ runner.temp }}/test-products + - name: Check and unpack the test products + if: inputs.direction == 'download' + shell: bash + env: + LANE: ${{ inputs.lane }} + run: python3 scripts/ci-test-products.py unpack "$LANE" "$RUNNER_TEMP/test-products/$LANE.tar.zst" diff --git a/.github/workflows/darkbloom-route.yml b/.github/workflows/darkbloom-route.yml index 07aee13139..5f851bb394 100644 --- a/.github/workflows/darkbloom-route.yml +++ b/.github/workflows/darkbloom-route.yml @@ -6,15 +6,21 @@ name: Darkbloom Route # 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. +# fallback without asking. A macOS lane can name a size. Sizes are sent only +# when the DARKBLOOM_JOB_SHAPES variable is exactly `on`; otherwise the request +# is the one without sizes, and a `required` lane keeps its fallback without +# asking. on: workflow_call: inputs: lanes: description: >- - One lane per line: ` [count]`. - Profiles are linux_arm64 and macos_arm64. Count is the number of jobs - that will run (default 1); 0 keeps the fallback without asking. + One lane per line: ` [count [size + [required]]]`. Profiles are linux_arm64 and macos_arm64. Count is the + number of jobs that will run (default 1); 0 keeps the fallback + without asking. Size, macOS only, is `x`, such as 4x24. + While sizes are off, a `required` lane keeps its fallback without + asking, and any other lane asks without its size. type: string required: true outputs: @@ -40,6 +46,7 @@ jobs: LANES: ${{ inputs.lanes }} ROUTING: ${{ vars.DARKBLOOM_ROUTING }} MACOS_LANES: ${{ vars.DARKBLOOM_MACOS_LANES }} + JOB_SHAPES: ${{ vars.DARKBLOOM_JOB_SHAPES }} PLANE_URL: ${{ vars.DARKBLOOM_SANDBOX_URL }} REPOSITORY: ${{ github.repository }} EVENT_NAME: ${{ github.event_name }} @@ -51,6 +58,8 @@ jobs: # The only labels a lane can receive besides its fallback. A plane # decision is used only when it repeats its profile's array exactly. + # For a lane sent with a size, the size qualifies the last label + # (darkbloom-macos-arm64-4x24). profiles='{"linux_arm64":["self-hosted","linux","ARM64","darkbloom-linux-arm64"],"macos_arm64":["self-hosted","macOS","ARM64","darkbloom-macos-arm64"]}' # Plane text is untrusted: keep it short, on one line, and free of # Markdown, HTML and workflow-command syntax before printing it. @@ -63,23 +72,48 @@ jobs: configured='[]' seen=' ' - while read -r lane profile fallback count extra; do + while read -r lane profile fallback count shape required extra; do [ -n "$lane" ] || continue count=${count:-1} - [ -z "$extra" ] || configuration_error "lane $lane has more than four fields" + [ -z "$extra" ] || configuration_error "lane $lane has more than six fields" [[ $lane =~ ^[A-Za-z0-9_-]+$ ]] || configuration_error "invalid lane name: $lane" jq -e --arg profile "$profile" 'has($profile)' <<<"$profiles" >/dev/null \ || configuration_error "lane $lane has unknown profile: $profile" [[ $fallback =~ ^[A-Za-z0-9._-]+$ ]] \ || configuration_error "lane $lane has invalid fallback label: $fallback" [[ $count =~ ^(0|[1-9][0-9]?)$ ]] || configuration_error "lane $lane has invalid count: $count" + # The plane's size grammar: x, lowercase decimal, no leading zeros. + if [ -n "$shape" ]; then + [[ $shape =~ ^[1-9][0-9]*x[1-9][0-9]*$ ]] \ + || configuration_error "lane $lane has invalid size: $shape (use x, such as 4x24)" + [ "$profile" = macos_arm64 ] || configuration_error "lane $lane has a size, but sizes are macOS only" + fi + [ -z "$required" ] || [ "$required" = required ] \ + || configuration_error "lane $lane has an unknown sixth field: $required" case $seen in *" $lane "*) configuration_error "lane $lane is listed twice" ;; esac seen="$seen$lane " configured=$(jq -c --arg lane "$lane" --arg profile "$profile" --arg fallback "$fallback" \ - --argjson count "$count" '. + [{$lane, $profile, $fallback, $count}]' <<<"$configured") + --argjson count "$count" --arg shape "$shape" --arg required "$required" \ + '. + [{$lane, $profile, $fallback, $count, + shape: (if $shape == "" then null else $shape end), required: ($required != ""), held: false}]' \ + <<<"$configured") done <<<"${LANES:-}" [ "$configured" != '[]' ] || configuration_error "no lanes are configured" + # Job sizes are a repository setting, off unless exactly `on`. While + # they are off, no size is sent, so the request is the request of a + # lane table without sizes. A `required` lane is then held: it keeps + # its fallback without asking and takes no place under the macOS cap. + shapes_note="" + if jq -e 'any(.[]; .shape != null)' <<<"$configured" >/dev/null; then + if [ "${JOB_SHAPES:-}" = on ]; then + shapes_note=" Job sizes are on: DARKBLOOM_JOB_SHAPES is 'on'." + else + shapes_note=" Job sizes are off: DARKBLOOM_JOB_SHAPES is not 'on'. No size was requested." + configured=$(jq -c 'map(.held = .required | .shape = null)' <<<"$configured") + fi + fi + # 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:-} @@ -90,13 +124,16 @@ jobs: 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 + if $entry.held then .lanes += [$entry + {capped: false}] + elif $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") + # A lane without a size is exactly {lane, profile, count}. + requested=$(jq -c '[.[] | select(.count > 0 and (.capped | not) and (.held | not)) + | {lane, profile, count} + (if .shape != null then {shape} else {} end)]' <<<"$configured") plane_url=${PLANE_URL:-https://api-sandbox.darkbloom.dev} body=$(mktemp) @@ -121,6 +158,8 @@ jobs: request=$(jq -n -c --arg repository "$REPOSITORY" --argjson run_id "$RUN_ID" \ --argjson run_attempt "$RUN_ATTEMPT" --argjson lanes "$requested" \ '{$repository, $run_id, $run_attempt, $lanes}') + # The request names only the repository, the run and the lanes. + echo "Request: $request" # One attempt plus at most one retry after a transport failure, # timeout or transient status; each attempt is bounded to 5 seconds. for attempt in 1 2; do @@ -157,28 +196,32 @@ jobs: ($reply[0].lanes // {}) as $plane_decisions | [ $configured[] | ($plane_decisions[.lane] | if type == "object" then . else {} end) as $decision + | (.shape as $shape | $profiles[.profile] + | if $shape == null then . else .[:-1] + [.[-1] + "-" + $shape] end) as $labels | if .count == 0 then .target = "fallback" | .reason = "not requested" elif $fallback_reason != "" then .target = "fallback" | .reason = $fallback_reason + elif .held then .target = "fallback" | .reason = "needs its size, and job sizes are off (DARKBLOOM_JOB_SHAPES)" elif .capped then .target = "fallback" | .reason = "over the macOS lane cap (DARKBLOOM_MACOS_LANES)" - elif $decision.target == "darkbloom" and $decision.runs_on == $profiles[.profile] + elif $decision.target == "darkbloom" and $decision.runs_on == $labels then .target = "darkbloom" | .reason = "granted" elif $decision.target == "fallback" then .target = "fallback" | .reason = "plane: " + ($decision.reason // "no reason" | clean) else .target = "fallback" | .reason = "plane decision is missing or invalid" end - | .runs_on = (if .target == "darkbloom" then $profiles[.profile] else .fallback end) ]') + | .runs_on = (if .target == "darkbloom" then $decision.runs_on else .fallback end) ]') routes=$(jq -c 'map({key: .lane, value: .runs_on}) | from_entries' <<<"$decisions") echo "routes=$routes" >> "$GITHUB_OUTPUT" - note="$note$cap_note" + note="$note$cap_note$shapes_note" echo "$note" - jq -r '.[] | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason))"' <<<"$decisions" + jq -r '.[] | (if .shape == null then "" else "; size \(.shape)" end) as $size + | "\(.lane): \(.runs_on | if type == "array" then join(",") else . end) (\(.reason)\($size))"' <<<"$decisions" { echo "### Darkbloom runner routing" echo echo "$note" echo - echo "| Lane | Profile | Jobs | Runner | Decision |" - echo "| --- | --- | --- | --- | --- |" - jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions" + echo "| Lane | Profile | Jobs | Size | Runner | Decision |" + echo "| --- | --- | --- | --- | --- | --- |" + jq -r '.[] | "| `\(.lane)` | \(.profile) | \(.count) | \(.shape // "-") | `\(.runs_on | if type == "array" then join(", ") else . end)` | \(.target): \(.reason) |"' <<<"$decisions" } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/provider-plan.yml b/.github/workflows/provider-plan.yml index 536d633213..531c82dfdd 100644 --- a/.github/workflows/provider-plan.yml +++ b/.github/workflows/provider-plan.yml @@ -137,24 +137,46 @@ jobs: 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. + # Chooses a Darkbloom Sandbox or the Blacksmith fallback for the macOS jobs + # of provider-tests.yml. This table is the one place that names each job's + # lane and size. A lane is granted whole or falls back whole, so each job + # (each shard) has a lane of its own and falls back alone, except the two + # Cluster Focused Checks shards, which share one lane with a count of 2. A + # lane asks for a job only when the job runs. The two Cluster GPU Tests + # shards are not routed: shard 2 uses 42 GiB, more than any signed size, + # and one lane carries one size for both shards. They run on + # blacksmith-12vcpu-macos-27. + # + # Sizes (x) are sent only while DARKBLOOM_JOB_SHAPES is `on` + # (darkbloom-route.yml). A job asks for the smallest signed size (4x16, + # 4x24, 8x16, 12x32) that holds 1.25 times its sampled used memory (app + + # wired + compressed, scripts/ci-resource-sampler.py) and on which it is at + # most 5% slower than on 12 vCPUs. There are two exceptions. Cluster runtime + # shard 2 uses 29.3 GiB (the Metal memory of the GLM-5.3 paged KV tests): + # 12x32, the largest size, holds it with a smaller margin. Build cluster + # test products and Cluster Release Build Checks ask for 8x16, on which a + # cold build is 5 to 10% slower. The sampled memory of each job is in + # docs/developer/build.md (Job sizes). + # + # While sizes are off, the 7 blocking test jobs ask without a size, as + # before. The build jobs and Cluster Release Build Checks are `required`: + # while sizes are off they keep Blacksmith without asking. The lanes are in + # the order the DARKBLOOM_MACOS_LANES cap keeps them: the critical-path test + # shards first, then the `required` jobs. route: - needs: [components, tested] + needs: [tested, components] 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 }} + test-cluster-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} 12x32 + test-cluster-3 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} 4x24 + test-cluster-focused macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 2 || 0 }} 4x16 + test-provider-2 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.provider == 'true' && 1 || 0 }} 4x24 + test-cluster-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} 4x16 + test-provider-1 macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.provider == 'true' && 1 || 0 }} 4x16 + build-cluster macos_arm64 blacksmith-12vcpu-macos-27 ${{ (needs.components.outputs.cluster == 'true' || (github.event_name == 'push' && needs.tested.outputs.skip == 'true' && needs.components.outputs.changed_cluster == 'true')) && 1 || 0 }} 8x16 required + build-provider macos_arm64 blacksmith-12vcpu-macos-27 ${{ (needs.components.outputs.provider == 'true' || (github.event_name == 'push' && needs.tested.outputs.skip == 'true' && needs.components.outputs.changed_provider == 'true')) && 1 || 0 }} 12x32 required + cluster-release-checks macos_arm64 blacksmith-12vcpu-macos-27 ${{ needs.components.outputs.cluster == 'true' && 1 || 0 }} 8x16 required diff --git a/.github/workflows/provider-tests.yml b/.github/workflows/provider-tests.yml index 9786246ba6..e769ced7c2 100644 --- a/.github/workflows/provider-tests.yml +++ b/.github/workflows/provider-tests.yml @@ -1,10 +1,11 @@ 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) +# The provider and cluster build and 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. +# the components and the runner of every macOS job; pull requests and pushes +# run the same jobs. Each lane builds once, on a large runner, and its test +# jobs run those products. Only pushes save caches. on: workflow_call: inputs: @@ -44,19 +45,193 @@ env: !/landing/public/media/ jobs: + build-cluster: + # Each lane builds once, on a large runner, and hands its debug test + # products to its test jobs (.github/actions/provider-ci-products). The + # cluster lane builds in a job of its own, so the cluster tests start as + # soon as their products are up. A push whose tree a pull request run + # already tested runs no test job; the build job then builds only the + # components the push changed, to refresh the branch's caches. The build + # jobs need a large Mac: their lanes ask only with their size, while job + # sizes are on; otherwise they run on Blacksmith (provider-plan.yml). + name: Build cluster test products + if: ${{ inputs.cluster == 'true' || (github.event_name == 'push' && inputs.skip == 'true' && inputs.changed_cluster == 'true') }} + runs-on: ${{ fromJSON(inputs.routes)['build-cluster'] }} + timeout-minutes: 60 + steps: + # SwiftPM's products hold absolute paths, and Blacksmith and Darkbloom + # check out to different paths. A job that builds or runs the test + # products works at one fixed path: its workspace becomes a link to it, + # so every step's working directory resolves there + # (scripts/ci-test-products.py). Its caches outside the workspace live + # in /private/tmp/dinf-ci: actions/cache unpacks each path relative to + # the workspace, which a runner.temp or home path cannot survive here. + - name: Work at the fixed build path + run: | + cd / + rm -rf /private/tmp/dinf /private/tmp/dinf-ci "$GITHUB_WORKSPACE" + mkdir -p /private/tmp/dinf /private/tmp/dinf-ci + ln -s /private/tmp/dinf "$GITHUB_WORKSPACE" + - 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: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - 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 }} + # Only a run that tests the lane hands its products on; a push of a + # tested tree only refreshes the caches. + - name: Upload cluster test products + if: ${{ inputs.cluster == 'true' }} + uses: ./.github/actions/provider-ci-products + with: + lane: cluster + direction: upload + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 + + build-provider: + name: Build provider test products + if: ${{ inputs.provider == 'true' || (github.event_name == 'push' && inputs.skip == 'true' && inputs.changed_provider == 'true') }} + runs-on: ${{ fromJSON(inputs.routes)['build-provider'] }} + timeout-minutes: 60 + steps: + # The fixed build path, as in build-cluster (scripts/ci-test-products.py). + - name: Work at the fixed build path + run: | + cd / + rm -rf /private/tmp/dinf /private/tmp/dinf-ci "$GITHUB_WORKSPACE" + mkdir -p /private/tmp/dinf /private/tmp/dinf-ci + ln -s /private/tmp/dinf "$GITHUB_WORKSPACE" + - 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: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Build provider test products + id: provider-ci-build + uses: ./.github/actions/provider-ci-build + with: + lane: provider + save-caches: ${{ env.SAVE_CACHES }} + strict-cache: ${{ inputs.strict_cache }} + # Only a run that tests the lane hands its products on; a push of a + # tested tree only refreshes the caches. + - name: Upload provider test products + if: ${{ inputs.provider == 'true' }} + uses: ./.github/actions/provider-ci-products + with: + lane: provider + direction: upload + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 + 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 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. + # test-provider- lane. Each shard runs the products of Build + # provider test products and 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: build-provider if: ${{ inputs.provider == 'true' }} runs-on: ${{ fromJSON(inputs.routes)[format('test-provider-{0}', matrix.shard)] }} timeout-minutes: 60 @@ -66,6 +241,13 @@ jobs: matrix: shard: [1, 2] steps: + # The fixed build path, as in build-cluster (scripts/ci-test-products.py). + - name: Work at the fixed build path + run: | + cd / + rm -rf /private/tmp/dinf /private/tmp/dinf-ci "$GITHUB_WORKSPACE" + mkdir -p /private/tmp/dinf /private/tmp/dinf-ci + ln -s /private/tmp/dinf "$GITHUB_WORKSPACE" - name: Select today's .git cache id: git-day run: | @@ -101,13 +283,14 @@ jobs: 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 + - name: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Download provider test products + id: test-products + uses: ./.github/actions/provider-ci-products with: lane: provider - save-caches: ${{ env.SAVE_CACHES }} - strict-cache: ${{ inputs.strict_cache }} + direction: download # 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. @@ -130,33 +313,33 @@ jobs: # 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' }} + if: ${{ !cancelled() && steps.test-products.outcome == 'success' }} uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: - path: ${{ runner.temp }}/mimo-metadata-cache + path: /private/tmp/dinf-ci/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' }} + if: ${{ !cancelled() && steps.test-products.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" --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" + python3 scripts/prepare-mimo-prompt-fixtures.py --output "$RUNNER_TEMP/mimo-prompt-fixtures" --github-env "$GITHUB_ENV" --cache /private/tmp/dinf-ci/mimo-metadata-cache + python3 scripts/prepare-mimo-image-http-fixtures.py --output "$RUNNER_TEMP/mimo-image-http-fixtures" --github-env "$GITHUB_ENV" --cache /private/tmp/dinf-ci/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 + path: /private/tmp/dinf-ci/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' }} + if: ${{ !cancelled() && steps.test-products.outcome == 'success' }} run: | python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-provider-fixtures" --github-env "$GITHUB_ENV" python3 scripts/prepare-mimo-provider-fixtures.py --output "$RUNNER_TEMP/mimo-prefix-fixtures" --asymmetric - name: Run Swift tests id: provider-unit-tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && steps.test-products.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} timeout-minutes: 35 env: MIMO_V26_PROVIDER_LIFETIME_METADATA_TESTS: '1' @@ -185,12 +368,12 @@ jobs: if-no-files-found: warn retention-days: 7 # Prompt Parity runs once, in shard 1 (the shard of selection - # PARITY_SHARD), against this shard's build. A failure fails the shard, + # PARITY_SHARD), against the provider products. 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 == 1 && steps.provider-ci-build.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 1 && steps.test-products.outcome == 'success' && steps.mimo-prompt-fixtures.outcome == 'success' }} env: PROMPT_PARITY_SKIP_BUILD: '1' run: | @@ -201,7 +384,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 == 1 && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 1 && steps.test-products.outcome == 'success' }} run: | set -o pipefail report="$RUNNER_TEMP/provider-unit-shard" @@ -210,32 +393,32 @@ jobs: python3 scripts/provider-test-shards.py counts parity NemotronTemplateParityLiveTests \ "$report/parity-nemotron.log" "$report/shard-parity-nemotron.json" - name: Test desktop control API with isolated local state - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' }} timeout-minutes: 3 run: python3 scripts/test-desktop-api.py provider-swift/.build/debug/darkbloom - name: Run isolated native MiMo startup gates - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: MIMO_V26_SERIAL_NATIVE_TESTS: '1' run: ../scripts/run-nested-suite.sh 'MiMoV26StandaloneLifecycleTests.test(ActualScannerPreloadStartsListenerWithSameNativeOwner|StartRefusesActualUnpublishedPreloadWithoutReplacingOwner)' --no-parallel - name: Run isolated native MiMo memory admission gates - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: MIMO_V26_SERIAL_NATIVE_TESTS: '1' run: ../scripts/run-nested-suite.sh 'testNativeMemoryAdmission|testNativeShutdownActivitySurvivesPendingHostUntilRealQuiescentDrain' --no-parallel - name: Run isolated native MiMo media admission gates - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: MIMO_V26_SERIAL_NATIVE_TESTS: '1' run: ../scripts/run-nested-suite.sh 'testNativeMediaRelease|testAuthenticatedChatResponsesActuallyRouteEncodedImageThroughNativeBridge|testActualMemoryBackedVideoIndicesAndAuthenticatedNativeRoute|testNativeIdleBootstrapLearnsRealTargetRateAndKeepsTextRateIsolated|testNativePreparedSealReachesRealAtomicDeadlineRejectionWithoutLosingCharge|testTypedDeadlineGatePreservesRawTextAndOffPolicyAndRefusesForeignCapability|MiMoMediaDecodeMemoryTests' --no-parallel - name: Run isolated native MiMo complete-prefix gates - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: @@ -243,7 +426,7 @@ jobs: MIMO_V26_SERIAL_LOAD_FIXTURES: ${{ runner.temp }}/mimo-prefix-fixtures run: ../scripts/run-nested-suite.sh 'MiMoV26NativeLoadTransactionTests.testNativeCompletePrefix' --no-parallel - name: Run isolated native MiMo retained-fault gate - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: @@ -254,7 +437,7 @@ jobs: DARKBLOOM_PREFIX_CACHE_MEMORY: '0' run: ../scripts/run-nested-suite.sh testNativeFenceRefusalKeepsActualBundlePermitAndBlocksOtherOwnerReclaim --no-parallel - name: Run isolated native MiMo lifecycle drain gate - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: @@ -266,24 +449,24 @@ jobs: # 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' && inputs.mimo_audio == 'true' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && inputs.mimo_audio == 'true' }} uses: actions/cache/restore@1bd1e32a3bdc45362d1e726936510720a7c30a57 id: mimo-audio-cache with: - path: ${{ runner.temp }}/mimo-audio-source + path: /private/tmp/dinf-ci/mimo-audio-source 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' && 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" + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && inputs.mimo_audio == 'true' }} + run: python3 scripts/prepare-mimo-audio-fixtures.py --cache /private/tmp/dinf-ci/mimo-audio-source --output "$RUNNER_TEMP/mimo-audio-fixtures" --github-env "$GITHUB_ENV" - name: Cache verified MiMo audio codec 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 + path: /private/tmp/dinf-ci/mimo-audio-source key: mimo-audio-source-v2-077033345d80eef3a315e8d394e0589667e80e4cdaba9bc5a7488410c6657265 - name: Run isolated native MiMo audio gate - if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.provider-ci-build.outcome == 'success' && steps.mimo-audio-fixtures.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == strategy.job-total && steps.test-products.outcome == 'success' && steps.mimo-audio-fixtures.outcome == 'success' }} working-directory: provider-swift timeout-minutes: 5 env: @@ -445,22 +628,44 @@ jobs: ${{ runner.temp }}/provider-unit-shard/provider.profdata if-no-files-found: error retention-days: 14 + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 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. + # the base selection alone, then the share probe; shard 2 runs its + # ordered groups of selections at the same time; shard 3 runs the Gemma 4 + # base suites alone. name: Cluster Runtime Tests (shard ${{ matrix.shard }}) + needs: build-cluster 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] + shard: [1, 2, 3] steps: + # The fixed build path, as in build-cluster (scripts/ci-test-products.py). + - name: Work at the fixed build path + run: | + cd / + rm -rf /private/tmp/dinf /private/tmp/dinf-ci "$GITHUB_WORKSPACE" + mkdir -p /private/tmp/dinf /private/tmp/dinf-ci + ln -s /private/tmp/dinf "$GITHUB_WORKSPACE" - name: Select today's .git cache id: git-day run: | @@ -496,34 +701,58 @@ jobs: 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 + - name: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Download cluster test products + id: test-products + uses: ./.github/actions/provider-ci-products with: lane: cluster - save-caches: ${{ env.SAVE_CACHES }} - strict-cache: ${{ inputs.strict_cache }} + direction: download - name: Run cluster runtime tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && steps.test-products.outcome == 'success' }} timeout-minutes: 40 env: SHARD: ${{ matrix.shard }} run: python3 scripts/cluster-test-plan.py run blocking "$SHARD" + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 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. + # workflow. Shard 2 uses 42 GiB, more than any signed Darkbloom size, so + # both shards run on Blacksmith without asking the route + # (provider-plan.yml). name: Cluster GPU Tests (non-blocking, shard ${{ matrix.shard }}) + needs: build-cluster if: ${{ inputs.cluster == 'true' }} - runs-on: ${{ fromJSON(inputs.routes)[format('test-cluster-gpu-{0}', matrix.shard)] }} + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 strategy: fail-fast: false matrix: shard: [1, 2] steps: + # The fixed build path, as in build-cluster (scripts/ci-test-products.py). + - name: Work at the fixed build path + run: | + cd / + rm -rf /private/tmp/dinf /private/tmp/dinf-ci "$GITHUB_WORKSPACE" + mkdir -p /private/tmp/dinf /private/tmp/dinf-ci + ln -s /private/tmp/dinf "$GITHUB_WORKSPACE" - name: Select today's .git cache id: git-day run: | @@ -559,31 +788,48 @@ jobs: 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 + - name: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Download cluster test products + id: test-products + uses: ./.github/actions/provider-ci-products with: lane: cluster - save-caches: ${{ env.SAVE_CACHES }} - strict-cache: ${{ inputs.strict_cache }} + direction: download - name: Run non-blocking cluster GPU tests - if: ${{ !cancelled() && steps.provider-ci-build.outcome == 'success' }} + if: ${{ !cancelled() && steps.test-products.outcome == 'success' }} continue-on-error: true timeout-minutes: 40 env: SHARD: ${{ matrix.shard }} run: python3 scripts/cluster-test-plan.py run nonblocking "$SHARD" + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 - 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 + cluster-release-checks: + # The worker capability and prefill schedule checks compile a release + # build of the cluster runtime and MLX (each runner its own source + # closure; no GPU, no model load, no weights), so they run in a job of + # their own: no test job waits for them. The build is 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). Its lane asks only with its size, + # while job sizes are on, as the build jobs' lanes do; otherwise it runs + # on Blacksmith (provider-plan.yml). + name: Cluster Release Build Checks if: ${{ inputs.cluster == 'true' }} - runs-on: ${{ fromJSON(inputs.routes)['test-cluster-focused'] }} + runs-on: ${{ fromJSON(inputs.routes)['cluster-release-checks'] }} timeout-minutes: 60 steps: - name: Select today's .git cache @@ -621,18 +867,17 @@ jobs: with: path: .git key: ${{ steps.git-cache.outputs.cache-primary-key }} + - name: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" - 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 - # The capability runner's release build of the cluster runtime and MLX is - # 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; - # it drops `git describe` text, which depends on the refs a cached .git holds. + # The key binds the toolchain, the 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' }} @@ -689,33 +934,123 @@ jobs: with: path: ${{ runner.temp }}/cluster-native-metadata key: ${{ steps.cluster-build-key.outputs.key }} + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 + + test-cluster-focused: + # The model-free cluster check runners on two Macs; each compiles its own + # source closure and runs on retained fixtures (no GPU, no model load, no + # weights; every runner runs even after another fails). Shard 1 runs the + # runner scripts under libs/darkbloom-cluster/Tests + # (scripts/cluster-test-plan.py focused lane); shard 2 runs the stage + # metadata, provisioning and onboarding runners. They need no test + # products. Both shards read the one lane test-cluster-focused, which the + # route requests for 2 jobs (provider-plan.yml). + name: Cluster Focused Checks (shard ${{ matrix.shard }}) + if: ${{ inputs.cluster == 'true' }} + runs-on: ${{ fromJSON(inputs.routes)['test-cluster-focused'] }} + 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: Start the resource sampler + run: python3 scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - 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 stage metadata checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 2 && steps.toolchain.outcome == 'success' }} run: python3 libs/darkbloom-cluster/Tests/StageMetadataChecks/run.py --output "$RUNNER_TEMP/stage-metadata-checks" - name: Run GPT-OSS stage checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 2 && steps.toolchain.outcome == 'success' }} run: bash libs/darkbloom-cluster/Tests/GPTOSSStageChecks/run.sh - name: Run Nemotron stage checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 2 && steps.toolchain.outcome == 'success' }} run: bash libs/darkbloom-cluster/Tests/NemotronStageChecks/run.sh # The download cache-policy check of the same runner stays on a Mac: on the # hosted VM, 0.75 of the pages written with F_NOCACHE stayed resident # (run 40804083002), which the VM's kernel and disk decide, not the code. - name: Run cluster model provisioning checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 2 && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning - name: Run cluster onboarding checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 2 && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh - name: Run cluster focused checks - if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + if: ${{ !cancelled() && matrix.shard == 1 && steps.toolchain.outcome == 'success' }} timeout-minutes: 40 run: python3 scripts/cluster-test-plan.py run focused 1 + # Report-only (scripts/ci-resource-sampler.py): it never fails the job. + - name: Report the resource samples + if: ${{ always() }} + run: python3 scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + - name: Upload the resource samples + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: resource-samples-${{ github.job }}-${{ strategy.job-index }} + path: ${{ runner.temp }}/resource-samples + if-no-files-found: ignore + retention-days: 14 provider-test-gate: name: Provider Tests runs-on: ubuntu-24.04 - needs: [test-provider, test-cluster, test-cluster-focused] + # The test jobs need their build jobs: a failed build skips its test jobs, + # and a skipped test job that should have run fails this gate. + needs: [test-provider, test-cluster, test-cluster-focused, cluster-release-checks] if: ${{ always() }} permissions: contents: read @@ -730,6 +1065,7 @@ jobs: UNIT_RESULT: ${{ needs.test-provider.result }} CLUSTER_RESULT: ${{ needs.test-cluster.result }} CLUSTER_FOCUSED_RESULT: ${{ needs.test-cluster-focused.result }} + CLUSTER_RELEASE_RESULT: ${{ needs.cluster-release-checks.result }} run: | test "$CHANGES_RESULT" = success # A tree that a successful run of this workflow already tested runs @@ -752,11 +1088,13 @@ jobs: esac test "$CLUSTER_RESULT" = "$cluster_expected" test "$CLUSTER_FOCUSED_RESULT" = "$cluster_expected" + test "$CLUSTER_RELEASE_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. + # lookup, the route, the workflow pins, the test products hand-off and + # the resource sampler. Python only; no build. They run even when a test + # job failed. - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 if: ${{ !cancelled() }} with: @@ -774,6 +1112,8 @@ jobs: python3 scripts/test-ci-tested-tree.py python3 scripts/test-darkbloom-route.py python3 scripts/test-provider-ci-workflow.py + python3 scripts/test-ci-test-products.py + python3 scripts/test-ci-resource-sampler.py # dev has no Release Integrity, so the gate runs the Date comparison # check too. SDK 27.2 back-deploys Date's >= and <=; pre-release macOS # 27.2 builds lack the symbols. The release build also checks the built @@ -784,6 +1124,13 @@ jobs: python3 scripts/test-check-date-comparisons.py python3 scripts/test-check-provider-weak-imports.py python3 scripts/check-date-comparisons.py + # The prompt fixture downloaders' retry rule, offline: no Mac, no network. + # Master also runs the first in its provider script checks. + - name: Test the prompt fixture downloaders offline + if: ${{ !cancelled() }} + run: | + python3 scripts/test-prepare-prompt-fixtures.py + python3 scripts/test-prepare-mimo-prompt-fixtures.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 @@ -809,62 +1156,3 @@ jobs: 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.d/chunked-read-memory.md b/changelog.d/chunked-read-memory.md new file mode 100644 index 0000000000..895230478c --- /dev/null +++ b/changelog.d/chunked-read-memory.md @@ -0,0 +1,6 @@ +### Chunked file reads release each chunk + +- Before, a file read in chunks kept every chunk in memory until the thread that read it went idle. On macOS each chunk read returns an autoreleased buffer, and a Swift task or a Dispatch block does not release these buffers between chunks. Thus memory grew with the size of the file. +- Now each chunk read releases its buffer before the next read. This applies to the model manifest hash in `darkbloom-publish`, the speculative-decoding store's artifact hash, the binary and file hashes, the metallib snapshot copy, the streamed SSD KV cache read, the cluster worker hash, the MTP benchmark weight hash and the App Attest worker's executable hash. It also applies to the output readers of desktop commands and sandbox commands. +- The output readers of desktop commands and sandbox commands keep only the last 32 KiB of output. Before, the buffer that held these 32 KiB also kept all the earlier output. The stderr tail that the provider keeps for a failed helper process had the same problem, and it is fixed the same way. Its stderr reads also release each buffer. +- The digests and the copied bytes do not change. diff --git a/changelog.d/ci-build-once.md b/changelog.d/ci-build-once.md new file mode 100644 index 0000000000..674e4a2080 --- /dev/null +++ b/changelog.d/ci-build-once.md @@ -0,0 +1,10 @@ +### Provider CI: build once, test on small Macs + +- Each lane builds its debug test products once, on a 12 vCPU Blacksmith Mac: Build cluster test products and Build provider test products. The test jobs download the products and run them with `swift test --skip-build`; they compile no package. A test job refuses products of another commit or of another Swift, Xcode or SDK version, and warns when only their builds differ. +- The jobs that build or run the products work at one fixed path, `/private/tmp/dinf`, because SwiftPM's products hold absolute paths and Blacksmith and Darkbloom check out to different paths. +- The cluster tests start as soon as the cluster products are up. The worker capability and prefill schedule checks, which compile a release build, run in Cluster Release Build Checks on a 12 vCPU Blacksmith Mac. The `Provider Tests` gate requires it. +- Refresh build caches is gone: a push whose tree a pull request run already tested runs the build jobs of the components it changed, without an upload. +- Cluster Runtime Tests runs in 3 shards: the Gemma 4 base suites (592 of the base tests' 970 s) run in their own process on shard 3. Cluster Focused Checks runs in 2 shards: the runner scripts, and the stage metadata, provisioning and onboarding runners. +- The provider shard weights are measured again, so the last selection no longer runs every suite the old weights missed. The last shard's audit warns when a serial suite has no weight. +- Only the 7 blocking test shards ask Darkbloom for a Mac; the build jobs, Cluster Release Build Checks and Cluster GPU Tests use Blacksmith directly. +- Every macOS job samples its memory and CPU use and prints the peaks; the samples upload as `resource-samples-*`. The sampler never fails a job. The products hand-off prints the archive size and the upload and download times. diff --git a/changelog.d/ci-macos-job-sizes.md b/changelog.d/ci-macos-job-sizes.md new file mode 100644 index 0000000000..8ae11ed978 --- /dev/null +++ b/changelog.d/ci-macos-job-sizes.md @@ -0,0 +1,9 @@ +### Provider CI: per-job macOS sizes for Darkbloom Sandboxes + +- Each macOS CI lane can ask the Darkbloom plane for a size, `x`. The route job checks each size against this grammar and fails on a bad value before it sends a request. +- Sizes are sent only when the repository variable `DARKBLOOM_JOB_SHAPES` is exactly `on`. While it is off, the route request is byte for byte the request without sizes, and every job keeps the runner it has today. +- Each size comes from the job's sampled memory: the smallest signed size that holds 1.25 times its used memory (app + wired + compressed) without making the job more than 5% slower. While sizes are on, the 7 blocking test jobs ask for 4x16 (provider shard 1, cluster runtime shard 1, both Cluster Focused Checks shards), 4x24 (provider shard 2, cluster runtime shard 3) or 12x32 (cluster runtime shard 2, 29.3 GiB). Build cluster test products and Cluster Release Build Checks ask for 8x16 and Build provider test products for 12x32, on the `required` lanes `build-cluster`, `build-provider` and `cluster-release-checks`. A run that tests every component then asks for 10 macOS jobs. While sizes are off, the `required` jobs use `blacksmith-12vcpu-macos-27` without asking. +- The 2 Cluster GPU Tests shards are not routed. Shard 2 uses 42 GiB, which no signed size holds, so both shards run on `blacksmith-12vcpu-macos-27`. +- A sized lane uses a grant only when its labels end in the qualified label, such as `darkbloom-macos-arm64-4x24`. Otherwise it keeps `blacksmith-12vcpu-macos-27`. +- For each lane, the route job's log and summary show the size asked, the runner, and the decision with its reason, such as `shape_not_signed`, `unavailable`, `unsupported_runner_class`, `image_not_available` or `lane_not_enabled`. +- The `DARKBLOOM_MACOS_LANES` cap still keeps the critical-path test lanes first. The `required` lanes come after them. diff --git a/changelog.d/ci-true-memory.md b/changelog.d/ci-true-memory.md new file mode 100644 index 0000000000..3a926f12df --- /dev/null +++ b/changelog.d/ci-true-memory.md @@ -0,0 +1,4 @@ +### Provider updates hash bundles in bounded memory; CI samples memory by class + +- An install, a verify or a rollback of the provider no longer keeps every byte it hashes in memory. Each 1 MiB read of the bundle hash and the file hash now releases its buffer before the next read. Before, a rollback test of the debug CLI held 15 GiB until its test process ended. The hashes are unchanged. +- The CI resource sampler now records memory by class: app (with Metal buffers), wired, file cache, compressed and swap. It also records the physical footprint of each process, which includes Metal memory, the test selection each large process runs, and busy vCPUs from the host's CPU ticks. Each job's report and `summary.json` show the peaks, the three largest processes and the time the job would take on 4 and 8 vCPUs. The sampler stays report-only. diff --git a/changelog.d/cluster-stream-failure-frame-before-retirement.md b/changelog.d/cluster-stream-failure-frame-before-retirement.md new file mode 100644 index 0000000000..fa3e9dc90e --- /dev/null +++ b/changelog.d/cluster-stream-failure-frame-before-retirement.md @@ -0,0 +1,3 @@ +### A two-Mac pair's local API no longer cuts a failed stream short + +- When the provider rejects a streamed chat completion's output mid-generation on a pair (for example a named or required `tool_choice` the model answers with text, or a streamed tool call that fails validation), the leader's local API now ends the stream with the same error chunk (`finish_reason: "error"`) as one Mac. Before, the client could get HTTP 200 and the chunks already sent, then the connection closed with no error chunk. Some clients took that cut-short stream for a complete answer. diff --git a/changelog.d/gemma-tensor-parallel-builds-greedy-steps-ahead.md b/changelog.d/gemma-tensor-parallel-builds-greedy-steps-ahead.md new file mode 100644 index 0000000000..2b5e5588b5 --- /dev/null +++ b/changelog.d/gemma-tensor-parallel-builds-greedy-steps-ahead.md @@ -0,0 +1,3 @@ +### Gemma tensor parallel prepares the next token while reading the last + +- For requests without sampling (temperature 0, no logprobs, no logit bias or penalties), a Gemma 4 pair now starts the next token's work on the GPU before it reads the token it just made, as GLM's pair already does. On GLM this took a token from 13.4 to 12.0 ms on two M5 Ultras; Gemma's gain has not been measured yet. The output is unchanged. diff --git a/changelog.d/gemma-tensor-parallel-builds-sampled-steps-ahead.md b/changelog.d/gemma-tensor-parallel-builds-sampled-steps-ahead.md new file mode 100644 index 0000000000..397bf8ce04 --- /dev/null +++ b/changelog.d/gemma-tensor-parallel-builds-sampled-steps-ahead.md @@ -0,0 +1,3 @@ +### Gemma tensor parallel prepares the next token ahead for sampled requests too + +- Requests that sample (temperature above 0, with or without logprobs), and greedy requests with logit bias or penalties, now also start the next token's work on the GPU before the last token is read. Each token is still the exact draw for its position and seed, so the output is unchanged (except that a request that already fails because one Mac stopped on its own may stream one extra token first, as on GLM). Greedy requests that ask for logprobs keep the old order. diff --git a/changelog.d/metal-cpp-from-the-sandbox-image.md b/changelog.d/metal-cpp-from-the-sandbox-image.md new file mode 100644 index 0000000000..a0593b690d --- /dev/null +++ b/changelog.d/metal-cpp-from-the-sandbox-image.md @@ -0,0 +1,4 @@ +### metal-cpp from the Darkbloom sandbox image + +- `scripts/fetch-metallib.sh` uses the metal-cpp archive that Darkbloom's macOS sandbox images carry, when it is the archive the nested MLX core names and its SHA-256 matches the pin. The metallib build then makes no download from developer.apple.com, where downloads through the sandbox's egress ended early (`transfer closed with … bytes remaining`). Elsewhere, MLX's configure downloads the archive as before. +- Changing the script changes the metallib cache key once: the first CI runs after this change rebuild the metallib. diff --git a/changelog.d/qwen27-public-assistant.md b/changelog.d/qwen27-public-assistant.md new file mode 100644 index 0000000000..8fa9c7346e --- /dev/null +++ b/changelog.d/qwen27-public-assistant.md @@ -0,0 +1,22 @@ +### Qwen3.8-27B pairs decode with their speculative assistant through Darkbloom + +- Two-Mac pairs that serve Qwen3.8-27B in tensor parallel through Darkbloom + now decode with the model's speculative assistant (depth 3), as local + clusters and single Macs already do. The guided setup plans it under the + default `mtp_mode = "auto"`. `mtp_mode = "off"` still plans the pair + without it. If the assistant cannot be planned, the pair is planned plain, + as before, and the setup screen and `darkbloom cluster status` say why in + one line. +- On one pair, the same requests decoded with the assistant and without it + gave identical greedy, sampled and tool answers. Requests that ask for + logprobs, use penalties or a logit bias, or carry images decode one token a + step, as before. The evidence is in + `docs/reports/2026-11-05-qwen27-public-assistant.md`. +- The release's cluster runtime facts name the assistant: the model's + serial-prefill tensor-parallel qualification rests on that report, and its + resource policy digest carries the build's declared assistant settings. A pair whose Macs run another + assistant is refused before any part stops. +- Speed records from served requests now say whether the request came through + Darkbloom or the local API and whether the assistant decoded it. A plan uses + only the records served the way it will serve, so a local pair's assisted + speed no longer stands for the same pair through Darkbloom. diff --git a/changelog.d/tensor-parallel-decode-submits-every-eight-layers.md b/changelog.d/tensor-parallel-decode-submits-every-eight-layers.md new file mode 100644 index 0000000000..ebcba44185 --- /dev/null +++ b/changelog.d/tensor-parallel-decode-submits-every-eight-layers.md @@ -0,0 +1,3 @@ +### Qwen tensor-parallel decode wastes less time per token + +- A Qwen pair now hands each token's work to the GPU every eight layers instead of after every layer, so the GPU spends less time waking up and waiting. On two M5 Ultras a token took about 15 % less time for one request and about 13 % less for four at once. The output is unchanged. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 23edeb35d3..6fb064179d 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -3326,6 +3326,9 @@ blocks and is not checked. Its restart line reads FileVault with `fdesetup isactive` (`OnboardingLive.fileVaultOn`): five seconds, then SIGTERM and two more, and no answer reads as unknown. The exit comes from `ProcessExitObserver`, which does not run the calling thread's run loop. +A Mac hashes its worker again only when the worker's size, modification time +or inode moved (`LiveContext.workerSHA256`), in 4 MiB reads that each release +their buffer before the next. After a Darkbloom update changes a Mac's worker digest, the control leader's cluster service re-plans and re-adopts the same model by itself (`ClusterService.checkForUpdate`, `ClusterOnboardingUpdate`), once both Macs @@ -4589,6 +4592,23 @@ earlier build kept read the same way; the request mix's 64-token floor on the answer (`ClusterRequestMix.minimumOutputTokens`) stays for samples a plan is given directly. +Each record also names how the request reached the pair (`serving`: +`ClusterServedScope.darkbloom` for a setup saved for coordinator pairing, +`local` for the leader's own API; `DistributedSessionFacts.serving`) and +whether the setup decoded with Qwen's resident tensor assistant +(`tensorAssistant`), and the leader keeps each combination's 32 newest apart. +A plan, the setup screen's served figures (`ClusterSetupPlanning.modes`) and the +router use only the records served the way they will serve +(`ClusterServedSpeedRecords.Setup.servedAs`): the same scope, and in tensor +parallel the assistant exactly when the plan has one. The served race reads +each mode at its fastest setup (`ClusterServedModes.figures`), so without the +split a local pair's assisted figure (pair-2's Qwen: 34–36 tok/s) stood for +tensor parallel through Darkbloom without it (14–20). Served calibration skips +assisted setups: its device rates are one-token rates, and nothing there knows +the assistant's speed-up (`ClusterServedCalibration.measurements`). A record +from before these fields existed reads as before; it is an earlier build's, +which the build rule below already leaves out. + Every plan of the pair (`ClusterPlacementFlow.decide`: the plan command, the setup screen with the other Mac's shared records, and automatic batch replacement) and the leader's per-request router (`ClusterRequestRoutingBasis`) @@ -4785,7 +4805,10 @@ Oracles run on synthetic checkpoints with the 26B's structure scaled down: prefill width rounds some rows unlike its 512-row half. `tp-check gemma run --path paged` runs `full`, `simulated` and `tp` through the -resident runtime's own request path instead of the SDK's legacy caches. +resident runtime's own request path instead of the SDK's legacy caches; +`--layer-stride N` submits each decode step every N layers instead of the +product's `decodeLayerStride` (1), so a pair can measure the stride before the +product's changes (Qwen's measured choice is 8, `QwenTensorParallelLaunch`). `tp-check gemma lanes` serves several requests together through the batch driver and checks each against itself alone. @@ -4843,6 +4866,32 @@ stops, cancellations and retirements. that could not grow) ends both after the same step (`Gemma4TensorParallelRequestLoop`). A rank that stopped commits nothing more, but still ends at a stop token its peer commits. + A greedy request's steps are built one ahead, in GLM tensor parallel's step + order (`TensorParallelOneTokenLoop`): step k+1 is built on step k's lazy + agreed token and submitted (`Gemma4TensorParallelPagedSession.submitDecode`, + `CBv2OwnedRequestState.submit`, which commits the step on host-held + frontiers and leaves native errors to the evaluation that reads it) before + the host reads step k, answers the owner and commits, so the GPU and the + collectives run while the host works. On two M5 Ultras GLM's pipelined step + took 12.0 ms against 13.4 ms read-then-build; Gemma's pair has not been + measured. The tokens are the read-then-build path's, with one exception, as + in GLM's loop: a rank's own stop (cancel, deadline, memory) and a refused page + growth ride one step later. So when rank 1 stops on its own or its pages run + out, rank 0 may stream one token that the final count drops (the request then + errors on both ranks: rank 0 refuses the peer's stop, and the worker session + refuses a length finish short of the output count). And a refused growth, which + still keeps the margin's rows, ends the request one token later than before. + Never a token past a stop token, a length end or the owner's stop. Sampled + requests, and greedy ones with logit bias or penalties (they draw through the + sampler), are built ahead too: rank 0's draw is + `QwenStageTokenSampler.sample`, the product's `CBv2DefaultSampler`, which + advances its penalty counts with each drawn token on the device and its keyed + step index with each draw, so a draw built before the previous token is read + is still the draw at its output index with the history up to it; each step + keeps its own lazy logprob gather (`takePendingStepLogprobs`). Greedy + requests asking for logprobs read each step first: their vocabulary-split + top-k gather is a collective evaluated on the host after the token is + agreed, which would wait for the step built ahead. - Prompt prefixes. Each rank keeps its own heads' state at a prompt's chunk boundaries as the Gemma pipeline keeps a stage's, in the pipeline's memory tier and the owner's encrypted SSD tier (`Gemma4TensorParallelPrefix`). A @@ -6676,10 +6725,17 @@ equals that row's alone; the agreement binds `moe-rows-one-collective-v1`. Mixed text/media rows retain their own original fused RoPE or MRoPE calculation. A decode step is submitted while it is built. `QwenTensorParallelBatchSession` -decodes under `Qwen35LayerSubmission` with a stride of one layer -(`decodeLayerStride`): after each decoder layer the forward submits what it has -built (`asyncEval`), so that layer's kernels and collectives run while the host -builds the next. The driver builds a step only after the previous step's tokens +decodes under `Qwen35LayerSubmission` with a stride of eight layers +(`QwenTensorParallelLaunch.decodeLayerStride`): after every eighth decoder layer +the forward submits what it has built (`asyncEval`), so those layers' kernels and +collectives run while the host builds the next eight. One layer a submission +paid a commit and a GPU wake-up per layer: on two M5 Ultra 256 GB over JACCL +(27B, sealed sums, synthetic 64-token prompt, 128-256 output tokens) a width-one +step took 21.4 ms at stride 1 and 20.2-20.3 ms at 8 to 16 (25.1 against 19.9-20.4 +ms with the host loaded by other builds), a width-four step 35.4 against +29.5-29.9 ms, and stride 32 was slower again (21.2 ms). Every stride retired the +same tokens on both ranks. The stride is not a launch option: it changes only +when work reaches the GPU. The driver builds a step only after the previous step's tokens are read (a plain step's plan is made before them, below), so the request-owned path does not build one step ahead as the retired single-lane loop did; submitting by layer hides the graph build instead. @@ -6802,9 +6858,43 @@ earlier build refuses to load. Tokens, logits and native state are unchanged: the control limbs are exact in FP32, each element of the sum is added alone, and the collective payload quote covers the longer frame (`QwenTensorParallelBatchBudget`). `darkbloom-cluster-tp-check qwen-decode` -(`QwenTensorParallelDecodeBench`) times the driver's decode on two ranks over -the loopback ring with the control exchanged or folded and checks that both -retire the same tokens. +(`QwenTensorParallelDecodeBench`) times the driver's decode on two ranks, over +the loopback ring or socket or, with `--backend jaccl`, over a pair's JACCL +link, with the control exchanged or folded, and checks that both retire the +same tokens; `--layer-strides 1,8,16` compares decode layer strides in one run. + +**Build-ahead (driver protocol; not yet on in the product).** With +`QwenTensorParallelBatchSettings.buildsAhead` (load agreement field +`qwen-tp-batch-build-ahead-v1`), the driver builds a plain decode step before +it reads the step before it (`QwenTensorParallelBatchDriver.serveAhead`), so +the GPU and the collectives run while the host reads, publishes and answers. +The window-1 profile measured about 1.9 ms of GPU idle at each token boundary. +- Every folded step's selection sum also carries two decision words, one per + rank, for the step two later. Continuations need no plan: both ranks build + that step on the unread step's selection rows (`QwenTensorParallelBatchExecutor.submitDecode` + and `readDecode`) only when neither rank asked for a barrier and the unread + step decoded the same lanes the decision covered. +- A rank asks for a barrier whenever anything needs a plan: an owner's stop or + the answer to a request's last token, a request waiting to join, an idle lane, + a cancellation or deadline, an ended lane, a lane that would pass its output + count, or more than four tokens held unpublished. At a barrier both ranks read + every submitted step, and the next plan is made and exchanged with nothing in + flight, exactly as without build-ahead. +- Owner answers that a decision reads and that need a plan are kept for that + plan, and their lane publishes nothing more meanwhile. Tokens selected before + their credit are held, one queue a row (`heldLogprobs`), and published in order, + one per "go on" answer. A client stop drops all held tokens. An EOS read after + the next step was built discards that one forward on both ranks (the + generation schedule accepts one declared discarded forward after an EOS). No + step is built past a request's output count. + +Every input to a decision and to the build is agreed state (read sums, read +tokens, plans), so both ranks submit the same collectives in the same order. +Ranks on different protocols refuse each other at load (the field). The driver +is checked on two ranks with a fake executor (`QwenTensorParallelBatchDriverTests`: +steady decode, EOS, owner stops, late credits, joins, prompts, cancellation, and +ranks that disagree failing closed). The native executor does not submit decode +steps yet (`buildsAhead` false), so the product runs read-then-build until it does. The batch path can restore mutually held original-grid prefix snapshots into fresh request-owned state. TP speculative rounds remain a separate integration. Installed owners propagate a priced @@ -7228,7 +7318,12 @@ types them ([fields](../reference/configuration.md#cluster-runtime-facts), native start of an owner-formed session calls it for its `resourcePolicySHA256`. A coordinator-formed start carries the approval's value, which the member and its owner compare with the installed approval - (`NativePairMemberPolicy.require`). + (`NativePairMemberPolicy.require`). A resident assistant the build declares + public for the model's artifact (`ClusterPublicModels.tensorAssistant`) adds + its launch arguments and evidence digest to the formula, so the approval and + every start under it name the declared assistant + ([Qwen27 resident assistant](#qwen27-tensor-parallel-resident-assistant)); + without one the digest is the five-field formula as before. 4. Every model carries a pair-serving grant when the build qualifies it. A pair member reports only hardware capabilities (`DistributedServingEligibility.memberCapabilities`: `apple_m5` on an M5, @@ -7349,9 +7444,17 @@ does not establish an installed distributed-model pass. The Qwen3.5 9B's artifact ships the same dense one-layer inline head, so its tensor owner runs the same resident assistant (`QwenTensorParallelMTPPolicy.models`, `ClusterQwenTensorAssistantPolicy.runtimeModelIDs`): `QwenTensorParallelMTPInventory.Head` derives every expected head tensor from the row's configuration and `QwenTensorParallelMTPBudget` prices the row's own widths (the 27B's inventory fingerprint and quotes are unchanged). The 9B's READY carries the assistant without the 27B's media contract. The routed-expert rows' heads are expert layers this assistant does not load; those rows serve their request-owned lanes without speculation, and planning never asks them for an assistant. -For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote. The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. +For the exact registered Qwen3.8 27B artifact, normal cluster planning discovers the embedded assistant from the catalog manifest, capability identity and bounded inline header inspection. With `backend.mtp_mode` set to `auto` or `on`, `ClusterPlacementTensorAssistantSelection.readAutomatic` asks the native metadata helper for a complete depth-three cohort quote for a local cluster (a cluster served through Darkbloom: below). The returned inventory fingerprint becomes the saved bilateral policy; the provider does not infer it from a model name. Explicit `off`, the existing MTP kill switch, or an absent head retains the completely quoted ordinary TP owner. A malformed declared assistant refuses planning. This policy does not create a hand-off or phase-split deployment. + +On a coordinator-formed pair the assistant serves only as the build declares it. Its verify windows are a computation the coordinator does not see: it qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. The owner therefore declares a public assistant per artifact beside the public model declaration (`ClusterPublicModel.tensorAssistant`, a `ClusterPublicTensorAssistant`: depth, the inline head's inventory fingerprint, verification, the SHA-256 of its evidence report under `docs/reports/` and when it was qualified). This build declares Qwen3.8-27B's: depth three, admitted cohorts, the registered artifact's head inventory, the policy a local cluster plans by itself ([evidence](../reports/2026-11-05-qwen27-public-assistant.md): on one pair, the same requests decoded with the assistant's rounds and with plain steps gave identical greedy, sampled and tool answers). A release's facts give the model's serial-schedule tensor-parallel parity qualification the report's digest and instant (`ClusterRuntimeApprovalFacts.parityQualifications`), so the qualification a coordinator derives names the speculative decoding it covers; the one-chunk-lookahead qualification keeps the model's evidence, since the assistant needs serial prefill and those pairs decode plain. + +1. A setup saved for coordinator pairing carries no assistant, or exactly the declared one (`ClusterConfiguration.validate`, refusal `ClusterConfiguration.tensorAssistantServesLocally`). The leader checks a coordinator's approval against this rule before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation), and the other Mac checks it again before it saves. +2. Under `auto` the guided setup plans a cluster served through Darkbloom with the declared assistant, or without one when none is declared (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). The quote is asked at the declared depth and verification, and the native helper must return exactly the declared policy, inventory included (`requireDiscoveredQuote`). When that quote is refused (a helper error or timeout, or another inventory), a cluster served through Darkbloom is planned with the ordinary target, as it was before the declaration, and the plan says why in one line (`ClusterSetupPlanning.assistantRefusedLine`, the plan's `speculationNote`); the line appears under the model on the screen, is kept with the adopted plan (`ClusterOnboardingLeadership.speculationNote`) and `darkbloom cluster status` prints it under how the cluster serves. A local cluster's refusal still stands. Explicit `on` plans the declared assistant the same way. Without a declaration, `on` plans a local cluster's assistant (depth three, admitted cohorts), the plan's public-traffic line says the pair is not offered (`ClusterPairOwnerServing.tensorAssistantNotOffered`), and the approval is refused as above. +3. The declared assistant's launch arguments (`--mtp-depth`, `--tp-mtp-inventory-sha256`, the verification) and its evidence digest are part of the model's resource policy (`DistributedInstalledNativeStart.resourcePolicySHA256`, see [cluster runtime facts](#cluster-runtime-facts-of-an-installed-app)). A release's facts, the coordinator's approval and every committed start under it therefore name the declared assistant; without a declaration the digest is unchanged. The digest follows the build's declaration for the artifact, not the setup: a pair planned without the assistant (`mtp_mode = "off"`) carries the same value. The assistant a pair loads is bound by both workers at LOAD, as on a local cluster. +4. Admitted-cohort verification (`admitted_target_cohort_v1`, the declared policy) verifies every eligible row of a step in one rectangle, as on a local cluster; a declared singleton verification (`singleton_ready_set_v1`) would speculate only for a step whose ready set is one request (`QwenTensorParallelNativeBatchExecutor.decodeRound`). Media rows, samplers that do not admit speculative verification and requested logprobs keep their target paths, as on a local cluster. +5. A pair slot whose ranks report the assistant in READY (`ClusterQwenTensorAssistantReady`) reports MTP as configured in its slot posture (`darkbloom status`, the `engine_v2_slot_posture` telemetry event), with the counts rank zero's runtime returned request by request (`ProviderLoop.publishClusterPairSlot`, `EngineV2Bridge.mtpStatusSnapshot`, `DistributedCBv2Engine.mtpTotalsSnapshot`). Any other pair keeps the disabled posture. -The assistant serves local clusters only. Its verify windows are a computation that no parity qualification covers: the coordinator qualifies `tensor_parallel_v1` placements by classes, cuts and mode, a pair's registration carries no speculation field, and the bundled tensor-parallel records of the 27B predate the assistant. A setup saved for coordinator pairing therefore carries none (`ClusterConfiguration.validate`). The guided setup plans a cluster served through Darkbloom under `auto` as under `off` (`ClusterPlacementTensorAssistantSelection.discoveryMode`, from the serving scope in `OnboardingLive.localPlanModels`). Explicit `on` is kept; the plan's public-traffic line then says the pair is not offered, and the leader refuses the coordinator's approval before any part stops (`ClusterApprovalAttachment.attachment` runs the setup's full validation). Public speculative decoding needs qualification evidence of the assisted placement. +The evidence a declaration needs (the fixed greedy answers byte-identical with and without the assistant, concurrent answers equal to solo, sampled and logprob requests against plain tensor parallel) is recorded on a non-production pair; tiny paired-shard fixtures and the checks above do not establish it. The assistant stays resident across admitted widths. Each request owns its history, assistant pages, target frontier and bounded accepted-token queue. Each row's round starts with its own B=1 assistant step over its own history (the step that also feeds its trusted history); the round's later steps run every row of a cohort through one assistant forward (`Qwen35InlineMTPAssistant.draftHiddens`, see [Batch-invariant tensor-parallel decode projections](#batch-invariant-tensor-parallel-decode-projections)). In a cohort, one head call per draft step chooses every row's proposal (`QwenTensorParallelMTPDecoder.stepBatch`; the SDK's `Qwen35InlineMTPAssistant.draftHidden`, `draftHiddens` and `recordDraft`): the rows' hidden states go through the vocabulary-sharded head together, and the cohort's draft step is one evaluation holding two collectives (rank zero's hidden rows, then the score exchange) in the same order on both ranks, instead of one evaluation and two collectives per row. Each row's choice equals its own call's: both collectives are element-wise, the head shard computes every row with the batch-invariant kernel (`QwenTensorParallelMTPProjection.exactRows`; with exact drafts off, each row as its own single-vector MLX product, `rowsAlone`, because one plain multi-row call would let MLX pick `qmv_wide` on Apple GPU family 15 and later and change rows), and the first maximum is taken per row. `QwenTensorParallelMTPHeadRowsTests` checks the head rows byte for byte for two to eight rows, and `QwenTensorParallelBatchMTPTransitionTests.batchedCohortDraftsMatchRowByRowDraftsWithOneHeadCallPerStep` checks tokens, MTP statistics and native state against row-by-row drafting (collective reductions per run: 577 to 401 at two rows, 1,633 to 401 at eight). A one-row round runs the same per-step functions with one row, so a request proposes the same tokens alone and in a cohort. Both ranks read every proposal from the same exchanged (maximum, index) pairs, so no proposal broadcast is needed. Eligible requests then share one captured target rectangle: `QwenTensorParallelMTPDecoder.stepBatch` verifies their seed and proposals, settles every row to its independently accepted prefix, and confirms the entire ordered cohort before publishing any result. Accepted suffixes consume the existing per-token credits without another native step. Request RNG and stopping remain independent. diff --git a/docs/architecture/security/identity-binding.md b/docs/architecture/security/identity-binding.md index bfa1d31a81..be4868bc81 100644 --- a/docs/architecture/security/identity-binding.md +++ b/docs/architecture/security/identity-binding.md @@ -1,6 +1,6 @@ # Identity binding -> Last updated: 2026-10-19 +> Last updated: 2026-11-05 How the coordinator binds a provider's process encryption key, account and verification credentials. Legacy MDM/APNs evidence and App Attest credentials @@ -154,7 +154,8 @@ The security boundary is enforced by these provider-owned components: 1. **Exact code and kernel peer.** `WorkerCodeIdentity` requires Developer ID team `SLDQ2GJ6TL`, identifier `io.darkbloom.provider`, hardened runtime and no ad-hoc/debug/library-validation/loader/JIT relaxations. Both sides compare - CodeDirectory identity and full executable SHA-256 at authentication. The + CodeDirectory identity and full executable SHA-256 at authentication, read + in 1 MiB chunks that are each released before the next read. The kernel `LOCAL_PEERTOKEN` audit token, including PID version, selects the running code; a peer-supplied PID/path or same team alone is insufficient. Subsequent exchanges recheck the captured audit/code identity diff --git a/docs/developer/build.md b/docs/developer/build.md index 539a7a5991..3dda8d1411 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-11-04 +> Last updated: 2026-11-05 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -74,6 +74,19 @@ make landing-install landing-build is a separate dependency pin. Native resources must match the compiled host library; a warm cache cannot waive that requirement. +MLX's configure fetches Apple's metal-cpp headers from developer.apple.com, +and CMake's FetchContent does not try again when the download fails. On a +Darkbloom macOS sandbox runner, the image carries that archive at +`/usr/local/libexec/darkbloom/share/metal-cpp/metal-cpp_26.zip`. When the +nested MLX core names that archive and its SHA-256 is the one the script pins, +`scripts/fetch-metallib.sh` unzips it into the build directory and passes +`-DFETCHCONTENT_SOURCE_DIR_METAL_CPP`. The build then makes no download from +developer.apple.com; MLX's other dependencies still come from GitHub. In any +other case, FetchContent downloads the archive as before. +`MLX_METAL_CPP_ARCHIVE` names another local copy of that archive, under any +file name, which must have the same SHA-256. The headers are the same bytes either way, so the metallib and its +cache key do not change. + The pinned core orders fast Metal fence waits after earlier kernels in the current concurrent pass as well as prior passes. Rebuild the Cmlx host object when changing this pin. This fence change has no shader or C-header delta; @@ -281,9 +294,9 @@ see [resource and release tooling checks](test.md#focused-tooling-checks). 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. +then the same tests, `.github/workflows/provider-tests.yml` (the build jobs, +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 @@ -304,9 +317,9 @@ 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. +foreign run, an API error) runs the tests. Such a push runs only the build jobs +of the components it changed, without an upload, 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 @@ -315,13 +328,89 @@ Pushes to `master` and pull requests into `master` select every component, so a 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. +the workflow pins. It also runs the offline self-tests of the prompt fixture +downloaders (`scripts/test-prepare-prompt-fixtures.py`, +`scripts/test-prepare-mimo-prompt-fixtures.py`). `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` | +### Build Once + +Each lane builds its debug test products once, on a large runner, and its +test jobs run them with `swift test --skip-build`. No test job compiles the +provider or the cluster packages. Every job below but `test-cluster-gpu` reads +its runner from the route ([CI Runner Routing](#ci-runner-routing)). Its +fallback is `blacksmith-12vcpu-macos-27`. While job sizes are off, a +`required` job keeps its fallback without asking ([Job sizes](#job-sizes)). + +| Job | Runner | Needs | Does | +|---|---|---|---| +| `build-cluster` (Build cluster test products) | routed, `required` | - | Builds the cluster lane (`.github/actions/provider-ci-build`), uploads `cluster-test-products` | +| `build-provider` (Build provider test products) | routed, `required` | - | Builds the provider lane, uploads `provider-test-products` | +| `cluster-release-checks` (Cluster Release Build Checks) | routed, `required` | - | Compiles the release build of the worker capability and prefill schedule checks, and runs them | +| `test-provider`, shards 1 and 2 | routed | `build-provider` | The provider selections, Prompt Parity, the native gates, the audit and coverage | +| `test-cluster`, shards 1 to 3 | routed | `build-cluster` | The blocking cluster selections | +| `test-cluster-gpu`, shards 1 and 2 | `blacksmith-12vcpu-macos-27`, not routed | `build-cluster` | The non-blocking cluster GPU selections | +| `test-cluster-focused`, shards 1 and 2 | routed | - | The focused runner scripts (shard 1); the stage metadata, provisioning and onboarding runners (shard 2) | + +The cluster lane builds in a job of its own, so the cluster tests start as soon +as their products are up; GitHub starts a job only when every job it needs is +done. The capability and prefill checks have their own job for the same +reason, and so that their failure skips no test job. + +SwiftPM's products hold absolute paths: `#filePath` in the test sources, +the resource bundle paths, and the local package paths in +`workspace-state.json`. Blacksmith and Darkbloom check out to different paths, +so the jobs that build or run the products work at one fixed path, +`/private/tmp/dinf`. Their first step replaces the job's workspace with a link +to it; every later step starts in the workspace, and the system resolves the +link, so SwiftPM, the compiler and the tests see only `/private/tmp/dinf`. The +Swift build cache keys bind that path (`scripts/provider-ci-cache.py` keys the +resolved checkout). + +`scripts/ci-test-products.py`, through `.github/actions/provider-ci-products`, +packs the lane's `.build` with tar and zstd, without the compile intermediates +(each target's `.build` directory, `ModuleCache`, `index` and +`Modules`). The archive keeps the test bundles, the executables, the resource +bundles, the staged matched `mlx.metallib`, and the checkouts, repositories and +`workspace-state.json`, so SwiftPM loads the package graph without a fetch. It +is uploaded without more compression and kept for one day. A test job selects +the SDK 27 toolchain, downloads the archive and unpacks it. It refuses +products of another commit or of another Swift, Xcode or SDK version, and it +never unpacks over a build. When only the builds of those versions differ (the +Blacksmith and Darkbloom images can carry different builds of one Xcode +version), it warns and runs the products. Both sides print the archive +size and the upload or download time. + +Every macOS job runs `scripts/ci-resource-sampler.py` in the background from +its checkout on. Every 5 s it records: + +- Memory by class, from `vm_stat`: app (anonymous less purgeable pages; Metal + buffers count here), wired, file cache (reclaimable), compressed, and used = + app + wired + compressed. Also swap in use and the memory pressure level. +- Busy vCPUs, from the host's CPU ticks. +- The physical footprint of each process of the runner user, from + `proc_pid_rusage`. This is the counter that `footprint` and Activity Monitor + show, and it includes IOAccelerator (Metal) memory. The sampler keeps the + sum and the three largest processes by lifetime peak. + +The provider and cluster test runners mark the start and end of each test +selection (`ci-resource-sampler.py mark`), so the report names the selection +of each large process and the selections that ran at the peak. When the +largest footprint first reaches 2 GiB, and again when it is 2 GiB above the +last capture, `/usr/bin/footprint` (if present) writes that process's breakdown +by category beside the samples, at most twice a job. + +The job's last steps print the peaks, the three largest processes, the busy +vCPUs and the sampled time scaled to 4 and 8 vCPUs to the log and the step +summary. They upload the samples and `summary.json` as +`resource-samples--`. The sampler is report-only: its steps never +fail a job. + 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 @@ -330,16 +419,16 @@ only for pull requests into `master`. ## CI Runner Routing -`.github/workflows/darkbloom-route.yml` chooses where read-only CI jobs run: a -Darkbloom Sandbox when its plane grants one, otherwise the job's Blacksmith -fallback. It runs on GitHub-hosted `ubuntu-24.04` with no token permissions or +`.github/workflows/darkbloom-route.yml` chooses where routed read-only CI jobs +run: a Darkbloom Sandbox when its plane grants one, otherwise the job's +Blacksmith fallback. It runs on GitHub-hosted `ubuntu-24.04` with no token permissions or checkout. Each routed job runs on `fromJSON(needs.route.outputs.routes)['']`, where the lane is the job's name; each shard of a sharded job reads its own lane, `format('-{0}', matrix.shard)`. | Workflow | Routed jobs | Fallback | |---|---|---| -| `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` | +| `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` to `test-cluster-3`), `test-cluster-focused` (one lane, `test-cluster-focused`, requested for both shards), `build-cluster`, `build-provider`, `cluster-release-checks` | `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` | @@ -363,14 +452,17 @@ Routing is off unless the repository variable `DARKBLOOM_ROUTING` is exactly `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 +without asking (any other value asks for no macOS lane). A lane gets the jobs +of its whole matrix, so the two focused shards share the lane name the approval +lists. + +While routing 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 most once after a transient failure. It uses a grant only when the grant -repeats the exact Darkbloom labels for the job's profile. Errors, timeouts and +repeats the exact Darkbloom labels for the job's profile, qualified by the +lane's size when it sends one ([Job sizes](#job-sizes)). Errors, timeouts and malformed replies keep the fallback; the plane never fails the route job. Every job of a lane shares one `runs-on` value, so the plane grants a lane whole, for its requested job count, or not at all. Each shard is therefore a @@ -399,11 +491,16 @@ 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. 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. +every macOS job but Cluster GPU 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`. Cluster GPU Tests run on `blacksmith-12vcpu-macos-27` and are +not routed ([Job sizes](#job-sizes)). A lane without a size gets the +approval's pinned image size for its profile (one for macOS, one for Linux). +The macOS one measured 12 vCPU / 32 GiB on 2026-11-05 (run 42105290034, +attempt 1); it is not a fixed default. The build jobs and Cluster Release +Build Checks ran on Blacksmith before sizes, so they ask only with their size +([Job sizes](#job-sizes)). Jobs on Darkbloom Sandboxes use GitHub's Actions cache, not Blacksmith's colocated cache, so their first runs start without cached build products. @@ -412,6 +509,63 @@ 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). +### Job sizes + +A macOS lane can ask for a size, `x`. The route job checks each +size against this grammar (lowercase decimal, no leading zeros) and fails on a +bad value, before it sends a request. The route job sends sizes only when the +repository variable `DARKBLOOM_JOB_SHAPES` is exactly `on`. While it is off: + +- The request has no size. It is byte for byte the request of a lane table + without sizes. +- The 7 blocking test jobs ask without a size, as before sizes. Their runners + do not change. +- A lane marked `required` keeps its fallback without asking. It takes no + place under the `DARKBLOOM_MACOS_LANES` cap. + +The lane table in the `route` job of `provider-plan.yml` is the one place that +names each job's lane and size. The lanes are in cap order: the critical-path +test shards first, then the `required` jobs. + +Each size is the smallest signed size (4x16, 4x24, 8x16, 12x32) that holds the +job's used memory times 1.25, on which the job takes at most 5% longer than on +12 vCPUs. Used memory is app + wired + compressed, the peak that +`scripts/ci-resource-sampler.py` recorded in runs 42105290034 (both attempts) +and 42123224100 ([Build Once](#build-once)), on 12 vCPU runners: Blacksmith +with 48 GiB, and for three jobs of the first attempt Darkbloom with 32 GiB. The +time on fewer vCPUs is the sampled time scaled to 4 and 8 vCPUs. The file cache +(up to 22.3 GiB) is not counted: the kernel can reclaim it. Swap stayed at 0 +and memory pressure stayed normal. + +| Lane | Jobs | Size | Used memory (GiB) | While sizes are off | +|---|---|---|---|---| +| `test-cluster-2` (the concurrent groups) | 1 | 12x32 | 29.29, the Metal memory of the GLM-5.3 paged KV tests; 12x32 leaves a 1.09 margin | asks without a size | +| `test-cluster-3` (the Gemma 4 base suites) | 1 | 4x24 | 14.67 | asks without a size | +| `test-cluster-focused` | 2 | 4x16 | 8.06, 7.61 | asks without a size | +| `test-provider-2` | 1 | 4x24 | 16.17 in one sample, about 9 otherwise | asks without a size | +| `test-cluster-1` | 1 | 4x16 | 11.97 | asks without a size | +| `test-provider-1` | 1 | 4x16 | 11.03 | asks without a size | +| `build-cluster` | 1 | 8x16 | 10.91; a cold build takes 5 to 10% longer on 8 vCPUs | Blacksmith, not asked | +| `build-provider` | 1 | 12x32 | 17.50; 8x24 is not signed, and a cold build takes 20% longer on 8 vCPUs | Blacksmith, not asked | +| `cluster-release-checks` | 1 | 8x16 | 9.65 with a reused build; a cold release compile (run 42041608780: 11.33 GiB, 11.4 busy vCPUs at p95 of 12) takes 26% longer on 4 vCPUs and 5.5% on 8 | Blacksmith, not asked | + +A run that tests every component asks for 10 macOS jobs while sizes are on, +and 7 while they are off. The two Cluster GPU Tests shards are not routed: +they run on `blacksmith-12vcpu-macos-27` (12 vCPU, 48 GiB). Shard 2 uses +41.99 GiB, which no signed size holds, and one lane carries one size for both +shards (shard 1 uses 17.40 GiB). + +A lane sent with a size uses a grant only when the grant's labels are its +profile's labels with the last one qualified by the size, such as +`[self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x24]`. The job then runs on +that `runs_on` value as the plane sent it. Otherwise the lane keeps its +fallback. The plane names its reason, for example `shape_not_signed` (no signed +image of that size), `unavailable` (the plane cannot read its image catalog), +`unsupported_runner_class` (the size has no price), `image_not_available` (the +image is not staged) or `lane_not_enabled` (the approval does not name the +lane). For each lane, the route job's log and step summary show the size +asked, the runner, and the decision with its reason. + ## CI Caching `.github/workflows/provider-tests.yml`, `.github/workflows/ci-master.yml` and @@ -432,12 +586,12 @@ the caches of the runners it ran on. |---|---|---|---| | 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 | +| SwiftPM repositories | `/private/tmp/dinf-ci/swiftpm-repositories`, which `~/Library/Caches/org.swift.swiftpm/repositories` links to | `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` | +| Metal library | `/private/tmp/dinf-ci/metallib-cache` | `metallib-key`, exact only | each build lane | +| MiMo metadata downloads | `/private/tmp/dinf-ci/mimo-metadata-cache`, one file per pinned SHA-256 | `mimo-metadata-v1-`, exact only | each provider shard | +| MiMo audio codec | `/private/tmp/dinf-ci/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 | `cluster-release-checks` | 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 @@ -456,13 +610,15 @@ 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 +Every checkout uses the same five steps, after the fixed-path step in the jobs +of the test products ([Build Once](#build-once)). 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 +`continue-on-error` (only the report-only upload of the resource samples +does). 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 @@ -491,7 +647,7 @@ flowchart LR 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"] + S --> B["Build job: restore SwiftPM,
build and Metal caches; build"] B --> M{"master or dev push,
no exact hit?"} M -- yes --> T[Save each cache] classDef save fill:#d4f7dc,stroke:#1a7f37,color:#0b2e13 @@ -506,7 +662,13 @@ flowchart LR 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 + workspace path. It unpacks with `tar -C `, and in the jobs of the + test products the workspace is a link to `/private/tmp/dinf` + ([Build Once](#build-once)): there a relative path that climbs out of the + workspace climbs out of `/private/tmp/dinf` instead. Those jobs therefore + keep every cache outside the workspace in `/private/tmp/dinf-ci`, whose only + common ancestor with any workspace is `/`, and never under `$RUNNER_TEMP` or + the home directory (`scripts/test-provider-ci-workflow.py` checks it). 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 diff --git a/docs/developer/test.md b/docs/developer/test.md index d8bd1a2d14..34d00af445 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-11-04 +> Last updated: 2026-11-06 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -18,7 +18,13 @@ association, empty-text holdback, parser flushes, terminal failures, cancellatio collected completeness and the 4096-entry pending bound. Reasoning/tool source spans remain unclassified; those entries retain the existing next-content policy. A separate unsupported-profile case requires HTTP 400 before reservation and -successful text afterward. Run +successful text afterward. The parity run's fabricated pair acknowledges +retirement at once; a forced-order case holds that acknowledgment until the +client has the answer, so a named `tool_choice` stream the shared pipeline +rejects mid-generation must end with the single-Mac failure frame while the +pair is still finishing the cancelled request. It also requires that the +request was cancelled and its acquisition and HTTP hold freed by then, and its +lane after retirement. Run `swift test --package-path provider-swift --filter ClusterAPIParityTests` with the [provider build prerequisites](build.md). These CPU checks prove API wiring, not native model capabilities, numerical parity or hardware qualification. @@ -113,8 +119,8 @@ 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 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 +Mac each. Each shard runs the products of the one provider build +([build once](build.md#build-once)) and 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. @@ -148,18 +154,22 @@ 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 +refresh the weights file. The last shard's audit warns, and does not fail, when +a serial suite in the list has no weight: the last selection then runs it with +every other new suite, and that selection grows. 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 the cluster metadata runners +The build jobs (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. +once more from nothing if that build fails. The test jobs build nothing: they +download their lane's products and refuse products of another commit or +toolchain version. 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; the build jobs of the components the push +changed save their caches. 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 @@ -1207,7 +1217,20 @@ hashes, enum casing and optional-field omission. download only the committed manifests' hash-pinned public prompt assets, never weights. The downloader identifies itself as `darkbloom-prompt-fixtures/1` to the CDN and retains same-origin HTTPS, byte-budget and integrity checks. -Provisioning failures fail qualification; they must not silently skip vectors. +It retries only a cut or failed transfer (a TLS, socket or connection error, a +timeout, a body that ends before its declared size, or HTTP 5xx), at most 3 +attempts per artifact with 1 s and 3 s backoff inside the 120 s deadline. A +full-size body with the wrong SHA-256, an oversize body, a Content-Length +mismatch, a cross-origin response, another non-200 status or the deadline fails +at once. `scripts/prepare-mimo-prompt-fixtures.py` and +`scripts/prepare-mimo-image-http-fixtures.py` apply the same retry rule to each +metadata file, with these differences. They refuse a redirect to plain HTTP but +follow a redirect to a different HTTPS host. The MiMo prompt script has no total +deadline: each connect and read has a 60 s socket timeout. The image script has +a 120 s deadline for each file, and it classifies curl's exit code: a cut +transfer (for example exit 18 or 56) retries, and an oversize body (63), a +certificate failure or a plain-HTTP redirect does not. Provisioning failures +fail qualification; they must not silently skip vectors. Public validation means **this implementation matches those fixed expectations**. It does not run private Go/Rust implementations, establish current cross-implementation @@ -1251,15 +1274,21 @@ 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-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`, +exits non-zero on a failure. When the classifier selects `cluster` (see below), +CI (`.github/workflows/provider-tests.yml`) runs them in three places. The job +`cluster-release-checks` (Cluster Release Build Checks; its runner is in +[Job sizes](build.md#job-sizes)) runs +`libs/darkbloom-cluster-worker/Tests/CapabilityChecks/run.sh` and +`libs/darkbloom-cluster/Tests/PrefillScheduleChecks/run.sh`, which compile a +release build of the cluster runtime. Shard 2 of `test-cluster-focused` +(Cluster Focused Checks) runs `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`, then -every other runner under `libs/darkbloom-cluster/Tests`. The provisioning runner runs the +`libs/darkbloom-cluster/Tests/NemotronStageChecks/run.sh`, +`provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning` and +the onboarding checks. Shard 1 runs every other runner under +`libs/darkbloom-cluster/Tests`. Each runner compiles only its own small source +closure. 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 @@ -1272,31 +1301,37 @@ 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 Runtime Tests, Cluster GPU Tests and Cluster -Focused Checks) run when the classifier selects `cluster`, on a pull request +The cluster jobs (Build cluster test products, Cluster Runtime Tests, Cluster +GPU Tests, Cluster Release Build Checks 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. The `Provider Tests` gate accepts a skipped cluster job only when `cluster` was not -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`). +selected. A provider-only change runs 3 Macs (the provider build and the 2 +provider shards). A cluster change adds 9 Macs (the cluster build, the release +build checks, 3 runtime shards, 2 focused shards and 2 GPU shards). Every +Mac job but the 2 GPU shards is routed; the GPU shards run on Blacksmith +([job sizes](build.md#job-sizes)). 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. 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 +the selection runs no test or skips a test. Runtime shard 1 runs `base` 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`). +The second group starts `CLUSTER_TEST_START_GAP` seconds (default 15) after +the first, as the provider shards' processes do, so their SwiftPM startups do +not meet on the shared build database. +Shard 3 runs `base-gemma` alone: the Gemma 4 base suites (`GEMMA_SUITES`, 592 of +the base tests' 970 s), so each model family still shares one process. 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. @@ -1309,8 +1344,8 @@ log prints both attempts' logs. Every process starts with | 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` (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 +plan names each gated test in the sources once, each runner under +`libs/darkbloom-cluster/Tests` once, and every Gemma suite in `GEMMA_SUITES`. 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 @@ -1882,10 +1917,14 @@ removed first, its failure fatal only when `CLUSTER_RUNTIME_SEND` is true, and HTTPS plane with a throwaway certificate; the host needs Bash, Python, jq, curl and openssl. It covers the default-off switch, fork pull requests, exact label grants, HTTP errors, the single retry, timeouts, untrusted or plain-HTTP planes -and hostile reply text. It also pins each routed job's lanes (one per provider -or cluster shard, matching the job's matrix), fallback, timeout and read-only -permissions, and keeps release workflows on literal Blacksmith runners. No check -contacts the real plane. +and hostile reply text. It covers [job sizes](build.md#job-sizes) both ways: +while `DARKBLOOM_JOB_SHAPES` is not exactly `on`, CI's request is byte for byte +the request without sizes; while it is on, each lane sends its size and takes +only the labels of that size. It also covers bad sizes and the macOS cap order. +It also pins each routed job's lanes (one per provider or cluster shard, +matching the job's matrix), size, fallback, timeout and read-only permissions, +and keeps release workflows and Cluster GPU Tests on literal Blacksmith +runners. No check contacts the real plane. Docs-impact tests retain provider, protocol, privacy, native capacity, cache, release/model publication and fixture mappings. Historical links need exact @@ -2216,7 +2255,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 Focused Checks` job (step `Run cluster onboarding checks`). +it in shard 2 of 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/provider/direct-mode.md b/docs/provider/direct-mode.md index 74ec3a42d6..0b1861f204 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -1,6 +1,6 @@ # Direct mode: a local OpenAI-compatible endpoint -> Last updated: 2026-10-31 +> Last updated: 2026-11-06 Run the provider's inference engine as an OpenAI-compatible HTTP server on your own Mac, either standalone (`darkbloom start --local`, no coordinator, no @@ -174,7 +174,13 @@ still cancels generation. Responses uses `response.failed` for late failures. The provider chat-upload interceptor selects the SDK service's HTTP framing policy (`LocalChatUploadResponder.respond` and `MLXOpenAIService.streamChatCompletionFrames`). A failed required tool call is still a failure; no argument repair or fabricated -call is performed. +call is performed. On a [two-Mac cluster](./two-mac-cluster.md) the leader's +local API ends such a stream with the same error chunk. This holds also when +the provider rejects the output mid-stream (a forced `tool_choice` answered +with text, a streamed tool call that fails validation) while the pair is still +finishing the cancelled request +(`provider-swift/Sources/ProviderCore/Server/Distributed/DistributedHTTPEventStream.swift`, +`DistributedHTTPEventStream`). ### Refused request shapes @@ -337,6 +343,9 @@ names the worker build each Mac served the request with, and a plan or route uses a speed only for the build that served it, so speeds an earlier build served no longer steer the pair's plan after an update ([served speed records](../architecture/inference.md#served-speed-records-and-worker-builds)). +Each record also says the request came through this local API (not +Darkbloom) and whether Qwen's tensor assistant decoded it; a plan for serving +through Darkbloom uses none of the local records. The HTTP API is unchanged. Source: `provider-swift/Sources/ProviderCore/Server/Distributed/DistributedLocalServer+Startup.swift` and `provider-swift/Sources/ProviderCore/Inference/Distributed/Observability/DistributedPairTelemetryRecorder.swift`. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 7253b65995..671748e6ec 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -107,6 +107,8 @@ file (`registered_models`), not from configuration. It has no setting. See ## Runtime metallib snapshots The provider creates an anonymous snapshot before binding the runtime metallib. +It copies and hashes the metallib in 1 MiB chunks and releases each chunk +before the next read. | Variable | Default / accepted values | Consumer | |---|---|---| @@ -966,7 +968,7 @@ runtime digest, and the provider computes no facts for it | `models[].artifact_sha256` | the capability's `artifactSHA256`, the catalog aggregate | | `models[].capability_sha256` | SHA-256 of the exact output of `darkbloom-cluster-worker --describe-runtime` | | `models[].profile_sha256` | the capability's `profileFingerprint` | -| `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries | +| `models[].resource_policy_sha256` | `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability, the value a native start carries: SHA-256 of `darkbloom/installed-resource-policy/v1`, the arithmetic policy ID and digest, the state semantics and the scheduling policy joined by U+001F; when the build declares a resident assistant public for the model's runtime model and artifact (`ClusterPublicModels.tensorAssistant`), followed by `qwen27_tensor_assistant_v1`, `depth=`, `--tp-mtp-inventory-sha256=`, `verification=` and `evidence=` (`ClusterPublicTensorAssistant.resourcePolicyFields`). This build declares Qwen3.8-27B's (depth 3, `admitted_target_cohort_v1`) | | `models[].pair_serving_grant` | `null`, or exactly `evidence_sha256` and `mode_families` (1 to 4 of `hand_off`, `pipeline`, `pipeline_speculative`, `tensor_parallel`, in byte order). A model the build's public declaration (`ClusterPublicModels`) names by runtime model, catalog ID and artifact: its declared families, with the evidence document's SHA-256. Any other model: the families the build's bundled records grant its artifact (`ClusterPairServingGrants.grant`), with the SHA-256 of the records that grant is computed from (the artifact's passing records, without a pass that a divergence of the same shape contradicts) as canonical JSON Lines (`ClusterPairServingGrant.evidenceSHA256`: each record's `encodedLine` in bundle order, joined by `\n`, no trailing newline); `null` when they grant none | | `models[].parity_qualifications` | `[]` unless the model is declared; then one object per declared mode family (in byte order: `pipeline`, `pipeline_speculative`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | | `…schedule` | `1` or `2`: the derived approval it qualifies | @@ -974,8 +976,8 @@ runtime digest, and the provider computes no facts for it | `…mode`, `…cuts` | `pipeline`: `pipeline_v1` cut at `[num_hidden_layers / 2]` (integer division) of the model's `config.json`, read at the top level or else in `text_config` (`[22]` for GLM-5.3-Flash, `[32]` for Qwen3.8-27B, `[24]` for MiMo-V2.6-Flash, `[15]` for Gemma 4 26B QAT); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `pipeline_speculative` (MiMo-V2.6-Flash): `pipeline_mtp_v1`, cut as the pipeline is. `tensor_parallel`: `tensor_parallel_v1`, `[]` (`ClusterPublicModels.placement`) | | `…tensor_parallel_shares` | `null`: equal shares | | `…promotable`, `…diverged` | `true`, `false` | -| `…evidence_sha256` | SHA-256 of the evidence document, [`docs/reports/2026-10-31-public-cluster-models.md`](../reports/2026-10-31-public-cluster-models.md) | -| `…qualified_at` | `2026-11-03T00:00:00Z`, the date of the latest declaration | +| `…evidence_sha256` | SHA-256 of the evidence document, [`docs/reports/2026-10-31-public-cluster-models.md`](../reports/2026-10-31-public-cluster-models.md); for the serial-schedule (`1`) `tensor_parallel` qualification of a model declared with a resident assistant, its report's (schedule `2` pairs decode plain: the assistant needs serial prefill) (Qwen3.8-27B: [`docs/reports/2026-11-05-qwen27-public-assistant.md`](../reports/2026-11-05-qwen27-public-assistant.md); `ClusterRuntimeApprovalFacts.parityQualifications`) | +| `…qualified_at` | `2026-11-03T00:00:00Z`, the date of the latest declaration; for that assistant qualification, the assistant's `qualifiedAt` | | `…request_envelope` | `sampling` and `tools` `true`; `max_prompt_tokens` and `max_output_tokens` 1,048,576 (the coordinator's maximum: only the model's own limits apply); where the placement serves media (`ClusterModelFeaturePolicy.mediaContract`: GLM-5.3-Flash and Qwen3.8-27B in tensor parallel; a pipeline is text only), `vision` when the model's catalog entry in the release's environment lists `image` in `input_modalities`, `video` when it also lists `video` (`ClusterPublicModels.requestEnvelope`). A model given by hand has no catalog entry, so its envelope admits text only | The public declaration names GLM-5.3-Flash (`registered_glm53_flash`, @@ -1112,7 +1114,7 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Lifetime | A saved approval with more than `renewWithinSeconds = 86_400` left is kept. Within that day a later matching entry replaces it. An entry that the operator replaced under the same `id` (other bytes, for example a new `not_after`) is no longer the saved approval: a matching entry replaces it, else it is withdrawn (Serve locally). An ended one is removed: each Mac saves its setup without it before its part starts, and its part then serves on the leader's local API (`ClusterService.supervise`) | `ClusterApprovalLifetime.decide` | | Serve locally | Both Macs save their setups without the approval, the other Mac first, and the pair serves on the leader's local API, when: no request gets an HTTP answer for the absence grace (`ClusterService.soloGraceSeconds`: 600 s; `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS` in a development build); the coordinator answers (a 404, or a list) without the saved approval as saved and serves no other matching entry; or either Mac's coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds = 3` times in a row right after starting (each Mac's status, `memberQuickEnds`). An end the coordinator decided is not counted: one because it was out of reach (`ClusterMemberControlError.coordinatorUnreachable`, which also starts the count again) or because it did not accept the member role in its negotiation window (`negotiationFailed`, which leaves the count as it is; a part that ran `quickEndSeconds = 120` or longer starts it again, as always) (`ClusterApprovalCheck.memberQuickEnds`). It complements a coordinator that ends each pair session before its shutdown closes the members' connections, which makes a deploy's ends cleaner; the rule still covers coordinators without that change, coordinator crashes and slow negotiation. When either Mac cannot save, both keep the approval and the next check tries again. The leader keeps the approval, the reason, the setup's worker digest and the time in its setup record (`approvalSetAside`, `runtimeBinarySHA256`, `setAt`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, a later entry at once, the same entry `ClusterApprovalFallback.failingSeconds = 3_600` after it was set aside, or the same entry after an update installs another worker. A record without `setAt` (an older build's) is past that bound | `ClusterApprovalCheck.step`, `ClusterApprovalSync.serveLocally`; `ClusterService.checkApproval` | | Both or neither | A send whose reply is lost may come after the other Mac saved: the leader gives it its setup back. Each Mac's status names its saved cluster approval (`approvalID`, `""` for none; a build without the field is unknown and never compared). On every check the leader compares it with its own; while they differ, it gives the other Mac its approval (while offered) or none, and saves its own setup without an approval it does not offer; when the other Mac refuses its approval, it saves its own setup without it too | `ClusterApprovalCheck.peerApprovalID`, `macsDiffer`, `ClusterApprovalSync.converge` | -| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files and with every rule the save applies to the setup with the approval attached (`ClusterConfiguration.validate`, which refuses a saved `tensorAssistant` beside `nativeMember`: "Qwen's speculative assistant serves local clusters only …", `tensorAssistantServesLocally`), so no part stops and nothing is sent for an approval either Mac must refuse. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply`, `ClusterApprovalAttachment.attachment` | +| Changing | The leader decides under the command lock, from the setup, record and the other Mac's status as they are then. A save is first checked against the leader's own files and with every rule the save applies to the setup with the approval attached (`ClusterConfiguration.validate`, which refuses a saved `tensorAssistant` beside `nativeMember` unless it is exactly the assistant the build declares public for the artifact: "Qwen's speculative assistant serves local clusters only unless declared public …", `tensorAssistantServesLocally`), so no part stops and nothing is sent for an approval either Mac must refuse. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply`, `ClusterApprovalAttachment.attachment` | A coordinator that answers 404, serves no matching entry or serves only ended entries leaves both saved setups byte for byte as they were: nothing is sent @@ -1709,8 +1711,8 @@ Normal setup discovers the embedded assistant from the native quote on a cluster | Setting | Bound and behavior | Source | |---|---|---| -| `[backend] mtp_mode` | Selects embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`) by how the cluster serves (`ClusterServingScope`): `auto` (default) discovers it for a cluster that serves locally only (`darkbloom cluster local`) and plans a cluster served through Darkbloom without it, as the re-plans after an update or a memory refusal do; `on` discovers it either way, and a cluster served through Darkbloom then is not offered to the coordinator (its public-traffic line says so, `ClusterPairOwnerServing.tensorAssistantNotOffered`); `off` retains the ordinary fully quoted target. Automatic discovery selects depth `3` and admitted-cohort verification. The developer six-step wizard and `darkbloom cluster plan` discover it as for a local cluster. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `discoveryMode`, `automaticCandidate`, `automaticDepth`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` (`OnboardingLive.localPlanModels`) | -| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. Never beside `nativeMember`: such a setup is refused when saved or loaded ("Qwen's speculative assistant serves local clusters only …"), and the leader refuses a coordinator's approval for it before any part stops. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy`; `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`tensorAssistantServesLocally`) | +| `[backend] mtp_mode` | Selects embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`) by how the cluster serves (`ClusterServingScope`): `auto` (default) discovers it for a cluster that serves locally only (`darkbloom cluster local`) and plans a cluster served through Darkbloom with the assistant the build declares public for the artifact (`ClusterPublicModels.tensorAssistant`: its depth and verification) or, when none is declared, without one, as the re-plans after an update or a memory refusal do; `on` discovers it either way, and a cluster served through Darkbloom whose assistant is not declared is then not offered to the coordinator (its public-traffic line says so, `ClusterPairOwnerServing.tensorAssistantNotOffered`); `off` retains the ordinary fully quoted target. Automatic discovery for a local cluster selects depth `3` and admitted-cohort verification. The developer six-step wizard and `darkbloom cluster plan` discover it as for a local cluster. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `discoveryMode`, `automaticCandidate`, `automaticDepth`; `provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift` (`OnboardingLive.localPlanModels`) | +| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. Beside `nativeMember` only as the exact policy the build declares public for the artifact (`ClusterPublicModels.tensorAssistant`; this build declares Qwen3.8-27B's: depth 3, the registered head inventory, `admitted_target_cohort_v1`): any other is refused when saved or loaded ("Qwen's speculative assistant serves local clusters only unless declared public …"), and the leader refuses a coordinator's approval for it before any part stops. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy`; `provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift` (`tensorAssistantServesLocally`) | | Saved `tensorAssistant.verification` | `singleton_ready_set_v1` is the omitted legacy value; `admitted_target_cohort_v1` verifies eligible rows together up to the completely priced capacity. Unknown/null values are refused. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `Verification` | | Native worker `--mtp-depth`, `--tp-mtp-inventory-sha256`, `--tp-mtp-verification` | Installed launch arguments derived from saved policy, bilaterally bound at LOAD. Normal setup does not ask the user to choose them. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledGenerationSelection.swift`; `libs/darkbloom-cluster-worker/Sources/DarkbloomClusterWorker/Startup/WorkerConfiguration.swift` | | `DARKBLOOM_QWEN_MTP_SERIAL`, `DARKBLOOM_QWEN_MTP_DOUBLE_FORWARD`, `DARKBLOOM_QWEN_MTP_SHORTLIST` | True serial/double-forward overrides and any shortlist setting other than `0` conflict with this TP policy and are refused; complete vocabulary scores and captured target settlement remain authoritative. | `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelMTPPolicy.swift`, `require` | diff --git a/docs/reference/model-registry-format.md b/docs/reference/model-registry-format.md index aafaeb4b7f..6b2be1e9f7 100644 --- a/docs/reference/model-registry-format.md +++ b/docs/reference/model-registry-format.md @@ -1,6 +1,6 @@ # Model registry format -> Last updated: 2026-10-27 +> Last updated: 2026-11-05 Exact shapes for everything the model registry stores or accepts: the `manifest.json` a publisher uploads to R2, the registration and admin requests, @@ -122,6 +122,10 @@ hash (`provider-swift/Sources/ProviderCoreFoundation/OverlappedFileDigest.swift` and the read then drops the file's pages from the file cache (`provider-swift/Sources/ProviderCoreFoundation/PageCache.swift`), so a verified download does not stay resident beside the model it is loaded into. +`ManifestBuilder` (`darkbloom-publish`) reads each file in 64 KiB chunks, each +in its own autorelease pool on macOS +(`provider-swift/Sources/ProviderCoreFoundation/FileHandle+DrainedRead.swift`), +so a publish holds one chunk for each file it hashes, not the files. ### R2 layout diff --git a/docs/reference/ssd-kv-cache.md b/docs/reference/ssd-kv-cache.md index 27fb09098f..a77b27c72f 100644 --- a/docs/reference/ssd-kv-cache.md +++ b/docs/reference/ssd-kv-cache.md @@ -1,6 +1,6 @@ # SSD KV cache reference -> Last updated: 2026-11-01 +> Last updated: 2026-11-05 Exact on-disk format, paths, identity binding, environment knobs, size and eviction rules, and per-family reuse capability of the provider's encrypted SSD @@ -62,7 +62,7 @@ header comment and `enum SSDBlockStore`). | Lookup key | `K_lookup = HKDF-SHA256-Expand(PRK: KEK, info: "dbkv3-lookup-v1", L = 32)` | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDLookupKeys.swift` | | File-name tag | `HMAC-SHA256(K_lookup, "dbkv3-name-v1" ‖ u64le(len(salt)) ‖ salt ‖ chainHash)`, truncated to `truncatedTagLength = 16` bytes; full tag authenticated in metadata | `SSDLookupKeys.swift` | | Window sidecar tags | `"dbkv3-window-v1"`, `"dbkv3-window-base-v1"` domains (format only; `DARKBLOOM_PREFIX_CACHE_SSD_WINDOW_SIDECAR` off; no restore consumer) | `SSDLookupKeys.swift`, `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDWindowSidecar.swift` | -| Streaming read | `SSDBlockChunkCursor` returns one authenticated chunk per call in file order, or skips one unread, then checks EOF and file identity; `readStreaming` drives one cursor. A field or chunk that one read returns whole is kept as read rather than copied into a second buffer (`SSDBlockStore.readExactly`) | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDBlockChunkCursor.swift`, `SSDBlockStore.swift` (`readExactly`) | +| Streaming read | `SSDBlockChunkCursor` returns one authenticated chunk per call in file order, or skips one unread, then checks EOF and file identity; `readStreaming` drives one cursor. A field or chunk that one read returns whole is kept as read rather than copied into a second buffer (`SSDBlockStore.readExactly`). Each read runs in its own autorelease pool (`FileHandle.readDrained`), so a streamed restore holds the chunks in use, not every chunk it read | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDBlockChunkCursor.swift`, `SSDBlockStore.swift` (`readExactly`) | | Temp files | `tempMarker = "darkbloom-tmp"`, crash-orphan TTL `crashTempTTLSeconds = 3600` | `SSDBlockStore.swift` | | Path safety | Descriptor-relative no-follow traversal; nonblocking final read/touch opens followed by regular-file validation | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDNoFollowIO.swift`, `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDBlockPathGuard.swift` | diff --git a/docs/reports/2026-11-05-qwen27-public-assistant.md b/docs/reports/2026-11-05-qwen27-public-assistant.md new file mode 100644 index 0000000000..6d8cc90d0a --- /dev/null +++ b/docs/reports/2026-11-05-qwen27-public-assistant.md @@ -0,0 +1,105 @@ +# Qwen3.8-27B tensor-parallel assistant on public traffic: parity evidence + +> Last updated: 2026-11-05 + +This record is the evidence document of the provider's public declaration of Qwen3.8-27B's resident speculative +assistant on tensor-parallel pairs (`ClusterPublicTensorAssistant` on the Qwen3.8-27B entry of +`ClusterPublicModels.declared`). The declaration's `evidenceSHA256` is the SHA-256 of this file. A release's cluster +runtime facts give the model's serial-schedule tensor-parallel parity qualification this digest and instant (the +assistant needs serial prefill, so one-chunk-lookahead pairs decode plain and keep the model's evidence). It records the owner's +decision and the checks it rests on. It contains no endpoint, credential, machine identifier or personal workspace +location. It is not a hosted-provider certification or a production deployment approval. + +## Decision + +The owner (jonathan308) decided on 2026-11-05: "spec decode should be on and working for all and be much faster +through 2x", then "Finish the mtp fix and bench's then let's release .9". Two-Mac pairs that serve Qwen3.8-27B +through Darkbloom therefore decode with the assistant, as a local cluster and one Mac (MTP) already do. + +## Declared assistant + +| Runtime model | Catalog model | Artifact | Depth | Inventory (`--tp-mtp-inventory-sha256`) | Verification | +|---|---|---|---|---|---| +| `registered_qwen38_27b` | `EigenLabs/Qwen3.8-27B-4bit-mtp` | `bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463` | 3 | `6bf428caf645e41cfda642108fc9a21d199ca999e80907be7476e87026afb014` | `admitted_target_cohort_v1` | + +This is the policy local clusters already plan by themselves (`ClusterPlacementTensorAssistantSelection.automaticDepth`, +admitted cohorts). The inventory is the one the native metadata helper returns for the registered artifact +(`darkbloom-cluster-plan tensor-batch-scope --mtp-depth 3`, `QwenTensorParallelMTPInventory.footprint`). The placement is +the declared `tensor_parallel` family (`tensor_parallel_v1`, no cut). Through Darkbloom the shares are equal. + +## What was run + +The pair was an Apple M3 Ultra (256 GB, macOS 27.2) leading an Apple M5 Max (128 GB), over Thunderbolt, on DevNet +build `0.10.7-dev.branch.95`, the same build on both Macs. Requests went to the leader's local API, so every request +reached this pair and no other. The Mac Studio's display was in use (WindowServer took 40–55 % of its GPU). +The fixed requests: +- the 12 greedy prompts (6 prompts, thinking off and on) at 200 and 1,024 tokens; +- 4 sampled rows with fixed seeds (temperature 1, top-p 0.95; and temperature 0.7, top-p 0.9, top-k 40); +- a greedy row with logprobs (top 5); +- a tool call; +- one image. + +A request that asks for logprobs decodes one token a step on an assisted pair. The assistant drafts only for +requests whose sampler admits speculative verification (`ClusterWorkerSampling.admitsSpeculativeVerification`: no +logprobs, no penalties, no logit bias), and media rows keep the target path +(`QwenTensorParallelNativeBatchExecutor`). So on one loaded pair, the same request with and without logprobs compares +the assistant's rounds with that pair's plain one-token path, with the same shares, weights, prefix state and build. + +| Check | Result | +|---|---| +| Greedy, the 12 prompts at 200 tokens: speculative rounds against the same pair's plain steps (the same request with logprobs) | **12 of 12 identical** | +| Greedy, the 12 prompts at 1,024 tokens (answers of 47 to 608 tokens, each to its natural end), the same comparison | **12 of 12 identical** | +| Greedy repeatability: the assisted pair twice; the plain pair twice | 12 of 12 each | +| Sampled rows (fixed seeds), speculative against the same pair's plain steps | **4 of 4 identical** | +| Tool call, speculative against plain steps | identical, apart from the random tool-call ID | +| Image row | identical: media rows run the target path | +| Logprobs row | runs the plain path by design; repeatable | +| c1 = c4 (`cn_equal`, 256 tokens, every third row sampled): assisted pair | 4 of 4 equal to each row's solo answer | + +A pair planned without the assistant gives other answers than the assisted pair for 8 of the 12 greedy prompts. The +logprobs row shows why. On both pairs it decodes one token a step, with no speculation, and still differs from the +first token on: −0.070116 against −0.070133 for the first token, at most 0.061 apart over 160 tokens. The first token +comes from the prompt's last row, before any draft. The local plan with the assistant split the layers 2:3 +(`0-64@2|0-64@3`). The plan without it, made for Darkbloom, split them equally. Each split sums the row-parallel +partials over different shards. The rounding difference that follows flips near-ties later in an answer. The +assistant does not cause it. Through Darkbloom both setups use equal shares. + +## Speed on this pair (decode tok/s, one request; four at once in total) + +Over the leader's local API, the same build, the same hour (256-token answers): + +| Setup | One request | Four at once (total) | First token | Prefill, 2K / 8K prompt | +|---|---:|---:|---:|---| +| Plain tensor parallel (equal shares) | 17.4 | 41.2 | 0.38 s | 516 / 558 tok/s | +| With the assistant (2:3 shares) | 39.7 | 47.6 | 0.38 s | 506 / 501 tok/s | + +Decode at the 2K and 8K prompts: 16.6 and 16.4 tok/s plain, against 42.3 and 46.7 with the assistant. + +The two rows are not like for like: the plain plan split the layers equally and the assisted one 2:3. The ratio +(2.3×) mixes the assistant's speed-up with the split's. The first DevNet build with this declaration measures both +through Darkbloom on equal shares. + +On build `0.10.7-dev.branch.93`, with the 2:3 split: 25.3 with the assistant (four at once: 34.1). +The Apple M5 Max alone (single-Mac product path, MTP on) decoded 69.3–73.6 on build `0.10.7-dev.branch.92`. + +## What this does not establish + +- No request went through Darkbloom with the assistant: this build refuses it there. The first DevNet build that + carries this declaration must repeat the same-request comparison through Darkbloom on equal shares. +- No run on two Apple M5 Ultras. +- Widths beyond four at once, prompts beyond 8,192 tokens, and the one-chunk-lookahead prefill schedule (the assistant + requires serial prefill). +- How fast the pair is against one Mac. On this pair the M5 Max alone is still faster, for both plain and assisted + tensor parallel. + +## Where it is used + +`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift` declares the assistant +on the Qwen3.8-27B entry, with this file's SHA-256 (`ClusterPublicTensorAssistantTests` checks the digest). From that +declaration: +- a setup saved for coordinator pairing may carry exactly this policy (`ClusterConfiguration.validate`); +- the guided setup plans it under `mtp_mode = "auto"` (`ClusterPlacementTensorAssistantSelection.readAutomatic`); +- a release's cluster runtime facts, the coordinator's approval and every committed start carry it in the model's + resource policy (`DistributedInstalledNativeStart.resourcePolicySHA256`); +- the model's serial-schedule tensor-parallel parity qualification carries this file's digest + (`ClusterRuntimeApprovalFacts.parityQualifications`). diff --git a/docs/reports/README.md b/docs/reports/README.md index ea59d1aab7..17e9d236ac 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -1,10 +1,11 @@ # Provider And Native Evidence -> Last updated: 2026-11-01 +> Last updated: 2026-11-05 Dated records and raw native evidence retain their original content, revisions and limitations. A record is not a fresh test result or proof of private platform compatibility. - [Gemma pipeline prompt experts](2026-11-01-gemma-pipeline-prompt-experts.md) - the registered Gemma stages' prompt expert blocks in one shared dispatch with the same bytes: CPU and M5 Ultra GPU equality evidence and synthetic one-layer timings; no pair or qualification result. +- [Qwen3.8-27B public tensor assistant](2026-11-05-qwen27-public-assistant.md) - the parity evidence of Qwen3.8-27B's resident assistant on tensor-parallel pairs served through Darkbloom: same-request speculative and plain decodes on one pair, sampling, tools, images and logprobs; the evidence document of `ClusterPublicModels.qwen27TensorAssistant`. - [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash, Qwen3.8-27B, MiMo-V2.6-Flash and Gemma 4 26B QAT for public cluster traffic in pipeline and tensor parallel, the checks it rests on and why releases carry pair-serving grants; the evidence document of `ClusterPublicModels`. - [Mixed-step prefill geometry](2026-10-21-mixed-step-prefill-geometry.md) - load, engine, inter-token latency and KV-subtracted activation measurements behind Gemma 4's 2,048 / 4,096 prompt geometry, its media ceiling and the GPT-OSS and dense Qwen opt-in. - [GLM-5.3-Flash single-Mac qualification record](2026-10-21-glm53-flash-single-mac-qualification.md) diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift index c175f5d889..e1c7f3a07b 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/GemmaCheck.swift @@ -12,6 +12,7 @@ import MLX // darkbloom-cluster-tp-check gemma run --mode full|split-sum|simulated|shard|tp --model-dir DIR --request FILE --report FILE // [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R] // [--pack yes|no] [--path legacy|paged] [--prefix none|repeat] [--deadline-seconds S] +// [--layer-stride N (paged path, full/shard/tp: decode submitted every N layers, 0 = whole step; default the product's)] // darkbloom-cluster-tp-check gemma compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U] // darkbloom-cluster-tp-check gemma allsum [--backend ring|socket|jaccl] [--count N] // darkbloom-cluster-tp-check gemma lanes --mode simulated|tp --model-dir DIR --report FILE [--lanes N] [--outputs N] @@ -147,7 +148,8 @@ enum GemmaCheck { ["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"), ["yes", "no"].contains(fields["--pack"] ?? "yes"), ["legacy", "paged"].contains(fields["--path"] ?? "legacy"), - ["none", "repeat"].contains(fields["--prefix"] ?? "none") else { + ["none", "repeat"].contains(fields["--prefix"] ?? "none"), + fields["--layer-stride"].map({ Int($0).map { (0 ... 64).contains($0) } ?? false }) ?? true else { throw Failure("gemma run needs --mode full|split-sum|simulated|shard|tp, --model-dir, --request, a new --report and bounded options") } let paged = (fields["--path"] ?? "legacy") == "paged" @@ -159,6 +161,10 @@ enum GemmaCheck { let sealed = (fields["--reduction"] ?? "native") == "sealed-bench" guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") } let pack = (fields["--pack"] ?? "yes") == "yes" + let layerStride = fields["--layer-stride"].flatMap { Int($0) } + guard layerStride == nil || (paged && Gemma4TensorParallelModel.benchLayerStrideApplies(mode: mode)) else { + throw Failure("--layer-stride applies to the paged path of a full, shard or tp rank (simulated ranks run on their own threads)") + } try ProcessForcedExit.routeTerminationSignals() ProcessNativeMemoryRelease.installForForcedExit() try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000, @@ -198,7 +204,7 @@ enum GemmaCheck { reduction = g note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")") // Everything that changes the collectives is agreed before loading. - let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" + let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|stride=\(layerStride.map(String.init) ?? "product")|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))" guard try g.digestsEqual(fnv(workload)) else { throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract") } @@ -216,7 +222,7 @@ enum GemmaCheck { packFeedForward: pack) note("loaded in \(String(format: "%.2f", model.loadSeconds)) s, \(model.loadedParameterBytes) parameter bytes") if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } } - let generation: Gemma4TensorParallelModel.Generation + var generation: Gemma4TensorParallelModel.Generation! var pairAgrees: Bool? var prefixOutcome: (reused: Int, equalsCold: Bool)? func bitsEqual(_ a: Gemma4TensorParallelModel.Generation, _ b: Gemma4TensorParallelModel.Generation) -> Bool { @@ -225,45 +231,52 @@ enum GemmaCheck { && bits(a.topLogprobs) == bits(b.topLogprobs) && a.finalLogits.map { $0.map(\.bitPattern) } == b.finalLogits.map { $0.map(\.bitPattern) } } - if repeatPrefix { - let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize - let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)] - if let pair { + try Gemma4TensorParallelModel.withLayerStride(layerStride) { + if repeatPrefix { + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)] + if let pair { + let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, + role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) + runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, + chunk: chunk, recordTop: recordTop) + return (value.cold, value.restored, value.reusedPromptTokens) + } + pairAgrees = bitsEqual(runs[0].restored, runs[1].restored) + } else { + let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk, + recordTop: recordTop) + runs = [(value.cold, value.restored, value.reusedPromptTokens)] + } + generation = runs[0].restored + prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) }) + note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)") + } else if let pair { let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) - runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in - let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, - chunk: chunk, recordTop: recordTop) - return (value.cold, value.restored, value.reusedPromptTokens) + let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize + let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in + paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) + : try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) } - pairAgrees = bitsEqual(runs[0].restored, runs[1].restored) + func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } + pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits) + && bits(both[0].topLogprobs) == bits(both[1].topLogprobs) + && both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) } + generation = both[0] } else { - let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk, - recordTop: recordTop) - runs = [(value.cold, value.restored, value.reusedPromptTokens)] - } - generation = runs[0].restored - prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) }) - note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)") - } else if let pair { - let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory, - role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)]) - let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize - let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in - paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) - : try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop) + generation = paged + ? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop) + : try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount, + chunk: request.chunkSize, recordTop: recordTop) } - func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } } - pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits) - && bits(both[0].topLogprobs) == bits(both[1].topLogprobs) - && both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) } - generation = both[0] - } else { - generation = paged - ? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount, - chunk: request.chunkSize, recordTop: recordTop) - : try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount, - chunk: request.chunkSize, recordTop: recordTop) + } + if !generation.stepSeconds.isEmpty { + let steps = generation.stepSeconds.sorted() + note(String(format: "decode stride=%@ step_ms_p50=%.3f step_ms_min=%.3f steps=%d", layerStride.map(String.init) ?? "product", + steps[steps.count / 2] * 1000, steps[0] * 1000, steps.count)) } var report = Report(mode: mode, role: mode == "simulated" ? "simulated-tp2" : role.label, rank: group?.rank ?? (mode == "shard" ? shardRank : 0), diff --git a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift index 8fea759d74..d77d1fd13d 100644 --- a/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift +++ b/libs/darkbloom-cluster-worker/Sources/TensorParallelCheck/QwenDecodeCheck.swift @@ -2,13 +2,17 @@ import DarkbloomClusterRuntime import Foundation import MLX -// The batch driver's plain decode on two ranks of one Mac (`QwenTensorParallelDecodeBench`): +// The batch driver's plain decode on two ranks (`QwenTensorParallelDecodeBench`), of one Mac over the loopback +// ring or socket, or of two Macs over JACCL (`--backend jaccl`, with the JACCL_* environment of a pair): // MLX_RANK=0|1 MLX_HOSTFILE=hosts.json darkbloom-cluster-tp-check qwen-decode --model-dir /DIR \ -// [--backend ring|socket] [--reduction native|sealed-bench] [--width 1] [--prompt-tokens 32] \ -// [--output-tokens 64] [--sampled 0|1] [--control exchanged,folded] [--repeats 3] [--answer-delay-us 0] +// [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--width 1] [--prompt-tokens 32] \ +// [--output-tokens 64] [--sampled 0|1] [--control exchanged,folded] [--repeats 3] [--answer-delay-us 0] \ +// [--layer-strides 1,8,16 (decode layer strides to compare, 0 = whole step; default: the product's, +// `QwenTensorParallelLaunch.decodeLayerStride`)] \ +// [--build-ahead 0,1 (read-then-build and/or the driver's build-ahead, folded control only; default 0)] // Each rank logs every run's decode step time and token digest; both agree // that every run retired the same tokens. Loopback timings show a step's host -// work and synchronization, never a pair's. +// work and synchronization, never a pair's; JACCL timings are the pair's. enum QwenDecodeCheck { static func run(_ arguments: [String]) throws { var options: [String: String] = [:] @@ -23,12 +27,25 @@ enum QwenDecodeCheck { guard let directory = options["model-dir"], directory.hasPrefix("/") else { throw Failure("qwen-decode needs --model-dir /DIR") } - guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring"), backend != .jaccl else { - throw Failure("qwen-decode runs on the loopback ring or socket only") + guard let backend = QwenTensorParallelGroup.Backend(rawValue: options["backend"] ?? "ring") else { + throw Failure("qwen-decode takes --backend ring, socket or jaccl") } + let strides: [Int?] = try options["layer-strides"].map { list in + try list.split(separator: ",", omittingEmptySubsequences: false).map { text -> Int? in + guard let value = Int(text), (0...64).contains(value) else { throw Failure("--layer-strides takes 0-64 each") } + return value + } + } ?? [nil] let reduction = options["reduction"] ?? "sealed-bench" guard ["native", "sealed-bench"].contains(reduction) else { throw Failure("--reduction takes native or sealed-bench") } let controls = (options["control"] ?? "exchanged,folded").split(separator: ",").map(String.init) + let aheads = try (options["build-ahead"] ?? "0").split(separator: ",").map { value -> Bool in + guard value == "0" || value == "1" else { throw Failure("--build-ahead takes 0, 1 or 0,1") } + return value == "1" + } + guard !aheads.contains(true) || controls == ["folded"] else { + throw Failure("--build-ahead 1 runs with --control folded only") + } guard let width = Int(options["width"] ?? "1"), (1...8).contains(width), let prompt = Int(options["prompt-tokens"] ?? "32"), prompt > 0, let output = Int(options["output-tokens"] ?? "64"), output > 1, @@ -42,7 +59,7 @@ enum QwenDecodeCheck { let url = URL(fileURLWithPath: directory) let configuration = try Data(contentsOf: url.appendingPathComponent("config.json")) let group = try QwenTensorParallelGroup(backend: backend) - let work = "\(reduction)|\(width)|\(prompt)|\(output)|\(sampled)|\(controls)|\(repeats)|\(delay)" + let work = "\(reduction)|\(width)|\(prompt)|\(output)|\(sampled)|\(controls)|\(repeats)|\(delay)|\(strides.map { $0.map(String.init) ?? "product" })|ahead=\(aheads)" guard try group.digestsEqual(fnv(sha256Hex(configuration) + "|" + work)) else { throw Failure("the ranks disagree on the checkpoint or the runs") } @@ -56,11 +73,18 @@ enum QwenDecodeCheck { let same = try Device.withDefaultDevice(.gpu) { () throws -> Bool in let model = try QwenTensorParallelModel.load(modelDirectory: url, role: .shard(rank: group.rank, size: 2), reduction: group) - return try QwenTensorParallelDecodeBench.pair(model: model, configuration: configuration, group: group, - width: width, promptTokens: prompt, outputTokens: output, sampled: sampled == 1, - folds: controls.map { $0 == "folded" }, repeats: repeats, answerDelayMicroseconds: delay) { line in - FileHandle.standardOutput.write(Data((line + "\n").utf8)) + var same = true + for stride in strides { + let label = stride.map(String.init) ?? "product" + note("decode layer stride \(label)") + same = try QwenTensorParallelDecodeBench.pair(model: model, configuration: configuration, group: group, + width: width, promptTokens: prompt, outputTokens: output, sampled: sampled == 1, + folds: controls.map { $0 == "folded" }, repeats: repeats, answerDelayMicroseconds: delay, + layerStride: stride, buildsAhead: aheads) { line in + FileHandle.standardOutput.write(Data((line + " stride=\(label)\n").utf8)) + } && same } + return same } let both = try group.exchangeIntegers([same ? 1 : 0]) == [2] note("both ranks retired the same tokens in every run: \(both)") diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift index 4e13be0661..17e9d29aba 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterServedSpeed.swift @@ -67,8 +67,28 @@ public struct ClusterServedSpeedRecords: Codable, Equatable, Sendable { /// its own builds served (`servedBy`). Nil in a record written before /// builds were recorded, which counts as another build's. public let rankBuildSHA256: [String]? - public init(modelID: String, mode: String, cut: String, ranks: [String]? = nil, rankBuildSHA256: [String]? = nil) { + /// Through Darkbloom or the leader's local API (`ClusterPairRequestTelemetry.serving`); nil in a record + /// written before it was recorded. + public let serving: ClusterServedScope? + /// Whether the setup decoded with Qwen's resident tensor assistant; nil in an older record. + public let tensorAssistant: Bool? + public init(modelID: String, mode: String, cut: String, ranks: [String]? = nil, rankBuildSHA256: [String]? = nil, + serving: ClusterServedScope? = nil, tensorAssistant: Bool? = nil) { self.modelID = modelID; self.mode = mode; self.cut = cut; self.ranks = ranks; self.rankBuildSHA256 = rankBuildSHA256 + self.serving = serving; self.tensorAssistant = tensorAssistant + } + + /// Whether a plan that will serve `serving`, with Qwen's tensor assistant in tensor parallel when + /// `tensorAssistant`, may take this setup's speeds: it was served the same way, and a tensor-parallel setup + /// decoded with the assistant exactly when the plan will. A speed served locally with the assistant (pair-2's + /// Qwen: 34-36 tok/s) says nothing of tensor parallel through Darkbloom without it (14-20), and the + /// served race reads each mode at its fastest setup (`ClusterServedModes.figures`). A record written + /// before these were recorded is read as before: it is an earlier build's, which `servedBy` already leaves + /// out of every plan of a build that records them. + public func servedAs(_ serving: ClusterServedScope, tensorAssistant: Bool) -> Bool { + guard self.serving.map({ $0 == serving }) ?? true else { return false } + guard mode == ClusterGenerationMode.tensorParallel.rawValue, let assisted = self.tensorAssistant else { return true } + return assisted == tensorAssistant } /// Whether every rank of this setup ran the worker build `builds` names @@ -222,6 +242,12 @@ public struct ClusterServedSpeedRecords: Codable, Equatable, Sendable { return (current, entries.count - current.count) } + /// The entries a plan that will serve `serving` (with Qwen's tensor assistant when `tensorAssistant`) may use + /// (`Setup.servedAs`). + public static func servedAs(_ serving: ClusterServedScope, tensorAssistant: Bool, _ entries: [Entry]) -> [Entry] { + entries.filter { $0.setup.servedAs(serving, tensorAssistant: tensorAssistant) } + } + /// The plan's one line for `count` records left out because another worker /// build served them (`servedBy`); nil when there were none. public static func otherBuildsLine(_ count: Int, builds: [String: String]) -> String? { @@ -496,6 +522,11 @@ public enum ClusterServedCalibration { var setups: [ClusterServedSpeedRecords.Setup] = [] for entry in entries where !setups.contains(entry.setup) { setups.append(entry.setup) } for setup in setups { + // Device rates are one-token rates; nothing here knows the speed-up of Qwen's tensor assistant. + guard setup.tensorAssistant != true else { + lines.append(" \(setup.mode) cut \(setup.cut): skipped (decoded with Qwen's tensor assistant, not one token a step)") + continue + } guard let ranks = setup.ranks, let mode = ClusterGenerationMode(rawValue: setup.mode), let cuts = ClusterServedSpeedRecords.Setup.cuts(setup.cut, layerCount: layout.layerCount, mode: mode, ranks: ranks.count), cuts.count == mode.layerCutCount(ranks: ranks.count) else { @@ -512,7 +543,8 @@ public enum ClusterServedCalibration { // record per device). if mode.usesSpeculativeHead, !mode.isPhaseSplit, let decoder = ordered.last { let plainSetup = ClusterServedSpeedRecords.Setup(modelID: setup.modelID, mode: ClusterGenerationMode.pipeline.rawValue, - cut: setup.cut, ranks: setup.ranks, rankBuildSHA256: setup.rankBuildSHA256) + cut: setup.cut, ranks: setup.ranks, rankBuildSHA256: setup.rankBuildSHA256, serving: setup.serving, + tensorAssistant: setup.tensorAssistant) if let plain = median(entries.filter { $0.setup == plainSetup && $0.sample.route == .pair }.compactMap(\.sample.decodeTokensPerSecond)), let rounds = median(samples.filter { $0.route == .pair }.compactMap(\.decodeTokensPerSecond)) { speculativeFactors.append((decoder, rounds / plain)) diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServedSpeedRule.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServedSpeedRule.swift index d75329b398..1fb386716c 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServedSpeedRule.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterServedSpeedRule.swift @@ -14,3 +14,13 @@ public enum ClusterServedSpeedRule { public static let minimumCompletionTokens = 64 } + +/// How a served request reached the pair: through Darkbloom (a coordinator-paired +/// setup) or the leader's own local API. A speed record names it, and a plan uses +/// only the records served the way the plan will serve (`ClusterServedSpeedRecords.Setup.servedAs`): +/// the two ways can run different decode paths (Qwen's tensor assistant served +/// locally only before a build declared it public), and their loads differ. +public enum ClusterServedScope: String, Codable, Sendable { + case darkbloom + case local +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterPairTelemetry.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterPairTelemetry.swift index 2564277784..638b813c9f 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterPairTelemetry.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRemote/ClusterPairTelemetry.swift @@ -62,12 +62,20 @@ public struct ClusterPairRequestTelemetry: Codable, Sendable, Equatable { /// (`ClusterServedSpeedRecords.servedBy`). Nil in a record written before /// builds were recorded: such a record counts as another build's. public let rankBuildSHA256: [String]? + /// Whether the request came through Darkbloom or the leader's local API. Nil in a record written before it was + /// recorded: `ClusterServedSpeedRecords.Setup.servedAs` reads it as served either way, and `servedBy` already + /// leaves it out of every plan of a build that records it (its worker build is an earlier one). + public let serving: ClusterServedScope? + /// Whether the setup decoded with Qwen's resident tensor assistant, the one speculative decoder that neither the + /// generation mode nor the model fixes (`ClusterQwenTensorAssistantPolicy`). Nil in an older record. + public let tensorAssistant: Bool? public init(requestID: String, finishedAt: Double, modelID: String, mode: String, cut: String, promptTokens: Int, cachedTokens: Int, completionTokens: Int, firstTokenMilliseconds: Double?, decodeTokensPerSecond: Double?, handoffMilliseconds: Double?, handoffBytes: Int?, mtpDrafted: Int?, mtpAccepted: Int?, outcome: String, route: String? = nil, routeReason: String? = nil, - ranks: [String]? = nil, concurrentRequests: Int? = nil, rankBuildSHA256: [String]? = nil) { + ranks: [String]? = nil, concurrentRequests: Int? = nil, rankBuildSHA256: [String]? = nil, + serving: ClusterServedScope? = nil, tensorAssistant: Bool? = nil) { self.requestID = requestID; self.finishedAt = finishedAt; self.modelID = modelID; self.mode = mode self.cut = cut; self.promptTokens = promptTokens; self.cachedTokens = cachedTokens self.completionTokens = completionTokens; self.firstTokenMilliseconds = firstTokenMilliseconds @@ -82,6 +90,7 @@ public struct ClusterPairRequestTelemetry: Codable, Sendable, Equatable { self.ranks = ranks.flatMap { $0.count <= 8 && $0.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 64 }) ? $0 : nil } self.concurrentRequests = concurrentRequests.map { max(0, $0) } self.rankBuildSHA256 = rankBuildSHA256.flatMap { (1...8).contains($0.count) && $0.allSatisfy(Self.isBuild) ? $0 : nil } + self.serving = serving; self.tensorAssistant = tensorAssistant } /// A worker build's SHA-256: 64 lowercase hexadecimal digits. @@ -185,7 +194,8 @@ public struct ClusterServedSpeedFile: Codable, Sendable, Equatable { guard value.isSpeedRecord else { return records } var result = records + [value] func key(_ r: ClusterPairRequestTelemetry) -> String { - [r.modelID, r.mode, r.cut, r.route ?? "pair", (r.ranks ?? []).joined(separator: ",")].joined(separator: "\u{1f}") + [r.modelID, r.mode, r.cut, r.route ?? "pair", (r.ranks ?? []).joined(separator: ","), r.serving?.rawValue ?? "", + r.tensorAssistant.map(String.init) ?? ""].joined(separator: "\u{1f}") } let same = result.indices.filter { key(result[$0]) == key(value) } if same.count > keptPerRoute { diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift index b19c02d43a..03a4ea11a7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelPagedSession.swift @@ -152,15 +152,9 @@ final class Gemma4TensorParallelPagedSession { throw ProbeError("Gemma tensor-parallel decode step differs from its request or pages") } let input = MLXArray([Int32(token)]).reshaped([1, 1]) - let text = model.textModel var logits: MLXArray? - let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride let output = try state.run(tokenCount: 1, check: check, forward: { caches, _ in - let row = Gemma4LayerSubmission.$stride.withValue(stride) { - Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) { - text(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...] - } - } + let row = decodeRow(input, caches: caches) logits = row return select(row) }, validateOutput: { _ in }) @@ -169,6 +163,41 @@ final class Gemma4TensorParallelPagedSession { return (logits, output) } + /// One decode step on the agreed token of the previous step's lazy + /// selection (`Gemma4TensorParallelChoice.build`, greedy: the token is its + /// first element), submitted and committed before that selection is read + /// (`CBv2OwnedRequestState.submit`), so the GPU and the collectives run + /// this step while the host reads the last one. The same graph as + /// `decode` on the read token: every value and token is unchanged. + func submitDecode(after selected: MLXArray, check: () throws -> Void, + select: (MLXArray) -> MLXArray) throws -> (logits: MLXArray, selected: MLXArray) { + guard !retired, state.committedTokens >= promptCount, selected.ndim == 1, selected.dim(0) >= 1, + pagesCover(writing: 1) || reservePages(writing: 1) else { + throw ProbeError("Gemma tensor-parallel decode step differs from its request or pages") + } + let input = selected[0 ..< 1].asType(.int32).reshaped([1, 1]) + var logits: MLXArray? + let output = try state.submit(tokenCount: 1, check: check, forward: { caches, _ in + let row = decodeRow(input, caches: caches) + logits = row + return select(row) + }) + guard let logits else { throw ProbeError("Gemma tensor-parallel decode produced no logits") } + try Self.validate(logits, rows: 1, model: model) + return (logits, output) + } + + /// One decode row's logits on `input` (`[1, 1]`) at the decode layer + /// stride: `decode`'s and `submitDecode`'s forward. + private func decodeRow(_ input: MLXArray, caches: [any CBv2AttendingLayerCache]) -> MLXArray { + let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride + return Gemma4LayerSubmission.$stride.withValue(stride) { + Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) { + model.textModel(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...] + } + } + } + /// One decode step of each of `sessions` (distinct requests on one model's /// host), a row each, in one forward under the explicit batch decode scope /// (`Gemma4BatchDecodeScope`: every row keeps each projection's singleton @@ -234,6 +263,17 @@ extension Gemma4TensorParallelModel { static let decodeLayerStride = 1 /// A bench or test's own stride (0: the whole step in one evaluation). @TaskLocal static var layerStride: Int? + /// Runs `body` with a bench's own decode layer stride (`layerStride`; nil: + /// the product's `decodeLayerStride`), to compare strides on a pair + /// (`darkbloom-cluster-tp-check gemma run --layer-stride`). + public static func withLayerStride(_ stride: Int?, _ body: () throws -> R) rethrows -> R { + try $layerStride.withValue(stride, operation: body) + } + /// The bench modes a `withLayerStride` stride reaches: ranks that decode + /// on the calling thread (`full`, `shard`, `tp`). `simulated` runs both + /// ranks on `Gemma4TensorParallelLocalPair`'s own threads, which never see + /// the stride, so a stride there is refused instead of silently ignored. + public static func benchLayerStrideApplies(mode: String) -> Bool { ["full", "shard", "tp"].contains(mode) } /// Greedy generation as `generate`, on this model's paged KV through the /// resident runtime's own request path (`Gemma4TensorParallelPagedSession`, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift index b3fa291709..fb3a750dd9 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Gemma4/TensorParallel/Gemma4TensorParallelRequestLoop.swift @@ -1,14 +1,23 @@ import DarkbloomClusterProtocol import Foundation import MLX +import MLXLMCommon /// One request on one rank of a Gemma 4 tensor-parallel pair, as the resident /// runtime serves it alone: the prompt in chunks of the request's own size /// (from a restored prefix's boundary, when both ranks restored one), then -/// one decode step a token. Each step's token and both ranks' stop flags +/// one decode step a token (`TensorParallelOneTokenLoop`, GLM tensor +/// parallel's step order). Each step's token and both ranks' stop flags /// are agreed in the step's own evaluation (`Gemma4TensorParallelChoice`); /// both ranks submit the same collectives in the same order whatever either -/// decides, and end after the same step. +/// decides, and end after the same step. Each step is built one ahead, on +/// the previous step's lazy agreed token +/// (`Gemma4TensorParallelPagedSession.submitDecode`), so the GPU and the +/// collectives run it while the host reads the previous one: greedy and +/// sampled requests (rank 0's keyed draw is the one made at its output index +/// with the history up to it), but not a greedy request asking for logprobs +/// (`pipelines`). A step built after the request ended is evaluated; its +/// token is never committed or published. /// /// Rank 0 publishes each token at once and reads the owner's answer to it /// after the next step ran; a stop answer is acted on one step later (the @@ -37,18 +46,48 @@ struct Gemma4TensorParallelRequestLoop { var pagesRefused: Bool } + /// One built step: its logits, its agreement (`Gemma4TensorParallelChoice.build`) + /// and, on rank 0 of a sampled request asking for them, its draw's + /// logprobs as graph nodes (kept with the step, as the next step's draw + /// may be built before this one is read). + struct Step { + let logits: MLXArray + let selected: MLXArray + let logprobs: CBv2StepLogprobs? + } + + /// Whether `choice`'s steps are built one ahead: greedy and sampled + /// requests alike (each draw is keyed on its output index and its + /// history on the device, `QwenStageTokenSampler.sample`). A greedy + /// request asking for logprobs reads each step before building the next: + /// its logprobs come from a vocabulary-split top-k gather, a collective + /// evaluated on the host after the step's token is agreed, which would + /// wait for the step built ahead and gain nothing. + static func pipelines(_ choice: Gemma4TensorParallelChoice) -> Bool { + if let buildsAhead { return buildsAhead } + return choice.gathersRow || choice.sampler?.wire.capturedLogprobs == nil + } + /// Tests only: a test's own order (nil: `pipelines`'s). The product never sets it. + @TaskLocal static var buildsAhead: Bool? + func run(channel: ClusterCommittedTokenChannel, check: () throws -> Void) throws -> Outcome { let rank = choice.rank, prompt = request.promptTokenIDs let sampler = choice.sampler // A restored prefix ends on the chunk grid: the rest runs the chunks a cold request runs there. var offset = session.committedTokens - var current: (logits: MLXArray, selected: MLXArray)? + /// A built step, with rank 0's sampled draw's logprobs taken now. + func built(_ step: (logits: MLXArray, selected: MLXArray)) -> Step { + let logprobs = rank == 0 && choice.gathersRow ? sampler?.takePendingStepLogprobs() : nil + return Step(logits: step.logits, selected: step.selected, logprobs: logprobs) + } + var current: Step? while offset < prompt.count { let end = min(prompt.count, offset + request.chunkSize) - current = try session.prefill(prompt, range: offset ..< end, check: check) { choice.build($0, stop: 0) } ?? current + current = try session.prefill(prompt, range: offset ..< end, check: check) { choice.build($0, stop: 0) } + .map(built) ?? current offset = end } - guard var step = current else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") } + guard let step = current else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") } var tokens: [Int] = [] var finish: ClusterWorkerFinishReason = .length var clientStopped = false @@ -61,9 +100,10 @@ struct Gemma4TensorParallelRequestLoop { if try !channel.answer(), stopKeep == 0 { clientStopped = true; stopKeep = Float(tokens.count) } } let logprobCount = sampler?.wire.capturedLogprobs + var stepLogprobs: ClusterWorkerTokenLogprobs? /// Commits one agreed token on this rank (and publishes it on rank 0): /// the request's own end at it (EOS or length), else nil. - func commit(_ value: Int, logprobs: ClusterWorkerTokenLogprobs?) throws -> ClusterWorkerFinishReason? { + func commit(_ value: Int, logprobs: ClusterWorkerTokenLogprobs?) throws -> QwenTensorParallelStopRule.Finish? { tokens.append(value) if rank == 0 { try channel.publishToken(tokens.count - 1, value, prompt.count + tokens.count - 1, logprobs) @@ -76,59 +116,58 @@ struct Gemma4TensorParallelRequestLoop { case .clientStop, .proceed: return nil } } - try GPU.withCommandBufferLimits(Gemma4TensorParallelModel.decodeCommandBuffers) { - steps: for index in 0 ..< request.outputCount { - // The answer to the last token arrived while this step ran. - if stopKeep == 0 { try readAnswer() } - let agreed = try choice.read(step.selected) - if let slot = agreed.flags.filter({ $0 > 0 }).min() { - // A rank asked both to stop: both keep the tokens it named - // and end here (at the request's length when its pages could not grow). - let stop = QwenTensorParallelStopRule.stop(slot: slot) - tokens = Array(tokens.prefix(stop.keep)) - finish = stop.finish == .length ? .length : .clientStop - break steps - } - // A greedy step's logprobs come from the split top-k gather, a - // collective every rank takes; a sampled one's from rank 0's draw. - var logprobs: ClusterWorkerTokenLogprobs? - if let count = logprobCount { + try withoutActuallyEscaping(check) { check in + // Steps are built one ahead (`TensorParallelOneTokenLoop`, GLM's step order): the next step is submitted + // on this step's lazy agreed token before the host reads it (`pipelines`). + let pipelined = Self.pipelines(choice) + let steps = TensorParallelOneTokenLoop( + outputCount: request.outputCount, stopTokenIDs: request.stopTokenIDs, pipelined: pipelined, + step: { current, stop in + let select: (MLXArray) -> MLXArray = { choice.build($0, stop: stop) } + return try built(pipelined ? session.submitDecode(after: current.selected, check: check, select: select) + : session.decode(choice.read(current.selected).token, check: check, select: select)) + }, + read: { current in + let agreed = try choice.read(current.selected) + return (agreed.token, agreed.flags) + }, + evaluate: { eval($0.selected); try check() }, + // Pages grow a granule ahead, at least a margin before they are + // needed: a growth the pool refuses still leaves the next step its + // row, and a later step carries the length stop (rank-local; the + // collectives are the same either way). + growPages: { if !pagesRefused { pagesRefused = !session.reservePages(writing: 1) } }, + pagesRefused: { pagesRefused }, + stopKeep: { stopKeep }, setStopKeep: { stopKeep = $0 }, readAnswer: readAnswer, + committed: { tokens.count }, keep: { tokens = Array(tokens.prefix($0)) }, + agreedStep: { current, token in + // A greedy step's logprobs come from the split top-k gather, a + // collective every rank takes, a stopped rank too; a sampled + // one's from rank 0's draw. + stepLogprobs = nil + guard let count = logprobCount else { return } if choice.gathersRow { if rank == 0, stopKeep == 0 { - guard let drawn = sampler?.takePendingLogprobs() else { + guard let drawn = current.logprobs else { throw ProbeError("Gemma tensor-parallel token has no logprobs") } - logprobs = drawn + stepLogprobs = QwenStageTokenSampler.tokenLogprobs(drawn) } } else { - let gathered = try choice.logprobs(step.logits, token: agreed.token, maximum: agreed.maximum, - count: count) - logprobs = rank == 0 ? gathered : nil - } - } - if stopKeep == 0 { - sampler?.commit(agreed.token) - if let end = try commit(agreed.token, logprobs: logprobs) { finish = end; break steps } - if localStop() { - stopKeep = Float(tokens.count) - } else if pagesRefused { - stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) + let maximum = try choice.read(current.selected).maximum + let gathered = try choice.logprobs(current.logits, token: token, maximum: maximum, count: count) + stepLogprobs = rank == 0 ? gathered : nil } - } else if request.stopTokenIDs.contains(agreed.token) { - // The owner's stop was read after this step ran, so only the - // next step could carry it; the peer ends at this token. - break steps - } - guard index + 1 < request.outputCount else { break steps } - // Pages grow a granule ahead, at least a margin before they are - // needed: a growth the pool refuses still leaves this step its - // row, and the step carries the length stop (rank-local; the - // collectives are the same either way). - if !pagesRefused { - pagesRefused = !session.reservePages(writing: 1) - if pagesRefused, stopKeep == 0 { stopKeep = QwenTensorParallelStopRule.lengthStop(keep: tokens.count) } + }, + commit: { _, token in + sampler?.commit(token) + return try commit(token, logprobs: stepLogprobs) + }, + localStop: localStop) + try GPU.withCommandBufferLimits(Gemma4TensorParallelModel.decodeCommandBuffers) { + if let ended = try steps.run(first: step) { + finish = ended == .eos ? .eos : ended == .length ? .length : .clientStop } - step = try session.decode(agreed.token, check: check) { choice.build($0, stop: stopKeep) } } } // The owner answers every published token, the last one too. A stop diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTool+Served.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTool+Served.swift index fe390b9372..f7aff0a1ed 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTool+Served.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Placement/ClusterPlacementTool+Served.swift @@ -41,6 +41,9 @@ extension ClusterPlacementTool { let concurrentRequests: Int? /// The worker build of each rank (`ClusterPairRequestTelemetry.rankBuildSHA256`); nil before builds were recorded. let rankBuildSHA256: [String]? + /// `ClusterPairRequestTelemetry.serving` and `tensorAssistant`; nil before they were recorded. + let serving: ClusterServedScope? + let tensorAssistant: Bool? } let schema: String let records: [Record] @@ -60,7 +63,8 @@ extension ClusterPlacementTool { result += records.entries.map { entry in guard let ranks, entry.setup.ranks == nil else { return entry } return .init(setup: .init(modelID: entry.setup.modelID, mode: entry.setup.mode, cut: entry.setup.cut, ranks: ranks, - rankBuildSHA256: entry.setup.rankBuildSHA256), + rankBuildSHA256: entry.setup.rankBuildSHA256, serving: entry.setup.serving, + tensorAssistant: entry.setup.tensorAssistant), sample: entry.sample) } continue @@ -75,7 +79,8 @@ extension ClusterPlacementTool { firstTokenMilliseconds: record.firstTokenMilliseconds, decodeTokensPerSecond: record.decodeTokensPerSecond, outcome: record.outcome, finishedAt: record.finishedAt) else { continue } result.append(.init(setup: .init(modelID: record.modelID, mode: record.mode, cut: record.cut, ranks: record.ranks ?? ranks, - rankBuildSHA256: record.rankBuildSHA256), + rankBuildSHA256: record.rankBuildSHA256, serving: record.serving, + tensorAssistant: record.tensorAssistant), sample: sample)) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageGenerationSchedule.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageGenerationSchedule.swift index a5531f1218..ffc0855bdf 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageGenerationSchedule.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/Generation/QwenLayerStageGenerationSchedule.swift @@ -56,13 +56,16 @@ struct QwenLayerStageGenerationSchedule { } /// `discardedDecodeForwards` counts decode frames this stage ran alone - /// whose tokens the request owner never published. Only a client stop can - /// leave any: the stage decodes a batch before it learns the decision. + /// whose tokens the request owner never published. A client stop can + /// leave any (the stage decodes a batch before it learns the decision), + /// and an EOS under tensor-parallel build-ahead leaves exactly one (the + /// next step is built before the EOS is read; `QwenTensorParallelBatchDriver`). A + /// length finish never does: no step is built past the output count. mutating func finish(_ reason: QwenLayerStageGenerationFinishReason, selectedTokenCount: Int, lastTokenID: Int, discardedDecodeForwards: Int = 0) throws { guard !complete, committedPromptTokens == request.promptCount, - discardedDecodeForwards >= 0, discardedDecodeForwards == 0 || reason == .clientStop, + discardedDecodeForwards >= 0, discardedDecodeForwards == 0 || reason == .clientStop || (reason == .eos && discardedDecodeForwards == 1), selectedTokenCount == decodeForwardCount + 1 - discardedDecodeForwards, (1...request.outputCount).contains(selectedTokenCount), (0.. MLXArray { let token = sampler.sample(logits: logits, params: [parameters], requestIDs: [stream], stepIndex: selected.count, pendingSampledTokens: nil, @@ -82,6 +88,17 @@ final class QwenStageTokenSampler { return pendingLogprobs.map(Self.tokenLogprobs) } + /// The last `sample`'s logprobs as graph nodes, once: a caller that draws + /// the next step before it reads this one (`TensorParallelOneTokenLoop`, + /// Qwen's build-ahead decode) + /// keeps each step's gather with its step and reads it with + /// `tokenLogprobs` after the step's token was agreed. Nil when the + /// request asks for none. + func takePendingStepLogprobs() -> CBv2StepLogprobs? { + defer { pendingLogprobs = nil } + return pendingLogprobs + } + /// The current round's verify window (`verifyRound`), kept for its /// logprobs when the request asks for them. private var verifiedWindow: MLXArray? diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift index 7b762ec90a..c39aed352d 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchDriver.swift @@ -55,11 +55,42 @@ protocol QwenTensorParallelBatchExecutor: AnyObject { func retire(_ lane: Lane, reason: QwenLayerStageGenerationFinishReason?, selected: Int, last: Int?) throws func takeLogprobs(_ lane: Lane) throws -> ClusterWorkerTokenLogprobs? func confirmedRetirement(_ lane: Lane, clean: Bool) throws + /// A submitted, unread plain decode rectangle (build-ahead). + associatedtype Submitted = Void + /// Whether this executor can submit a plain decode rectangle without + /// reading it (`submitDecode`, `readDecode`), so the driver may build the + /// next step before it reads this one (`QwenTensorParallelBatchDriver`'s + /// build-ahead, load-agreed). + var buildsAhead: Bool { get } + /// Submits one plain decode rectangle (its forward, its selection and the + /// selection sum carrying the words `control` returns, called once the + /// forward committed, as `decode`'s) and returns without reading it. + /// `inputs`: the host's tokens, or rows of the previous submitted + /// rectangle's selection, which may still be unread. + func submitDecode(_ lanes: [Lane], inputs: QwenBatchDecodeInputs, control: () throws -> [Float], + check: () throws -> Void) throws -> Submitted + /// Reads a submitted rectangle: one token a lane and both ranks' summed control words. + func readDecode(_ submitted: Submitted, check: () throws -> Void) throws -> (tokens: [Int], control: [Float]) +} + +/// A submitted decode rectangle's input tokens: held on the host, or rows of +/// the previous submitted rectangle's selection (not yet read). +enum QwenBatchDecodeInputs { + case tokens([Int]) + case after(Submitted, rows: [Int]) } extension QwenTensorParallelBatchExecutor { var carriesSelectionControl: Bool { false } func confirmedRetirement(_ lane: Lane, clean: Bool) throws {} + var buildsAhead: Bool { false } + func submitDecode(_ lanes: [Lane], inputs: QwenBatchDecodeInputs, control: () throws -> [Float], + check: () throws -> Void) throws -> Submitted { + throw ProbeError("This TP executor does not build decode steps ahead") + } + func readDecode(_ submitted: Submitted, check: () throws -> Void) throws -> (tokens: [Int], control: [Float]) { + throw ProbeError("This TP executor does not build decode steps ahead") + } /// An executor whose selection sum carries no control words: the driver /// never folds for it, so `control` is always empty. @@ -90,10 +121,11 @@ final class QwenTensorParallelBatchDriver, capacity: Int, vocabulary: Int, - joinWaitNanoseconds: UInt64 = 30_000_000_000, foldsControl: Bool = true, + joinWaitNanoseconds: UInt64 = 30_000_000_000, foldsControl: Bool = true, buildsAhead: Bool = false, now: @escaping () -> UInt64 = { DispatchTime.now().uptimeNanoseconds }) throws { guard (0...1).contains(executor.rank), (1...8).contains(capacity), vocabulary > 0, joinWaitNanoseconds > 0 else { throw ProbeError("Qwen TP batch driver has invalid geometry") } + guard !buildsAhead || (executor.buildsAhead && executor.carriesSelectionControl && foldsControl) else { + throw ProbeError("Qwen TP build-ahead needs an executor that submits decode steps and folds control") + } self.executor = executor; self.book = book; self.capacity = capacity; self.vocabulary = vocabulary - self.joinWaitNanoseconds = joinWaitNanoseconds; self.foldsControl = foldsControl; self.now = now + self.joinWaitNanoseconds = joinWaitNanoseconds; self.foldsControl = foldsControl + self.buildsAhead = buildsAhead; self.now = now } private func cancelled(_ record: Record) -> Bool { @@ -139,6 +185,7 @@ final class QwenTensorParallelBatchDriver Void = { _, _, _ in }, check: () throws -> Void) throws { + if buildsAhead { return try serveAhead(host: host, retiredSelection: retiredSelection, check: check) } var step = 0 var decisions = QwenBatchDecisionProgress() var coalescing = QwenBatchDecodeCoalescing() @@ -243,6 +290,258 @@ final class QwenTensorParallelBatchDriver, check: () throws -> Void) throws -> [Float] { + var barrier = false + if executor.rank == 0 { + let answers = try decisions.serviceAndPoll(host) + try check() + for (id, proceed) in answers.sorted(by: { $0.key.uuidString < $1.key.uuidString }) { + guard let record = records.values.first(where: { $0.id == id }) else { continue } + if proceed, record.finish(true, count: record.published) == nil { + try publishHeld(record, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } else { + // The next plan leaves this lane (a stop, or its last token answered): + // nothing more is published meanwhile. + deferredAnswers[id] = proceed; record.leaving = true; barrier = true + } + } + if !deferredAnswers.isEmpty || book.hasStarted { barrier = true } + } else { + try host.serviceControl(); try check() + } + for (slot, record) in records { + guard let native = record.native, let flight = inFlight[slot] else { barrier = true; continue } + // Selected once every submitted step is read, the next step and the decided one too. + let selected = record.tokens.count + flight + 2 + if cancelled(record) || peerCancelled.contains(slot) || record.ended || !native.canSelectNext || !native.plainSelection + || selected > record.reservation.request.outputCount + || (executor.rank == 0 && selected - record.published > Self.aheadHeldLimit) { + barrier = true + } + } + var words = [Float](repeating: 0, count: Self.decisionWordCount) + words[executor.rank] = barrier ? 1 : 0 + return words + } + + /// Owner answers for the next plan: those a build-ahead decision kept, then the ones polled now. + private func answers(_ decisions: inout QwenBatchDecisionProgress, host: QwenBatchServingHost) throws -> [UUID: Bool] { + let polled = try decisions.serviceAndPoll(host) + defer { deferredAnswers = [:] } + return deferredAnswers.merging(polled) { kept, _ in kept } + } + + /// `serve` with build-ahead. Each plain folded decode step's selection + /// sum also carries both ranks' decision words for the step two later: + /// with neither rank asking for a barrier, and that step's predecessor + /// decoding the same lanes, both ranks build it on the predecessor's + /// unread selection before reading the predecessor, so the GPU runs it + /// while the host reads, publishes and answers. Anything else (an owner's + /// stop, a join, a prompt, a leave, a cancellation, an ended lane, a width + /// change) is a barrier: both ranks read every submitted step and the next + /// plan is made and exchanged with nothing in flight, as in `serve`. + /// Every input to these choices is agreed (read sums, read tokens, plan + /// contents), so both ranks submit the same collectives in the same order. + /// A lane that ends on a token read after its next step was built keeps + /// that step's forward discarded; its token is never selected or published. + private func serveAhead(host: QwenBatchServingHost, + retiredSelection: (UUID, [Int], QwenLayerStageGenerationFinishReason) throws -> Void, + check: () throws -> Void) throws { + var step = 0 + var decisions = QwenBatchDecisionProgress() + var coalescing = QwenBatchDecodeCoalescing() + var peerCancelled = Set() + var carried: (plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply)? + /// Steps whose decision words were read, and the slots a "build ahead" decision covers. + var decided: [Int: Set?] = [:] + var pending: Pending? + func laneCheck() throws { try check(); try host.serviceControl() } + func read(_ submitted: Pending) throws { + let result = try executor.readDecode(submitted.handle, check: laneCheck) + guard result.tokens.count == submitted.slots.count, + result.control.count == submitted.planWords + Self.decisionWordCount else { + throw ProbeError("Qwen TP build-ahead step omitted a lane or its control words") + } + for (slot, token) in zip(submitted.slots, result.tokens) { + guard let record = records[slot] else { throw ProbeError("Qwen TP build-ahead row has no lane") } + // Built ahead past its end: the forward is discarded, the token never selected. + if record.ended { continue } + try selected(token, lane: record, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + let words = Array(result.control.suffix(Self.decisionWordCount)) + guard words.allSatisfy({ $0 == 0 || $0 == 1 }), words[executor.rank] == submitted.localDecision[executor.rank] else { + throw ProbeError("Qwen TP build-ahead decision changed in transit") + } + decided[submitted.step + 2] = words.contains(1) ? .some(nil) : Set(submitted.slots) + if submitted.planWords > 0 { + let (next, nextPeer) = try Self.read(Array(result.control.prefix(submitted.planWords)), step: submitted.step + 1, + lanes: capacity, plan: submitted.localPlan, report: submitted.localReport) + carried = (try resolve(next, carrying: Set(submitted.slots)), nextPeer) + } + } + do { + while true { + let stop = try autoreleasepool { () throws -> Bool in + // A decided continuation: build this step on the unread one's selection, then read that one. + if let previous = pending, case .some(.some(let covered)) = decided[step], covered == Set(previous.slots), + previous.slots.allSatisfy({ records[$0]?.native != nil && records[$0]?.ended == false }) { + decided[step] = nil + let lanes = previous.slots.map { records[$0]! } + var words: [Float] = [] + let handle = try executor.submitDecode(lanes.map { $0.native! }, + inputs: .after(previous.handle, rows: Array(previous.slots.indices)), control: { + words = try decision(inFlight: Dictionary(uniqueKeysWithValues: previous.slots.map { ($0, 2) }), + host: host, decisions: &decisions, peerCancelled: peerCancelled, check: check) + return words + }, check: laneCheck) + let next = Pending(step: step, slots: previous.slots, handle: handle, planWords: 0, + localPlan: nil, localReport: nil, localDecision: words) + // `next` is the step a failure must drain: it depends on `previous`, so draining it + // completes both, and `previous` is never read twice. + pending = next + try read(previous) + return false + } + if let previous = pending { pending = nil; try read(previous) } + decided[step] = nil + decided = decided.filter { $0.key > step } + let plan: QwenBatchWire.Header, peer: QwenBatchWire.Reply + let wasCarried = carried != nil + if let folded = carried { + (plan, peer) = folded; carried = nil + if executor.rank == 1 { try host.serviceControl() } + try check() + } else { + let polled = executor.rank == 0 ? try answers(&decisions, host: host) : [:] + if executor.rank == 1 { try host.serviceControl() } + try check() + let localPlan = executor.rank == 0 + ? try makePlan(step: step, answers: polled, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing) : nil + let localReport = executor.rank == 1 ? report(step: step) : nil + let sum = try executor.exchange(QwenTensorParallelBatchWire.contribution( + rank: executor.rank, plan: localPlan, report: localReport), check: check) + (plan, peer) = try Self.read(sum, step: step, lanes: capacity, plan: localPlan, report: localReport) + } + try validate(plan, peer: peer) + peerCancelled = Set((0.. Record in + guard let record = records[slot], let native = record.native, + native.canSelectNext, record.tokens.last == plan.slots[slot].inputToken else { + throw ProbeError("Qwen TP decode differs from its request history") + } + return record + } + let folds = executor.carriesSelectionControl && prompts.isEmpty + && lanes.allSatisfy { $0.native!.plainSelection } + if folds { + // The successor's plan rides this sum unless a continuation was already + // decided for it (after a barrier the plan rides, so no exchange follows). + let carriesPlan: Bool + if case .some(.some) = decided[step + 1] { carriesPlan = false } else { carriesPlan = true } + let carrying = Set(decode) + var nextPlan: QwenBatchWire.Header?, nextReport: QwenBatchWire.Reply? + var planWords = 0, decisionWords: [Float] = [] + let handle = try executor.submitDecode(lanes.map { $0.native! }, + inputs: .tokens(lanes.map { $0.tokens.last! }), control: { [self] () throws -> [Float] in + var words: [Float] = [] + if carriesPlan { + if executor.rank == 0 { + let polled = try answers(&decisions, host: host) + try check() + nextPlan = try makePlan(step: step + 1, answers: polled, decisions: &decisions, host: host, + peerCancelled: peerCancelled, coalescing: &coalescing, carrying: carrying) + } else { + try host.serviceControl(); try check() + nextReport = report(step: step + 1, carrying: carrying) + } + words = try QwenTensorParallelBatchWire.contribution(rank: executor.rank, plan: nextPlan, report: nextReport) + } + planWords = words.count + decisionWords = try decision(inFlight: Dictionary(uniqueKeysWithValues: decode.map { ($0, 1) }), + host: host, decisions: &decisions, peerCancelled: peerCancelled, check: check) + return words + decisionWords + }, check: laneCheck) + pending = Pending(step: step, slots: decode, handle: handle, planWords: planWords, + localPlan: nextPlan, localReport: nextReport, localDecision: decisionWords) + } else { + let result = try executor.decode(lanes.map { $0.native! }, tokens: lanes.map { $0.tokens.last! }, + control: { nil }, check: laneCheck) + guard result.tokens.count == lanes.count, result.control == nil else { + throw ProbeError("Qwen TP decode omitted a lane or carried control words") + } + for (lane, token) in zip(lanes, result.tokens) { + try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) + } + } + } + if let slot = prompts.first { + let value = plan.slots[slot] + guard let lane = records[slot], let native = lane.native, let frame = native.promptStep(tokens: value.frameCount), + frame.phase == .prefill, frame.tokenOffset == value.frameOffset, + frame.tokenCount == value.frameCount, frame.finalPromptChunk == value.finalChunk else { + throw ProbeError("Qwen TP prefill differs from its original chunk grid") + } + let token = try executor.prefill(native, frame: frame, check: laneCheck) + guard (token != nil) == frame.finalPromptChunk else { throw ProbeError("Qwen TP prefill returned the wrong final-row kind") } + if let token { try selected(token, lane: lane, decisions: &decisions, host: host, peerCancelled: peerCancelled) } + } + if !wasCarried, decode.isEmpty, prompts.isEmpty, + plan.slots.allSatisfy({ $0.state == .active || $0.state == .empty }) { + Thread.sleep(forTimeInterval: 0.0005) + } + return false + } + if stop { return } + step += 1 + } + } catch { + let primary = error + // A submitted step is drained before its lanes retire: its read may fail as well (the + // primary error stands), and no token of it is selected. + if let submitted = pending { pending = nil; _ = try? executor.readDecode(submitted.handle, check: {}) } + do { try retireAll() } + catch { throw ProbeError("\(primary); Qwen TP batch cleanup failed (\(error))") } + throw primary + } + } + /// Rank 0's plan for `step`. `carrying`: rows decoding in the step whose /// selection sum carries this plan. Each counts the token it is selecting /// and decodes on it (`carriedToken`) only if the owner already answered @@ -353,10 +652,11 @@ final class QwenTensorParallelBatchDriver) throws { - guard lane.published == lane.tokens.count - 1, !lane.leaving, decisions.canForward(lane.id), + guard lane.published < lane.tokens.count, lane.heldLogprobs.count == lane.tokens.count - lane.published, + !lane.leaving, decisions.canForward(lane.id), !peerCancelled.contains(lane.slot), !cancelled(lane) else { return } try decisions.published(lane.id) try host.publishToken(requestID: lane.id, ordinal: lane.published, tokenID: lane.tokens[lane.published], - committedTokens: lane.reservation.request.promptCount + lane.published, logprobs: lane.heldLogprobs) - lane.published += 1; lane.heldLogprobs = nil + committedTokens: lane.reservation.request.promptCount + lane.published, logprobs: lane.heldLogprobs[0]) + lane.published += 1; lane.heldLogprobs.removeFirst() } private func leave(_ plan: QwenBatchWire.Header, host: QwenBatchServingHost, diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift index dbd95206ef..b274b1aacd 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/Qwen/TensorParallel/QwenTensorParallelBatchSession.swift @@ -234,10 +234,10 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { } /// A decode forward is submitted to the GPU every this many layers - /// (`Qwen35LayerSubmission`), so the GPU and the collectives run the - /// layers already built while the host builds the rest. Evaluation order - /// only: the logits and every committed state keep their bits. - static let decodeLayerStride = 1 + /// (`QwenTensorParallelLaunch.decodeLayerStride`, where the measured + /// choice is). Evaluation order only: the logits and every committed + /// state keep their bits. + static let decodeLayerStride = QwenTensorParallelLaunch.decodeLayerStride /// A bench or test's own stride (0: the whole forward in one evaluation). @TaskLocal static var layerStride: Int? /// A prompt frame is submitted to the GPU every this many decoder layers @@ -417,9 +417,40 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { return (result.logits, hidden) } + /// `decode`'s step, submitted and not read, on lazy input tokens (`[B]` + /// int32, the previous step's unread selection; `CBv2OwnedRequestState.submitBatch`), + /// so the next step can be built before this one is read + /// (`QwenTensorParallelBatchDriver`'s build-ahead). The same forward and + /// arithmetic as `decode` on the read tokens; native (unpacked) rows. + static func submitDecode(_ sessions: [QwenTensorParallelBatchSession], tokens: MLXArray, + check: () throws -> Void) throws -> MLXArray { + guard tokens.shape == [sessions.count], tokens.dtype == .int32 else { + throw ProbeError("Qwen TP submitted decode needs one int32 token a row") + } + return try decodeResult(sessions, input: .submitted(tokens), capturingHidden: false, check: check).logits + } + + /// A batch decode step's input: tokens the host read, or a previous step's lazy selection. + private enum DecodeInput { + case read([Int]) + case submitted(MLXArray) + + var rows: Int { + switch self { + case .read(let tokens): tokens.count + case .submitted(let tokens): tokens.dim(0) + } + } + } + private static func decodeResult(_ sessions: [QwenTensorParallelBatchSession], tokens: [Int], capturingHidden: Bool, check: () throws -> Void) throws -> (logits: MLXArray, hidden: MLXArray?) { - guard let first = sessions.first, (1...8).contains(sessions.count), sessions.count == tokens.count, + try decodeResult(sessions, input: .read(tokens), capturingHidden: capturingHidden, check: check) + } + + private static func decodeResult(_ sessions: [QwenTensorParallelBatchSession], input decodeInput: DecodeInput, + capturingHidden: Bool, check: () throws -> Void) throws -> (logits: MLXArray, hidden: MLXArray?) { + guard let first = sessions.first, (1...8).contains(sessions.count), sessions.count == decodeInput.rows, Set(sessions.map { ObjectIdentifier($0) }).count == sessions.count, sessions.allSatisfy({ $0.model === first.model && !$0.retired && !$0.failed && ($0.window?.isIdle ?? true) }) else { throw ProbeError("Qwen TP batch decode needs distinct sessions of one loaded shard") @@ -431,9 +462,12 @@ final class QwenTensorParallelBatchSession: QwenTensorParallelMTPTarget { // If any lane carries explicit media positions, all rows supply // their own three axes, including ordinary text rows in the cohort. let positioned = sessions.contains { $0.inputs != nil } - for (session, token) in zip(sessions, tokens) { - guard (0..