From e9babca438a95d886a0e4f9f7e4ffd742ce298a9 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 19:03:27 -0500 Subject: [PATCH 1/6] Keep master's prod default for plain builds (release snapshot only) dev carries one commit that lives on dev alone (431a93d4a, docs/developer/ build.md "The dev branch"): a plain swift build defaults to DARKBLOOM_RELEASE_ENVIRONMENT=dev, so it talks to the DevNet coordinator. Merging dev into master would carry that default to master. This commit, on the dev-to-master release snapshot only, sets the default back to prod in Package.swift and in the build-environment test, as on master. Released binaries do not change either way: every release lane and CI set DARKBLOOM_RELEASE_ENVIRONMENT explicitly. On the next master-into-dev sync, revert this commit on the sync branch so that dev keeps its dev default. --- provider-swift/Package.swift | 2 +- .../ProviderCoreTests/Config/BuildEnvironmentTests.swift | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/provider-swift/Package.swift b/provider-swift/Package.swift index e04193d90d..c8be5b8a35 100644 --- a/provider-swift/Package.swift +++ b/provider-swift/Package.swift @@ -8,7 +8,7 @@ import Foundation // DARKBLOOM_RELEASE_ENVIRONMENT. On the dev branch every other build is dev: // it talks to the DevNet coordinator. On master it is prod. let releaseEnvironment = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" + .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" precondition(["prod", "dev", "staging"].contains(releaseEnvironment), "DARKBLOOM_RELEASE_ENVIRONMENT must be prod, dev or staging") let buildEnvironmentSwiftSettings: [SwiftSetting] diff --git a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift index 6841118e77..f9da9b1e1b 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/BuildEnvironmentTests.swift @@ -5,11 +5,12 @@ import Testing @Suite("Build environment defaults") struct BuildEnvironmentTests { - /// A plain build of the dev branch is a dev build. DARKBLOOM_RELEASE_ENVIRONMENT, read by Package.swift when - /// the tests are built, selects another: CI builds prod, the identity the provider suites pin. - @Test func devBranchBuildsDefaultToDevNet() throws { + /// A plain build of master is a prod build (on the dev branch it is a dev build). DARKBLOOM_RELEASE_ENVIRONMENT, + /// read by Package.swift when the tests are built, selects another: CI builds prod, the identity the provider + /// suites pin. + @Test func plainBuildsTakeTheBranchDefault() throws { let requested = ProcessInfo.processInfo.environment["DARKBLOOM_RELEASE_ENVIRONMENT"] - .flatMap { $0.isEmpty ? nil : $0 } ?? "dev" + .flatMap { $0.isEmpty ? nil : $0 } ?? "prod" let built = try #require(BuildEnvironment(rawValue: requested)) let coordinator = built.coordinatorWebSocketURL let hardware = HardwareInfo( From 40a1c4b726e0fad4046f2bf2d44c9cae63c0e2a1 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sat, 31 Oct 2026 08:46:00 -0700 Subject: [PATCH 2/6] Two-Mac clustering for provider 0.10.6: release cluster facts (#1692), heartbeat fix (#1690) and the pair fixes (#1694) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * cluster: runtime facts v2 name each model's pair-serving grant; release modes `darkbloom cluster runtime-facts` prints schema darkbloom_cluster_runtime_v2: the v1 digests, unchanged, plus each model's pair_serving_grant. The grant is the public grant a member of the same build reports for the described artifact (ClusterPairServingGrants.grant), null when there is none: its mode families sorted by byte, and evidence_sha256, the SHA-256 of the records it rests on as canonical JSON Lines (ClusterPairServingGrant.records, evidenceSHA256). The canonical encoder writes null rather than omitting it; the strict decoder init(canonical:releaseVersion:) refuses unknown, missing or repeated fields, schema v1, and a model whose derived IDs (release///s2, plus /grant for a granted model) exceed 128 bytes. The model bound is 64. The release modes come back (ClusterRuntimeApprovalFacts+Release.swift): --list-release-models prints the models this build qualifies on a cluster, and --app A --release-candidates DIR describes, for every listed artifact and every catalog model ID among its candidates, the first candidate the app's worker describes as that model. A listed model with no candidate is left out (the environment's catalog lacks it); the output must read back under the strict decoder for this build's version. Co-Authored-By: Claude Opus 5.5 * ci(release): every lane computes cluster_runtime; sent only when enabled The release lane (dev branch, staging, prod) computes the cluster runtime facts of its final signed, notarized app with that app's own CLI and worker, in the step "Compute cluster runtime facts from the final signed app" of build-and-release: after the final hashes, with no secret (the signing keychain is deleted and the identity proven gone first), from the target environment's public catalog and model CDN (provider-cluster-runtime-models.py --environment). A listed model that catalog lacks is left out and named. The job summary shows the block and a run artifact retains it in every lane. The payload carries it (prepare --cluster-runtime) only when CLUSTER_RUNTIME_SEND is true: the run registers a release and the environment's repository variable DEV_, STAGING_ or PROD_CLUSTER_RUNTIME_ENABLED is exactly 'true'. Unset, prepare runs today's command and the payload is byte for byte today's (pinned by digest in the tests), and a facts failure only warns (continue-on-error). Set, a failure fails the release before staging and registration. validate accepts a valid block in every environment and refuses an invalid one and one whose derived approval or grant IDs exceed 128 bytes. Co-Authored-By: Claude Opus 5.5 * fix(release): the registration carries cluster_runtime in its canonical form Contract A defines the block as canonical JSON (keys sorted by byte, no whitespace, no trailing newline). prepare now refuses a block file that is not canonical, and the registration body is encoded without whitespace when, and only when, it carries the block, so the coordinator receives the block's canonical bytes whether it parses them or compares them. A body without the block is byte for byte the one sent before (pinned in the tests). Co-Authored-By: Claude Opus 5.5 * cluster: no derived grants; the owner's public models and their parity qualifications Owner decisions (jonathan308, 2026-10-31): "public traffic should not be manual"; "only glm 5.3 flash should be serving public & qwen 3.8 27b they are both good to go they should be approved for serving". The v2 facts no longer carry pair_serving_grant. A coordinator grant restricts its approval to the families it names, and GLM-5.3-Flash's bundled records hold only a pipeline_v1 run, so a derived grant would stop the GLM tensor-parallel pairs M5 members serve today. ClusterPairServingGrants is back to dev apart from the public-traffic line below. ClusterPublicModels (beside the grants, reviewed in PRs) declares exactly GLM-5.3-Flash (registered_glm53_flash, glm-5.3-flash) and Qwen3.8-27B (registered_qwen38_27b, EigenLabs/Qwen3.8-27B-4bit-mtp): tensor_parallel on schedules 1 and 2, evidence placement two Apple M5 Ultras (applegpu_g17d, NAX on) on macOS 27.0, cuts [], equal shares, qualified 2026-10-31T00:00:00Z, and the SHA-256 of the evidence document docs/reports/2026-10-31-public-cluster-models.md (a test holds them equal). It also names the artifact the runtime registers for each model. Each model's parity_qualifications is [] unless the declaration names its runtime model, catalog ID and artifact; then one object per declared family and schedule: numerics classes of the evidence placement with the block's metallib (g17d-nax1-mlx-98bab9d7-macos27.0 on 0.10.5-dev.branch.15 and .16), cuts, mode, tensor_parallel_shares null, promotable, not diverged, evidence_sha256, qualified_at and the request envelope (ClusterPublicModels.requestEnvelope: sampling, tools, 1,048,576 tokens each way, vision and video as the candidate's catalog entry lists image and video; text only without one). Release candidates carry that entry (catalog.json). The strict decoder and validate check the qualifications as a coordinator does and bound the derived IDs release///s/q. The setup's public-traffic line says a declared model is qualified in its declared family without a record of it. The GLM block the installed 0.10.5-dev.branch.16 app computes from DevNet's catalog is pinned as a golden. The placement check runner compiles the new file. Co-Authored-By: Claude Opus 5.5 * ci(release): candidates carry their catalog entry; validate parity qualifications provider-cluster-runtime-models.py saves each candidate's catalog entry (its id and input_modalities, canonical, catalog.json) beside its manifest and config.json, so the released app's own CLI gives a declared model's request envelope the media the target environment's catalog lists; a malformed modality list fails that entry, none listed means text only. provider-release-publication.py checks parity_qualifications in place of pair_serving_grant: the exact fields, schedule 1 or 2, two numerics classes, the cuts the mode has, null shares, flags, an instant the coordinator accepts, the envelope bounds, video only with vision, no placement twice, at most 8; and bounds every derived approval and qualification ID (release///s/q) at 128 bytes. The pinned GLM block is accepted. Docs and the changelog fragment follow; the release step's comments name the parity qualifications. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the service's part beats into its own heartbeat file Under its supervisor the cluster service beats every 2 s into the file DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE names. Its part was started with the service's environment unchanged, and a coordinator-paired part (`start --foreground --cluster-member`) beats every 5 s into the file the same key names, with its own pid. The supervisor's liveness guard reads the file every 15 s and treats a beat of another pid as no beat. The three periods are near multiples of each other, so their phases drift by milliseconds per probe: once the part's beat was the last write at six probes in a row, the guard recycled a healthy service ("heartbeat missing for 75 s while its process is alive") and the pair dropped and registered again. Seen on a DevNet leader about every 15 minutes. The part now gets the service's environment with the key pointing at part-health.json beside the service's files. The key stays set, so the part still waits for its registration as a supervised member does. Co-Authored-By: Claude Opus 5.5 * docs: the cluster service part's own heartbeat file Docs Impact failed: ClusterService.swift changed without its mapped architecture document. The cluster serving section now says which file the service and its part each write their heartbeat to, and why. Co-Authored-By: Claude Opus 5.5 * test(cluster): keep the approval fixture alive through the part heartbeat tests Both new tests failed on CI at every run: the member part never started. They dropped the ClusterApprovalMacs fixture (`let (_, service, parts)`), whose deinit removes both homes, so the leader's saved setup was gone before the service's first tick. The fixture now lives until the last check, as in the other tests of the suite. Co-Authored-By: Claude Opus 5.5 * cluster: pair-serving grants again, beside parity qualifications David's finding: a pair member reports only hardware capabilities (DistributedServingEligibility.memberCapabilities: apple_m5 on an M5), and without a pair-serving grant the coordinator holds each member to the model's single-Mac requirements (providerMeetsServingRequirementsLocked), which no member meets for GLM-5.3-Flash (mlx_nax, glm5_next_v1) or Qwen3.8-27B (mlx_nax). No pair forms without a grant, so every model in the v2 facts again carries pair_serving_grant (null, or exactly evidence_sha256 and mode_families) beside parity_qualifications. A declared public model's grant names its declared families with the evidence document's SHA-256. Owner ruling 2026-10-31 ("It should be tensor or pipeline obviously but that shouldn't matter for the coordinator"): ClusterPublicModels declares pipeline and tensor_parallel for both GLM-5.3-Flash and Qwen3.8-27B. Any other model's grant is the one this build's bundled records give its artifact (ClusterPairServingGrants.grant), with the SHA-256 of those records' canonical JSON Lines (ClusterPairServingGrant.records, evidenceSHA256); null when they grant none. The declaration's families drive the parity qualifications: one promotable record per family and schedule, pipeline first (byte order), so each approval's q1 is the pipeline and q2 tensor parallel. A pipeline is pipeline_v1 cut at [num_hidden_layers / 2] of the model's config.json (top level, else text_config: GLM 45 -> [22], Qwen3.8-27B 64 -> [32]); without a layer count its records are left out and the command says so on standard error. An envelope admits media only where the placement serves media (ClusterModelFeaturePolicy.mediaContract): tensor parallel follows the catalog entry, a pipeline is text only. The strict decoder and validate check the grant (1 to 4 known families in byte order, nonzero evidence) and bound release///s/grant at 128 bytes beside the approval and /q IDs. The setup's public-traffic line follows the declaration (pipeline and tensor parallel); tests about the records alone pass publicModels: []. The evidence report says the owner approved both modes for both models, that GLM-5.3-Flash's bundled records hold a pipeline_v1 run while its tensor parallel rests on the owner's decision and the DevNet serving results, and why grants are needed; its SHA-256 is re-pinned. The GLM golden is re-pinned from the installed 0.10.5-dev.branch.17 app, which replaced branch.16 on this Mac. Co-Authored-By: Claude Opus 5.5 * ci(release): validate pair-serving grants and their derived IDs provider-release-publication.py checks each model's pair_serving_grant again (null, or exactly evidence_sha256 and 1 to 4 known mode_families in byte order) beside its parity_qualifications, adds the grant's evidence to the digests it checks, and bounds release///s<1|2>/grant at 128 bytes with the approval and /q IDs. Its tests cover the grant rows, the ID bound for a model with neither, qualifications only, a grant only and both, the /grant and /q IDs, and the branch.17 GLM golden (q1 the pipeline, text only; q2 tensor parallel). The docs (configuration reference, release runbook, inference architecture, test guide), the changelog fragment and the release step's comments describe the grants and why pairs need them, both declared families, the pipeline cut, the per-placement media and the q1/q2 order. Co-Authored-By: Claude Opus 5.5 * release(publication): refuse a registration body over the coordinator's 64 KiB The coordinator reads POST /v1/releases under MaxReleaseRegisterBodyBytes (64 KiB, as http.MaxBytesReader applies it), the same bound as the cluster_runtime block's own, so a block within its bound could take the body over the limit and fail only at publish, after R2 staging. validate (in prepare, stage and publish) now refuses a payload whose registration body exceeds 65,536 bytes, naming its size and the limit. One function (registration_body) builds the bytes it sizes and the bytes registration sends, so they cannot differ. The test grows a valid block to a body of exactly 65,536 bytes (accepted) and 65,537 (refused before staging, with no payload written), refuses the same limit without a block (release notes), and checks that registration sends the sized bytes. Independent review N1. Co-Authored-By: Claude Opus 5.5 * docs(cluster): the declared placement is evidence, not a limit; catalog room Independent review fixes (S1, S2, N2, N3, N4, N7, N10, N15 wording). The configuration reference, the release runbook, the inference page and the changelog say how a coordinator applies the declared qualifications: a promotable record qualifies its approval's whole mode family on any numerics classes, cuts and shares within the envelope (parityQualification, platform df61dd6f9), so public traffic for GLM-5.3-Flash and Qwen3.8-27B is admitted in pipeline and tensor parallel on any Apple silicon pair; the declared placement names the evidence, not a limit. No pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record: both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash serves only the serial schedule, so its schedule 2 entries are inert. The digest-pinned evidence document is unchanged. The runbook adds the catalog-room precondition (64 approvals with the operator's own, 2 per model per release, newest release whole first, older releases left out first), DevNet's numbers on 2026-10-31 (26 served, 4 catalog models: 8 per release, the 4 newest fit), the log check after the first registration (release cluster approvals omitted), the recovery when a facts failure stops a release, "set to true" (GitHub compares case-insensitively; also in the workflow comment), the release-handler link re-pinned to platform df61dd6f9, and "a catalog model ID of a listed artifact". The inference page notes that a grant also bounds owner-formed sessions to its families. The grant's evidence is the passing records it is computed from, without a pass a divergence of the same shape contradicts: said so in the code comment and the reference, with a test row for a family still granted by another pass. Co-Authored-By: Claude Opus 5.5 * fix(cluster): release facts leave out another model's catalog ID of a shared artifact Production's catalog lists the Gemma 4 26B artifact a4722b60 twice: gemma-4-26b and gemma-4-26b-8bit. The build registers two runtime models on it that only the manifest tells apart (registered_gemma4_26b and registered_gemma4_26b_8bit), and only the 8-bit one is qualified on a pair, so only it is a listed release model. ClusterRuntimeApprovalFacts .release required every catalog model ID of a listed artifact to be described as the listed model, and the worker describes gemma-4-26b's manifest as registered_gemma4_26b. Run against production's catalog and CDN, the release's facts step therefore failed ("Qualified cluster models the release cannot describe: gemma-4-26b"), and a production release with PROD_CLUSTER_RUNTIME_ENABLED=true would stop after signing. A catalog model ID whose candidates the worker describes only as another registered model is that model's: a member that installed it runs as that model, which this release does not qualify. It is now left out and named on standard error (note: left out, the catalog model ID of another registered model). A catalog model ID of which the worker describes no candidate at all still fails the step, and so does an empty result, whose message now names what was left out. The new test builds production's shape from the checked-in metadata fixtures (gemma-4-26b and gemma-4-26b-8bit, one configuration): it fails on the previous code with the production error and passes now; a second test checks the note in both directions. The runbook's release step and the configuration reference state the rule. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): refactor pass on the release facts fix Behaviour-preserving cleanup of 35f7b9f09, from the dedicated refactor pass that AGENTS.md requires before the pull request opens. The facts block, --list-release-models and every message and note stay byte for byte the same. - ClusterRuntimeApprovalFacts.release: the left-out list holds the note lines it names (leftOut) instead of a list called othersCatalogIDs that held reason strings and was mapped to those lines afterwards. The doc comment says "whose candidates the worker describes only as another registered model", as the docs do, and that the empty-result error names what was left out. - ClusterRuntimeFactsCommand: one note(_:) writes "note: " to standard error, for the declared families without a qualification and for the catalog IDs release(note:) leaves out, instead of a second copy of that format in a closure. The command's doc comment names both. - ClusterRuntimeApprovalFactsTests: the "another" case of releaseNamesEveryCatalogModelItCannotDescribeAndRefusesAnEmptyResult now passes through the empty-result error, which names the left-out ID; it checks that message's prefix as well as the refusal it already checked. - provider-release.md, release step 6: "every catalog model ID of a listed artifact gets one entry" contradicted the exception the fix added two sentences later. It now reads "every catalog model ID of a listed artifact that it describes as the listed model gets one entry"; the rest of the step is only rewrapped. - configuration.md: the fix's paragraph is rewrapped (one 108-column line); no word changes. Co-Authored-By: Claude Opus 5.5 * fix(cluster): Qwen3.8 27B pairs register with the coordinator by default With the default [backend] mtp_mode = "auto", the guided setup planned Qwen3.8 27B tensor parallel with the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry (ClusterConfiguration.validate). The leader's check of a coordinator's approval ran only the attachment's own checks, so it stopped both parts and sent the approval, and the other Mac refused it at its save ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"). The pair served on the leader's local API only, while the setup said it was qualified for public traffic (finding F1 of the 0.10.6 two-Mac proof). The assistant stays local-only: no parity qualification covers its verify windows. The bundled tensor-parallel records of the 27B predate it, and neither the records, the release's cluster_runtime block nor a pair's registration has a speculation field. - The onboarding plans for how the cluster serves: through Darkbloom, auto discovers like off (ClusterPlacementTensorAssistantSelection. discoveryMode), so the default Qwen setup carries no assistant and both Macs accept the approval. darkbloom cluster local keeps it. The service's re-plans follow the saved scope, and forwarded planModels and adopt carry the asking Mac's scope. An explicit on is kept. - ClusterApprovalAttachment.attachment runs the whole ClusterConfiguration.validate on the setup with the approval attached, so the leader refuses an assistant setup before any part stops or anything is sent. The refusal names the reason and the remedy in 163 characters. - A plan that decodes with the assistant says "not offered for public traffic" instead of "qualified for public traffic". Tests: ClusterApprovalTensorAssistantTests (real stores, the other Mac's own approval handling) and the onboarding's public-traffic line for the registered 27B artifact fail on 35f7b9f09 with the live F1 message and pass with the fix; discoveryMode, the plain refusal through the link, the public-traffic line and the CLI scope binding have tests of their own. The release's model list and cluster_runtime block are byte-identical (51c77bdb..., 4fd4ea8a...). Co-Authored-By: Claude Opus 5.5 * fix(cluster): coordinator-side member ends no longer set a pair's approval aside for good ClusterApprovalCheck.memberQuickEnds counted every coordinator-paired part end under 120 s except an unreachable coordinator. A registration the coordinator did not acknowledge in its 10 s negotiation window (a deploy, a restart, a slow coordinator) counted like a local failure. Three in a row set the approval aside as failing, and the same build never took it again; a release-derived approval keeps its ID for the whole release, so the pair served only the leader's local API until someone intervened (provider bug hunt 1.4, probe 8bad154d9). (a) Which ends count - A quick end whose error is ClusterMemberControlError.negotiationFailed leaves the count as it is; a run of 120 s or more still resets it, and an unreachable coordinator still resets it. Every other end counts: a changed input, a crash without an error line, connectionEnded, roleUnsupported. - "The coordinator control connection ended or lost trust" never ends a coordinator-paired part: `start --cluster-member` runs its loop with stopOnDisconnect false, so a dropped connection, an untrusted or offline trust_status and a runtime-outdated status leave it reconnecting. That exit (memberControlEnded) is the distributed leader part's, which the count never includes. A coordinator restart reaches the count only as a registration the restarted coordinator does not accept in time: the negotiation case above. Per platform master 2847f27dd, "untrusted" is sent only for this Mac's own verification (failed or missed attestation challenges, a revoked App Attest credential, a failed security check, a replaced connection), so it would count; "offline" only accompanies the end of the connection. - This complements the coordinator fix that ends each pair session before its shutdown closes the members' sockets (darkbloom-platform fix/coord-shutdown-pair-cancel, 824e82e3c, not yet on master): a deploy then ends members cleanly, and this rule still covers older coordinators, coordinator crashes and slow negotiation. (b) A bounded set-aside - ClusterSetupRecord.ApprovalSetAside gains setAt (wall-clock seconds), which the cluster service records (ClusterApprovalCheck.setAside(by:worker:now:)). step holds a failing approval aside for ClusterApprovalFallback.failingSeconds = 3_600 only; then the same build takes it again. A record without setAt (an older build's) or with a time ahead of the clock is past the bound. The count starts again because each Mac's part that serves locally resets it, so the approval comes back with none. - The status line says when; two-mac-cluster and the configuration reference follow; changelog fragment. Tests (ClusterApprovalWatchTests): coordinatorSideEndsDoNotReachTheFailingLimit, localQuickEndsStillSetTheApprovalAside, aFailingApprovalIsOfferedAgainAnHourAfterItWasSetAside, aSetAsideInTheCurrentRecordFormatReadsCleanlyAndIsPastTheHour. They fail on the old rules (12 issues in 5 tests, with a compile shim for the new field) and pass with the change. The model-approval test now expects an older build's record to be past the hour. Co-Authored-By: Claude Opus 5.5 * docs(cluster): pair Macs do not update themselves; update both by hand Nothing updates Darkbloom on a Mac set up with `darkbloom cluster` (provider bug hunt 1.2): ClusterServiceCommand.runSupervisor builds its supervisor with autoUpdate false, so the update slot never runs; the coordinator-paired part never starts startAutoUpdateMonitor (ProviderLoop+Serve, solo providers only); and the single-Mac provider cannot run beside the cluster (DistributedInstalledProviderExclusion). The docs said otherwise. - two-mac-cluster: a section "Updating Darkbloom on the pair" with the manual procedure, as the code does it: `darkbloom update` on each Mac (UpdateCommand installs; its "Restart the provider" line does not apply without a provider LaunchAgent); the control leader's ClusterService.checkForUpdate compares the pinned worker digests with this Mac's worker file and the other Mac's reported facts every 60 s while serving, then stops both parts, plans the same model again and serves it ("Darkbloom changed on ...: setting the cluster up again for "). The cluster service process itself keeps the release it started with until it starts again: a re-run of `darkbloom cluster` leaves an unchanged login agent alone, so log out and in (or restart). Automatic pair updates are listed as not yet in this build. - cluster-always-on: the login agent's supervisor runs without the update slot; the update-slot row applies to the developer route (`start --cluster-member --always-on`) only, with auto_update on. Co-Authored-By: Claude Opus 5.5 * docs(inference): note that min_p applies on one Mac too abbe697ca made EngineV2Bridge forward an explicit min_p on every single-Mac slot, as a cluster pair already did (intentional: requests without min_p are unchanged). The 0.10.6 fragments did not say so, and ChatRequest.min_p still said it applied on a pair only (provider bug hunt 1.6). - changelog.d/min-p-single-mac.md: the bug hunt's proposed line. - ChatRequest.min_p: applied on every slot; the samplers count a value above 1 as 1 and ignore 0, negative and NaN values; MiMo native media and Nemotron Super refuse a non-zero value. Comment only. Co-Authored-By: Claude Opus 5.5 * docs(cluster): Qwen pairs refuse grammar-constrained JSON before any output; pair updates in the notes The Qwen pair JSON fix is not part of 0.10.6 (refactor pass #2, finding M1). Skipping the grammar on a pair would have answered public JSON-mode requests with no grammar and no answer check, because the provider streams every coordinator request and validates a streamed answer only when a grammar was built. - Two-Mac guide, Qwen section: a JSON response_format request that one Mac would answer under a grammar is refused on a Qwen pair before any output (constrained_decoding_unsupported, HTTP 400). The coordinator moves a public request refused this way to a single Mac, which constrains it (darkbloom-platform fix/coord-pair-refusal-failover); the owner's local cluster API gets the refusal. - changelog.d/cluster-pair-update-by-hand.md: pair Macs set up with darkbloom cluster do not update themselves yet; run darkbloom update on both Macs, then log out and back in, and press m once if the status says the assistant is not offered. Co-Authored-By: Claude Opus 5.5 * fix(provider): co-resident loads fund every model's KV floor before the proportional split 0.10.5 providers report "loading 'gemma-4-26b-qat-4bit' would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance (fleet KV budget 51467271830 B across 7 slots) — refused", and the same for gpt-oss-20b at 54999766706 B, with every floor far inside the budget. resliceGrants split the fleet KV budget only in proportion to each slot's fp16 rate x min(context, 131072). A resident with a small rate but a real fixed request workspace gets less than its own floor once a seventh model joins: on a 192 GB Mac with Ternary Bonsai 2 27B, Qwen3.8 27B, Qwen3.6 and Qwen3.5 35B-A3B, Gemma 4 26B and Nemotron 3.5 Lightning resident, Lightning (6,144 B/token; nine recurrent generations with its assistant, a floor of at least 1.587 GB) is offered 1.443 GB, while all seven floors total 9.9 GB of the 51.5 GB budget. Given the floors, resliceGrants keeps the proportional result whenever it clears every floor (configurations that load today keep identical grants). Otherwise, if the floors fit, each slot gets its floor plus its weighted share of the rest; if they do not, the proportional result stands and the floor check refuses as before. Every re-slice passes the floors: ProviderLoop and StandaloneServer loads with the MTP target-only retry, the managed Super newcomer, the reserve-raise preflights, native MiMo, and both regrow paths, so an unload or reserve change cannot shrink a slot below its floor. Tests: real EngineV2 residents with their fixed workspace reproduce the refusal through ProviderLoop and StandaloneServer and are admitted after the fix; a plain regrow cut Lightning to zero serving width and now keeps its floor. Pure tests pin the reported budgets, unchanged results when nothing starves, refusal for infeasible or unprovable floors, and Σ ≤ budget. The Super capacity test that used proportional starvation as its trigger now asserts that Super loads at its floor, and a genuine shortfall still refuses. Co-Authored-By: Claude Opus 5.5 * docs(provider): a newcomer's KV floor is checked only when its engine is assembled The re-slice funds every resident's floor first, but a newcomer has no engine yet and counts only the base 1 GiB floor. A newcomer with a small KV rate and its own fixed workspace can therefore still receive less than its floor and fail at assembly with no_kv_headroom: Nemotron 3.5 Lightning loaded seventh beside the reported residents gets 1.443 GB against its 1.587 GB floor (serving width 0), unchanged from 0.10.5. hardware-support.md now states that limit where the floors are described, and inference.md says the re-slice, not every load, refuses only when the floors exceed the fleet KV budget. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 * test(provider): local server regrow and reserve check keep a starved slot's KV floor The fix passes slot floors at both regrow paths and both reserve checks, but only the ProviderLoop pair had a test. Dropping the floors from StandaloneServer.resliceGrowSurvivors and reserveKeepsSurvivorsServiceable left all 350 selected tests passing. The new test mirrors the ProviderLoop one on the same seven-slot scenario: it first checks that the server's own budget starves Lightning under the plain proportional split, then expects the reserve check to pass and the regrow to leave every resident at its floor with serving width, within the budget. With either floors argument removed it fails. Co-Authored-By: Claude Opus 5.5 * docs(provider): the KV floor changelog entry names the refusal it removes "A load is refused only when the minimums together exceed the budget" promised more than the split can check. The model being loaded counts only the 1 GB base minimum until it is built, so Nemotron 3.5 Lightning loaded beside several high-rate models can still fail with no KV headroom, as on 0.10.5. The entry now says the message appears only when the minimums exceed the budget, and states that limit. Release preparation already rendered this fragment into CHANGELOG.md; the matching one-line change there equals changelog.py render of the new fragment. 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: David Tai --- .github/workflows/ci.yml | 1 + .github/workflows/release-dev-branch.yml | 2 + .github/workflows/release-provider.yml | 114 ++- .github/workflows/release-swift.yml | 2 + ...uster-pair-coordinator-ends-not-failing.md | 5 + changelog.d/cluster-pair-update-by-hand.md | 3 + ...ster-qwen-pair-public-without-assistant.md | 7 + changelog.d/cluster-release-runtime-facts.md | 7 + ...runtime-facts-another-models-catalog-id.md | 4 + changelog.d/cluster-service-part-heartbeat.md | 3 + changelog.d/kv-reslice-slot-floors.md | 4 + changelog.d/min-p-single-mac.md | 3 + docs/architecture/hardware-support.md | 25 +- docs/architecture/inference.md | 71 +- docs/developer/test.md | 25 +- docs/operations/provider-release.md | 164 ++++- docs/provider/cli-reference.md | 4 +- docs/provider/cluster-always-on.md | 20 +- docs/provider/direct-mode.md | 7 +- docs/provider/two-mac-cluster.md | 90 ++- docs/reference/configuration.md | 111 ++- .../2026-10-31-public-cluster-models.md | 128 ++++ docs/reports/README.md | 3 +- .../Config/ClusterConfiguration.swift | 13 +- .../ClusterRuntimeApprovalFacts+Release.swift | 107 +++ .../Config/ClusterRuntimeApprovalFacts.swift | 467 +++++++++++- .../ClusterSetupWizardLiveOperations.swift | 16 +- .../Console/ClusterSetupWizardPlanning.swift | 3 +- .../Console/ClusterSetupWizardStore.swift | 13 +- .../Installed/ClusterPublicModels.swift | 131 ++++ ...DistributedInstalledPairServingGrant.swift | 72 +- .../ClusterApprovalAttachment.swift | 13 +- .../ClusterApprovalCheck.swift | 33 +- .../Onboarding/ClusterOnboardingLive.swift | 31 +- .../Onboarding/ClusterService.swift | 32 +- .../Placement/ClusterPlacementFlow.swift | 10 +- ...terPlacementTensorAssistantSelection.swift | 10 + .../Inference/Memory/EngineV2Reslice.swift | 52 +- .../Inference/Prompting/ChatRequest.swift | 9 +- .../ProviderCore/ProviderLoop+EngineV2.swift | 37 +- .../MiMo/StandaloneServer+NativeMiMo.swift | 3 +- .../Server/StandaloneServer.swift | 25 +- .../Service/ClusterServiceAgent.swift | 6 + .../ClusterRuntimeFactsCommand.swift | 55 +- .../darkbloom/ClusterSetupWizardCommand.swift | 1 + .../MemberFixtureServicePart.swift | 4 + .../PlacementSetupCheck.swift | 8 +- .../Tests/ClusterPlacementChecks/run.sh | 1 + .../ClusterOnboardingScopeSettingsTests.swift | 22 + .../ClusterRuntimeFactsCommandTests.swift | 14 +- .../ClusterRuntimeApprovalFactsTests.swift | 667 +++++++++++++++++- .../glm-5.3-flash-dev-branch17.json | 1 + .../ClusterApprovalFixture.swift | 52 +- .../ClusterApprovalServiceStartTests.swift | 57 +- .../ClusterApprovalTensorAssistantTests.swift | 74 ++ .../ClusterApprovalWatchTests.swift | 120 +++- .../ClusterOwnerServingTests.swift | 73 +- .../ClusterPairServingDecisionsTests.swift | 3 +- ...istributedAutomaticBatchPlannerTests.swift | 107 ++- .../EngineV2ResliceFloorWiringTests.swift | 256 +++++++ .../Fixtures/ResliceFloorScenario.swift | 139 ++++ .../Memory/EngineV2ResliceFloorTests.swift | 150 ++++ ...motronSuperManagedSlotTests+Capacity.swift | 49 +- scripts/provider-cluster-runtime-facts.sh | 37 + scripts/provider-cluster-runtime-models.py | 226 ++++++ scripts/provider-release-publication.py | 190 ++++- .../test-provider-cluster-runtime-models.py | 292 ++++++++ scripts/test-provider-release-pipeline.py | 125 +++- scripts/test-provider-release-publication.py | 352 +++++++++ 69 files changed, 4684 insertions(+), 277 deletions(-) create mode 100644 changelog.d/cluster-pair-coordinator-ends-not-failing.md create mode 100644 changelog.d/cluster-pair-update-by-hand.md create mode 100644 changelog.d/cluster-qwen-pair-public-without-assistant.md create mode 100644 changelog.d/cluster-release-runtime-facts.md create mode 100644 changelog.d/cluster-runtime-facts-another-models-catalog-id.md create mode 100644 changelog.d/cluster-service-part-heartbeat.md create mode 100644 changelog.d/kv-reslice-slot-floors.md create mode 100644 changelog.d/min-p-single-mac.md create mode 100644 docs/reports/2026-10-31-public-cluster-models.md create mode 100644 provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift create mode 100644 provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift create mode 100644 provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift create mode 100644 provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift create mode 100755 scripts/provider-cluster-runtime-facts.sh create mode 100644 scripts/provider-cluster-runtime-models.py create mode 100644 scripts/test-provider-cluster-runtime-models.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6068bfbf31..84db42949a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,6 +64,7 @@ jobs: python3 scripts/test-prepare-metal-toolchain.py python3 scripts/test-provider-release-pipeline.py python3 scripts/test-provider-release-publication.py + python3 scripts/test-provider-cluster-runtime-models.py python3 scripts/test-release-dev-branch.py python3 scripts/test-provider-release-artifact.py python3 scripts/test-provider-signing-validation.py diff --git a/.github/workflows/release-dev-branch.yml b/.github/workflows/release-dev-branch.yml index 4b5e3cbc62..8b62153baa 100644 --- a/.github/workflows/release-dev-branch.yml +++ b/.github/workflows/release-dev-branch.yml @@ -68,6 +68,8 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-cluster-runtime-models.py' + - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' - 'scripts/sign-cluster-helpers.sh' - 'scripts/stage-swiftpm-resource-bundles.sh' diff --git a/.github/workflows/release-provider.yml b/.github/workflows/release-provider.yml index 884adb299d..341187f72d 100644 --- a/.github/workflows/release-provider.yml +++ b/.github/workflows/release-provider.yml @@ -63,6 +63,13 @@ name: Provider Release Lane (reusable) # release-swift.yml runs the staging lane only when the STAGING_ENABLED # repository variable is 'true'. Apple signing secrets are shared (same cert for # all envs). +# +# Repository variables DEV_CLUSTER_RUNTIME_ENABLED, STAGING_CLUSTER_RUNTIME_ENABLED +# and PROD_CLUSTER_RUNTIME_ENABLED: 'true' sends the final signed app's cluster +# runtime facts (cluster_runtime) with that environment's release registration +# (job build-and-release, CLUSTER_RUNTIME_SEND). Every lane computes, shows and +# retains them either way. Set one only after that environment's coordinator +# accepts the block (docs/operations/provider-release.md). on: workflow_call: @@ -288,6 +295,17 @@ jobs: RELEASE_UNSIGNED_ARTIFACT_DIGEST: ${{ needs.resolve-env.outputs.unsigned_artifact_digest }} RELEASE_BUILD_RUN_ID: ${{ needs.resolve-env.outputs.build_run_id }} RELEASE_BUILD_RUN_ATTEMPT: ${{ needs.resolve-env.outputs.build_run_attempt }} + # 'true' only when this run registers a release and the environment's + # repository variable (DEV_, STAGING_ or PROD_CLUSTER_RUNTIME_ENABLED) is + # set to 'true' (== compares case-insensitively, so 'True' counts too). + # Then the payload carries cluster_runtime and a failure + # to compute it fails the release before registration; otherwise the + # payload is unchanged and a failure only warns. + CLUSTER_RUNTIME_SEND: >- + ${{ needs.resolve-env.outputs.publish == 'true' && + ((needs.resolve-env.outputs.environment == 'dev' && vars.DEV_CLUSTER_RUNTIME_ENABLED == 'true') || + (needs.resolve-env.outputs.environment == 'staging' && vars.STAGING_CLUSTER_RUNTIME_ENABLED == 'true') || + (needs.resolve-env.outputs.environment == 'prod' && vars.PROD_CLUSTER_RUNTIME_ENABLED == 'true')) }} steps: - name: Resolve release metadata URLs @@ -920,6 +938,89 @@ jobs: echo "Bundle hash: $BUNDLE_HASH" echo "Metallib hash: $METALLIB_HASH" + # Every lane: the cluster runtime facts (cluster_runtime) from which a + # coordinator derives this build's cluster approvals, their pair-serving + # grants and the parity qualifications of the models it declares public + # (ClusterPublicModels), computed by the final signed app's own CLI and + # worker after every signing, notarization and final-bytes check above. + # The payload carries them only when CLUSTER_RUNTIME_SEND is 'true'; + # otherwise a failure here only warns (continue-on-error) and the release + # continues exactly as before. No secret is in this step: it reads no secrets.*, + # removes the two secret-derived values the job's GITHUB_ENV holds and + # the signing keychain (and proves the identity is gone) before any + # release code runs, and runs the app's CLI with an empty environment. + - name: Compute cluster runtime facts from the final signed app + id: cluster_runtime + continue-on-error: ${{ env.CLUSTER_RUNTIME_SEND != 'true' }} + timeout-minutes: 20 + run: | + set -euo pipefail + unset r2_public_url coordinator_url + # The signing keychain must be gone, and no keychain may still list + # the signing identity, before any release code runs. + security delete-keychain "$KEYCHAIN_PATH" + test ! -e "$KEYCHAIN_PATH" + test -n "$DEVELOPER_ID" + IDENTITIES=$(security find-identity -p codesigning) + if grep -F -q -- "$DEVELOPER_ID" <<< "$IDENTITIES"; then + echo "::error::The signing identity is still readable after the signing keychain was deleted" + exit 1 + fi + test "$(shasum -a 256 /tmp/darkbloom-bundle-macos-arm64.tar.gz | cut -d' ' -f1)" = "$BUNDLE_HASH" + FACTS_ROOT="$RUNNER_TEMP/cluster-runtime" + rm -rf "$FACTS_ROOT" + mkdir -p "$FACTS_ROOT/app" + /usr/bin/tar -xzf /tmp/darkbloom-bundle-macos-arm64.tar.gz -C "$FACTS_ROOT/app" + scripts/provider-cluster-runtime-facts.sh "$FACTS_ROOT/app/$APP_NAME" "$CLI_NAME" "$ENV_PREFIX" "$FACTS_ROOT/facts" + if [ "$CLUSTER_RUNTIME_SEND" = true ]; then + echo "CLUSTER_RUNTIME_FILE=$FACTS_ROOT/facts/cluster-runtime.json" >> "$GITHUB_ENV" + fi + + - name: Show the cluster runtime facts + if: ${{ !cancelled() && (steps.cluster_runtime.outcome == 'success' || steps.cluster_runtime.outcome == 'failure') }} + continue-on-error: true + env: + FACTS_OUTCOME: ${{ steps.cluster_runtime.outcome }} + run: | + set -euo pipefail + FACTS="$RUNNER_TEMP/cluster-runtime/facts" + VARIABLE="$(echo "$ENV_PREFIX" | tr '[:lower:]' '[:upper:]')_CLUSTER_RUNTIME_ENABLED" + if [ "$CLUSTER_RUNTIME_SEND" = true ]; then + SENT="$VARIABLE is true: the release registers with these facts (cluster_runtime) or not at all." + FAILED="::error::The cluster runtime facts could not be computed; with $VARIABLE true the release stops before registration." + else + SENT="Not sent: $VARIABLE is not true, or this run registers no release; the payload is unchanged." + FAILED="::warning::The cluster runtime facts could not be computed; the release continues without them, as before." + fi + { + echo "### Cluster runtime facts ($ENV_PREFIX)" + echo "$SENT" + if [ "$FACTS_OUTCOME" = success ]; then + cat "$FACTS/skipped.md" + echo '```json' + python3 -m json.tool --sort-keys "$FACTS/cluster-runtime.json" + echo '```' + else + echo "Failed: see the log of the step 'Compute cluster runtime facts from the final signed app'." + fi + } >> "$GITHUB_STEP_SUMMARY" + if [ "$FACTS_OUTCOME" != success ]; then + echo "$FAILED" + fi + + - name: Retain the cluster runtime facts + if: ${{ !cancelled() && (steps.cluster_runtime.outcome == 'success' || steps.cluster_runtime.outcome == 'failure') }} + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cluster-runtime-${{ needs.resolve-env.outputs.environment }}-${{ needs.resolve-env.outputs.source_sha }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/cluster-runtime/facts/cluster-runtime.json + ${{ runner.temp }}/cluster-runtime/facts/release-models.json + ${{ runner.temp }}/cluster-runtime/facts/skipped.md + if-no-files-found: warn + retention-days: 30 + - name: Record signed validation identity id: validation_identity if: needs.resolve-env.outputs.publish == 'false' @@ -974,8 +1075,17 @@ jobs: COORDINATOR_URL: ${{ env.coordinator_url }} run: | set -euo pipefail - python3 scripts/provider-release-publication.py prepare \ - --directory "$RUNNER_TEMP/provider-publication" --bundle /tmp/darkbloom-bundle-macos-arm64.tar.gz + if [ "$CLUSTER_RUNTIME_SEND" = true ]; then + # The environment's variable is 'true': the facts step succeeded + # (it fails the job otherwise) and its block goes with the payload. + test -s "${CLUSTER_RUNTIME_FILE:-}" + python3 scripts/provider-release-publication.py prepare \ + --directory "$RUNNER_TEMP/provider-publication" --bundle /tmp/darkbloom-bundle-macos-arm64.tar.gz \ + --cluster-runtime "$CLUSTER_RUNTIME_FILE" + else + python3 scripts/provider-release-publication.py prepare \ + --directory "$RUNNER_TEMP/provider-publication" --bundle /tmp/darkbloom-bundle-macos-arm64.tar.gz + fi # dev and staging names carry the environment, so two lanes in one # GitHub run never collide; prod keeps the unqualified # name the resume path (provider_release_resume) reconstructs and the diff --git a/.github/workflows/release-swift.yml b/.github/workflows/release-swift.yml index 4ff9a90408..102e9af384 100644 --- a/.github/workflows/release-swift.yml +++ b/.github/workflows/release-swift.yml @@ -63,6 +63,8 @@ on: - 'scripts/provider_release_github.py' - 'scripts/provider_release_identity.py' - 'scripts/provider-signing-validation.py' + - 'scripts/provider-cluster-runtime-models.py' + - 'scripts/provider-cluster-runtime-facts.sh' - 'scripts/build-cluster-helpers.sh' - 'scripts/sign-cluster-helpers.sh' - 'scripts/stage-swiftpm-resource-bundles.sh' diff --git a/changelog.d/cluster-pair-coordinator-ends-not-failing.md b/changelog.d/cluster-pair-coordinator-ends-not-failing.md new file mode 100644 index 0000000000..85f55ed611 --- /dev/null +++ b/changelog.d/cluster-pair-coordinator-ends-not-failing.md @@ -0,0 +1,5 @@ +### A coordinator deploy no longer takes a cluster pair off public traffic + +- A pair registered with the coordinator serves on the leader's local API instead when its coordinator-paired parts end three times in a row right after starting. A part that ended because the coordinator did not accept its registration within the 10-second window counted too, although the coordinator decided that end: it happens during a coordinator deploy, right after a restart, or while the coordinator is slow. Such an end no longer counts. Ends with a local cause, such as a changed input or a crash, still count. +- This complements a coordinator that ends each pair session before it shuts down, which makes a deploy's ends cleaner: the provider rule still covers coordinators without that change, coordinator crashes and slow registrations. +- A pair set aside this way is offered to the coordinator again with the same approval an hour later, or at once with a later approval. Before, only a later approval, the approval's end or a Darkbloom update brought it back, so it could serve only the leader's local API for the rest of the release. diff --git a/changelog.d/cluster-pair-update-by-hand.md b/changelog.d/cluster-pair-update-by-hand.md new file mode 100644 index 0000000000..e4760b3177 --- /dev/null +++ b/changelog.d/cluster-pair-update-by-hand.md @@ -0,0 +1,3 @@ +### Pair Macs set up with `darkbloom cluster` do not update themselves yet + +- Darkbloom on a Mac set up with `darkbloom cluster` does not update itself yet. To update a pair, run `darkbloom update` on both Macs, then log out and back in, so that the cluster service runs the new release. If `darkbloom cluster` status then says that Qwen's speculative assistant is not offered for public traffic, press `m` once in `darkbloom cluster` to plan the model again. diff --git a/changelog.d/cluster-qwen-pair-public-without-assistant.md b/changelog.d/cluster-qwen-pair-public-without-assistant.md new file mode 100644 index 0000000000..8d98f3fa68 --- /dev/null +++ b/changelog.d/cluster-qwen-pair-public-without-assistant.md @@ -0,0 +1,7 @@ +### Qwen3.8 27B pairs register with the coordinator by default + +- A Qwen3.8 27B pair set up with `darkbloom cluster` now registers with the coordinator and can serve public traffic. With the default `[backend] mtp_mode = "auto"`, the setup used to carry the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry. The other Mac therefore refused every cluster approval ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"), and the pair served on the leader's local API only, although the setup said it was qualified for public traffic. +- The assistant's speculative decoding has no parity qualification, so it stays on local clusters. Under `auto`, a cluster served through Darkbloom is planned without it, as are the re-plans after an update or a memory refusal. `darkbloom cluster local` keeps it. The cost is speed: on two M5 Ultras, one request decodes at about 40 tokens/s without the assistant and about 93 tokens/s with it. +- `mtp_mode = "on"` keeps the assistant in either case. A cluster served through Darkbloom is then not offered to the coordinator, and the setup says so in its public-traffic line instead of claiming qualification. +- The leader now checks a coordinator's approval with every rule the save applies, the assistant rule included, before it stops either Mac's part or sends anything over the cable. The pair is not offered, with the reason in one line: `Not offered for pairing: this Mac's check refused it: Qwen's speculative assistant serves local clusters only …`. +- Public speculative decoding for Qwen pairs needs qualification evidence of its own and is a follow-up. diff --git a/changelog.d/cluster-release-runtime-facts.md b/changelog.d/cluster-release-runtime-facts.md new file mode 100644 index 0000000000..f61e8f7068 --- /dev/null +++ b/changelog.d/cluster-release-runtime-facts.md @@ -0,0 +1,7 @@ +### Releases carry their cluster runtime facts + +- Every release lane (dev branch, staging, prod) now computes the cluster runtime facts of its final signed app with that app's own CLI and worker: the digests of the cluster worker, placement tool, Metal library and paged-attention source, and for each model the build qualifies on a cluster and the environment's catalog has, the digests of its capability and its pair-serving grant. The job summary and a run artifact show them in every release. +- Each model's pair-serving grant lets a coordinator form its two-Mac pairs: a pair member reports only hardware capabilities, so without a grant no pair of GLM-5.3-Flash or Qwen3.8-27B forms. A declared public model's grant names its declared mode families; any other model's is the grant of the build's own qualification records, or none. +- GLM-5.3-Flash and Qwen3.8-27B are declared for public cluster traffic in pipeline and tensor parallel (owner decisions, 2026-10-31): their entries carry parity qualifications from which a coordinator derives their public qualifications, and it applies them to each declared mode family on any Apple silicon pair, with sampling and tools, and in tensor parallel images and video as the environment's catalog lists them. The qualifications name the evidence placement (two Apple M5 Ultras; a pipeline cut at half the model's layers), not a limit; no pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record, so both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash runs the serial prefill schedule only, so its schedule 2 entries are inert. Every other model's clusters serve their owner only. The setup says a declared model is qualified for public traffic in pipeline and tensor parallel. +- The release registration carries the facts as `cluster_runtime` only when that environment's repository variable (`DEV_CLUSTER_RUNTIME_ENABLED`, `STAGING_CLUSTER_RUNTIME_ENABLED`, `PROD_CLUSTER_RUNTIME_ENABLED`) is `true`; a coordinator that accepts the block then approves the build's two-Mac clusters automatically. Unset, the registration is unchanged and a failure to compute the facts only warns. +- `darkbloom cluster runtime-facts` (hidden) prints schema `darkbloom_cluster_runtime_v2`: the same digests as before plus each model's `pair_serving_grant` and `parity_qualifications`. diff --git a/changelog.d/cluster-runtime-facts-another-models-catalog-id.md b/changelog.d/cluster-runtime-facts-another-models-catalog-id.md new file mode 100644 index 0000000000..4d7163168a --- /dev/null +++ b/changelog.d/cluster-runtime-facts-another-models-catalog-id.md @@ -0,0 +1,4 @@ +### Cluster runtime facts leave out another model's catalog ID of a shared artifact + +- A release's cluster runtime facts no longer fail when one artifact is listed under the catalog IDs of two registered models. Production lists `gemma-4-26b` and `gemma-4-26b-8bit` for the same Gemma 4 26B artifact, and the build registers them as two runtime models that only the manifest tells apart. Only the 8-bit one is qualified on a pair, so `darkbloom cluster runtime-facts --release-candidates` stopped with "Qualified cluster models the release cannot describe: gemma-4-26b", and a production release with `PROD_CLUSTER_RUNTIME_ENABLED=true` would have stopped after signing. +- A catalog model ID whose candidates the build's worker describes only as another registered model is now that model's: it is left out of the facts and named on standard error (`note: left out, the catalog model ID of another registered model: …`). A catalog model ID of which the worker describes no candidate at all still fails the step. diff --git a/changelog.d/cluster-service-part-heartbeat.md b/changelog.d/cluster-service-part-heartbeat.md new file mode 100644 index 0000000000..031989696d --- /dev/null +++ b/changelog.d/cluster-service-part-heartbeat.md @@ -0,0 +1,3 @@ +### The cluster service is no longer restarted while its pair is registered + +A pair registered with the coordinator could restart the cluster service of a Mac many times a day (about every 15 minutes on one DevNet leader: "heartbeat missing for 75 s while its process is alive"), and each restart dropped the pair for a short time. The Mac's part inherited the service's heartbeat file and wrote its own heartbeats into it, and the supervisor does not count a heartbeat from another process. The part now writes its heartbeats to a file of its own (`~/.darkbloom/cluster-setup/part-health.json`). diff --git a/changelog.d/kv-reslice-slot-floors.md b/changelog.d/kv-reslice-slot-floors.md new file mode 100644 index 0000000000..228e32f74a --- /dev/null +++ b/changelog.d/kv-reslice-slot-floors.md @@ -0,0 +1,4 @@ +### Models load when every model's minimum KV fits + +- Loading a model beside others no longer fails with "would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance" while the KV budget still covers every model's minimum. The split gave each model a share in proportion to its per-token KV cost alone. A resident model with a small per-token cost and a fixed per-request workspace, such as Nemotron 3.5 Lightning with its assistant on, could get less than its own minimum and block every further load. Now, when that would happen, each model gets its minimum first and the rest of the budget is split as before; the message now appears only when the minimums together exceed the budget. The model being loaded counts only the 1 GB base minimum until it is built, so Lightning itself can still fail to load, with no KV headroom, when it joins several high-rate models. +- A split that already gives every model its minimum is unchanged. Unloading a model, or a change to the activation reserve, no longer shrinks another model below its minimum. diff --git a/changelog.d/min-p-single-mac.md b/changelog.d/min-p-single-mac.md new file mode 100644 index 0000000000..9e574f2b24 --- /dev/null +++ b/changelog.d/min-p-single-mac.md @@ -0,0 +1,3 @@ +### A request's `min_p` now applies on one Mac too + +- A request's `min_p` now applies on one Mac too, as it already did on a cluster pair: tokens less likely than `min_p` times the most likely token are dropped before sampling (values above 1 count as 1). Requests without `min_p`, or with 0, are unchanged. diff --git a/docs/architecture/hardware-support.md b/docs/architecture/hardware-support.md index d351ca1964..c91f96c2e6 100644 --- a/docs/architecture/hardware-support.md +++ b/docs/architecture/hardware-support.md @@ -1,6 +1,6 @@ # Hardware support and the provider memory model -> Last updated: 2026-10-26 +> Last updated: 2026-10-31 What hardware the provider runs on and how it decides, in bytes, whether a model may load and how much KV cache each resident model may use. Read this to @@ -556,6 +556,22 @@ Unknown or saturated policy evidence and a fixed pool that cannot meet the floor fail closed. `resliceMeetsServiceabilityFloor` rejects the unattainable `Int.max` sentinel rather than accepting it as a usable grant. +Every re-slice passes those floors to `resliceGrants`; a newcomer, whose engine +does not exist yet, has only the base `minimumServiceableGrantBytes`. When the +proportional split already gives each slot at least its floor, that split is the +result. Otherwise, if the floors sum to no more than the budget, each slot +receives its floor plus its weighted share of the rest; if they do not, the +proportional split stands and `resliceMeetsServiceabilityFloor` refuses the load +or reserve raise. Regrowth after an unload or rollback uses the same floors, so +it never shrinks a slot below its floor. Without this, a slot with a small KV +rate and a fixed per-request workspace, such as `nvidia-nemotron-3.5-lightning` +with its embedded assistant, falls below its floor beside high-rate models even +when every floor fits (`EngineV2KVSizing.resliceGrants`, +`ProviderLoop.resliceAndBuildEngineV2Bundle`, `ProviderLoop.resliceGrowSurvivorsLocked`). +A newcomer's own floor is checked only when its engine is assembled, so such a +model loaded last can still receive less than its floor and fail with +`no_kv_headroom` (`EngineV2Bridge.requireServiceableOrdinaryGrant`). + A private hybrid-cache carve is added once to the engine floor. The bridge retains the total requested grant for exact rollback instead of feeding an already-carved engine grant back through the carve. Physically retained cache @@ -831,8 +847,10 @@ grant or reported capacity field changes, so replaces the first term with its own claim's ledger room, which keeps no load reserve — `ProviderLoop.evictUntilNemotronSuperFits`, `nemotronSuperLoadIsCertainToFail`. -6. Load-time re-slicing refuses a newcomer if any resulting engine share falls - below `minimumServiceableGrantBytes`; shrink preserves existing ownership — +6. Load-time re-slicing refuses a newcomer only when the slots' + `minimumServiceableGrantBytes` floors sum to more than the fleet KV budget; + otherwise every engine share is at least its floor. Shrink preserves existing + ownership — `EngineV2KVSizing.resliceGrants`, `EngineV2KVSizing.resliceMeetsServiceabilityFloor`, `AdmissionV2.updateBytesCapacity`. 7. `freeForLoadGb` applies no multiplicative discount; the only padding is the scanner's `memoryOverheadFactor` on weights — `ModelLoadAdmission.swift`, @@ -846,6 +864,7 @@ grant or reported capacity field changes, so | Start refused: Metal unavailable | `GPUEnforcement.requireMetal()` threw | `GPUEnforcement.swift` | | Load refused: "… need N GB to serve — unloaded" | Post-load `hasServeableKVHeadroom` false (live KV headroom below `minimumLoadKVBytes`) | `ProviderLoop+ModelLoading.swift`, `KVHeadroomProbe.swift` | | Load refused with `no_kv_headroom` | Slot KV sizing overflowed or no serviceable grant during construction | `EngineV2Config.swift` (`EngineV2RefusalReason.noKVHeadroom`), `EngineV2SlotFactory.swift` | +| Load refused: "loading '…' would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance (fleet KV budget … B across … slots) — refused" | The slots' `minimumServiceableGrantBytes` floors sum to more than the fleet KV budget | `ProviderLoop+EngineV2.swift` (`resliceAndBuildEngineV2Bundle`), `EngineV2Reslice.swift` (`resliceGrants`) | | Catalog says the tier fits, provider refuses | Static cap arithmetic passes but `freeForLoadGb` (real free minus `loadReserveBytes` and in-flight reservations) is below `requiredToLoadGb` | `ModelLoadAdmission.swift`, `ProviderLoop+ModelLoading.swift` | | Nemotron Super refused: "Insufficient memory (… GB of LOAD room, need … GB) …" | The claim's ledger room cannot hold its narrowest configuration, even after evicting every idle model | `provider-swift/Sources/ProviderCore/NemotronSuper/ProviderLoop+NemotronSuperAdmission.swift` | | New request cannot fit | Its complete request promise exceeds the slot grant, or live ownership/OS pressure leaves no process headroom | `AdmissionV2.swift`, `ProcessMemoryLedger.swift` | diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 45c07ff127..c61afb03fe 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -982,7 +982,11 @@ adapter is dropped from the advertised set at scan time and never loads Slot construction carries the engine's immutable admission watermark into the bridge so future load and reserve-raise checks can preserve a serviceable total grant. These [workspace-aware floors](hardware-support.md#kv-slot-grants) do not -lower the activation reserve or replace actual per-request byte admission. +lower the activation reserve or replace actual per-request byte admission. Every +re-slice, including regrowth, funds those floors first when the proportional +split alone would leave a slot below one, so the re-slice refuses a load only +when the floors together exceed the fleet KV budget. A newcomer counts only the +base floor until its engine is assembled. ### GLM5Next implementation boundary @@ -3525,6 +3529,15 @@ the system assertion wrappers in `provider-swift/Sources/ProviderCore/System/`. See [cluster member operation](../provider/cluster-always-on.md) for the limits on explicit sleep and laptop lid closure. +Under its supervisor, the cluster service writes its heartbeat to the file that +`DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE` names (`ClusterServiceAgent.healthPath`, +`service-health.json`), and the supervisor's liveness guard accepts only a beat +with the service's own PID. `ClusterService.partEnvironment` gives this Mac's +part the same key with a different file (`ClusterServiceAgent.partHealthPath`, +`part-health.json`), so a coordinator-paired part never writes over the +service's heartbeat and still waits for its registration as a supervised member. +An empty or absent key is passed on unchanged. + ## GLM tool-stream completion GLM tool output uses the SDK GLM parser to validate the complete tool suffix at @@ -5218,10 +5231,12 @@ New saves and installed startup enforce the same mode rule. Old pipeline records ## Cluster runtime facts of an installed app A coordinator-formed cluster session is admitted when its committed native start -matches the approval each member installed. The guided setup registers the -digests of such an approval from the installed app and the chosen model, so -that no person types them -([fields](../reference/configuration.md#cluster-runtime-facts)). +matches the approval each member installed. A signed release computes the +digests of such approvals from its own final app and registers them +(`cluster_runtime`), and the guided setup matches a served approval against the +installed app and the chosen model with the same computation, so that no person +types them ([fields](../reference/configuration.md#cluster-runtime-facts), +[release lane](../operations/provider-release.md#cluster-runtime-facts)). 1. The file digests (worker, metallib, paged-attention source, placement tool) come from `DistributedInstalledFiles.digest`. `DistributedInstalledFiles.verify`, @@ -5236,13 +5251,51 @@ that no person types them `resourcePolicySHA256`. A coordinator-formed start carries the approval's value, which the member and its owner compare with the installed approval (`NativePairMemberPolicy.require`). +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, + never `mlx_nax` or `glm5_next_v1`), and a coordinator holds each member of a + pair without a grant to the model's single-Mac requirements + ([`providerMeetsServingRequirementsLocked`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/registry/cluster_pair_serving_grant.go)), + so no pair of GLM-5.3-Flash or Qwen3.8-27B forms without one. For a + described model whose runtime model, catalog ID and artifact the build's + checked-in public declaration names (`ClusterPublicModels`: the owner's + decisions, with its evidence document's SHA-256), the grant names the + declared families with that digest. Any other model's grant is the public + grant a member of the same build reports for the described artifact + (`ClusterPairServingGrants.grant`, records of that artifact only), with the + SHA-256 of the records it rests on (`ClusterPairServingGrant.evidenceSHA256`). + A grant also bounds the sessions formed for the owner: a coordinator forms + none under an approval in a mode family that its grants do not name + ([`pairServingGrant`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_pair_serving_grant.go)). + Each undeclared model's records grant covers the modes its runtime serves + today; a mode added to an undeclared model later forms coordinator sessions + only once a record of that mode is bundled. +5. The parity qualifications come from the declaration only: one per declared + family and schedule. Each rank's numerics class is the one a member of that + build registers for the evidence placement + (`ClusterMemberDeviceProfile.numericsClass`, the block's Metal library); a + pipeline is cut at half the model's layers (`ClusterPublicModels.placement`); + the request envelope admits media only where the placement serves it + (`ClusterModelFeaturePolicy.mediaContract`). A coordinator applies them to + the whole declared family, on any Apple silicon pair: the placement names + the evidence, not a limit + ([fields](../reference/configuration.md#cluster-runtime-facts)). This build + places Qwen3.8-27B in tensor parallel only + (`ClusterModelFeaturePolicy.admissibleModes`), so its declared pipeline + takes effect with a build that places it as one. The + release lane runs the released build's own CLI, so the declaration and the + records are that build's. A model approval needs none of these facts: the member takes the same values from its own saved setup and files ([model approvals](../reference/configuration.md#model-approvals)). Code map: `provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift` -(`ClusterRuntimeApprovalFacts`), +(`ClusterRuntimeApprovalFacts`), `ClusterRuntimeApprovalFacts+Release.swift` (the release's model list and +candidate choice), +`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift`, +`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift`, `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledFiles.swift`, `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift`. @@ -5318,7 +5371,9 @@ 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-two 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. 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. + +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 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/developer/test.md b/docs/developer/test.md index 51b2b1d9c4..c4ef7949a9 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-29 +> Last updated: 2026-10-31 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1286,6 +1286,7 @@ make changelog-check python3 scripts/test-provider-release-resolution.py python3 scripts/test-provider-release-resume.py python3 scripts/test-provider-release-publication.py +python3 scripts/test-provider-cluster-runtime-models.py python3 scripts/test-release-dev-branch.py python3 scripts/test-provider-release-pipeline.py python3 scripts/test-provider-release-artifact.py @@ -1321,7 +1322,22 @@ prove Apple runtime behavior. with verbatim annotations, including multiline opening paragraphs, extra blank lines, CRLFs and synthetic SSH/PGP signature armor. It checks exact retained note text and payload/provenance digest guards without invoking signing or live -publication. +publication. Its cluster runtime rows pin the prod and dev payload bytes without +`cluster_runtime` to their digests from before the block existed, carry a valid +block through `stage` in dev and prod, refuse each malformed block (grants and +parity qualifications included) and a block whose derived approval, grant or +parity qualification IDs exceed 128 bytes, refuse a registration body over the +coordinator's 64 KiB limit before staging (65,536 bytes accepted, 65,537 +refused), accept the GLM-5.3-Flash block pinned from the 0.10.5-dev.branch.17 +app, and check that registration sends the block in its canonical form. +`scripts/test-provider-cluster-runtime-models.py` runs the release's +model-metadata fetch against a local HTTP registry: the environment's catalog and +CDN, candidate selection, the manifest and `config.json` checks, each candidate's +catalog entry (`id`, `input_modalities`), a listed model the catalog lacks (left out +and named), retries and refusals. It reads no weights +and uses no network. `scripts/provider-cluster-runtime-facts.sh` has no +fake-driven test; the release lane runs it on every final signed app and shows +its result in the job summary. `scripts/test-provider-release-pipeline.py` and `scripts/test-provider-release-resolution.py` pin the routing of @@ -1334,7 +1350,10 @@ from master and a master push routed to dev. A push to `dev` resolves to refused. `scripts/test-provider-release-resume.py` pins the source gate: a dev push needs environment `dev` and a verified commit on `dev` ancestry, and the tag, master push and dispatch rows keep the master checks. The pipeline test -pins the final-app check against the self-updater's designated requirement. +pins the final-app check against the self-updater's designated requirement, and +the cluster runtime facts step: after the final hashes, no secret, the keychain +removed first, its failure fatal only when `CLUSTER_RUNTIME_SEND` is true, and +`prepare` byte for byte today's command when it is not. `scripts/test-darkbloom-route.py` runs the actual [CI runner routing](build.md#ci-runner-routing) shell step against a loopback diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index 5edddbe37c..191b53d3f4 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -1,6 +1,6 @@ # Release A Provider Version -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Build, sign, notarize and publish an explicitly authorized provider artifact. The pipeline registers its exact official identity through the external platform @@ -574,8 +574,9 @@ run is a tooling failure, not a model or notarization failure. | 3 | Sign the canonical app with hardened runtime and preserve SwiftPM resources | | 4 | Copy `darkbloom`, `darkbloom-enclave` and `mlx.metallib` into regular files under `bin/`; these verification copies support current and older updaters, not flat installation | | 5 | Notarize, staple, rebuild/extract the final archive, run packaged smoke and compute final binary/archive/metallib and full CodeDirectory SHA-256 hashes | -| 6 | Run `scripts/provider-release-publication.py prepare` to retain exact registration payload, original annotated-tag notes without the signature suffix, and source/run provenance | -| 7 | Retain `provider-publication--` for 30 days; always remove the signing keychain | +| 6 | Compute the [cluster runtime facts](#cluster-runtime-facts) from the final archive, show them in the job summary and retain them as a run artifact | +| 7 | Run `scripts/provider-release-publication.py prepare` to retain exact registration payload, original annotated-tag notes without the signature suffix, and source/run provenance | +| 8 | Retain `provider-publication--` for 30 days; always remove the signing keychain | All hashes describe final signed bytes. `scripts/install.sh` and self-update verify the `bin/` files before installing the app; the external artifact verifier @@ -598,11 +599,15 @@ staging and performs these operations in order: The payload contains `version`, `platform=macos-arm64`, `backend=mlx-swift`, `binary_hash`, `bundle_hash`, `metallib_hash`, `code_directory_hash`, `source_commit`, `ci_run_id`, `require_app_attest_qualification=true`, `url` -and `changelog`. The URL is the configured CDN followed by +and `changelog`. It also contains `cluster_runtime` only when that environment's +`*_CLUSTER_RUNTIME_ENABLED` variable is `true` +([cluster runtime facts](#cluster-runtime-facts)). The URL is the configured CDN followed by `releases/v/artifacts//darkbloom-bundle-macos-arm64.tar.gz`. Use the retained payload, never hand-reconstruct hashes. The -[pinned release-handler contract](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/api/releases/release_handlers.go) -documents artifact validation; it predates automatic identity registration. +[release handler, pinned at the platform `dev` merge that accepts `cluster_runtime`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/api/releases/release_handlers.go) +validates the artifact, records the build identity and reads the block strictly +(`registry.ParseReleaseClusterRuntime`); a coordinator without that change +refuses the field (`DisallowUnknownFields`). The updated platform verifies the staged archive and records complete native identity in its durable `AppAttestBuildQualification` registry before publication @@ -641,6 +646,153 @@ environment-free signing workflow builds, stages, signs and verifies the helpers the same way. An owner signing a local build runs the same script with the Developer ID identity, then signs and notarizes the app as the workflow does. +### Cluster Runtime Facts + +Each signed release can carry the cluster runtime facts of its final app as +`cluster_runtime` in its `POST /v1/releases` payload. A coordinator that +accepts the block derives from it that build's cluster approvals, their +pair-serving grants (without one no pair of GLM-5.3-Flash or Qwen3.8-27B forms: +[why](../architecture/inference.md#cluster-runtime-facts-of-an-installed-app)), +and the parity qualifications (public traffic) of the models the build declares +public (`ClusterPublicModels`: GLM-5.3-Flash and Qwen3.8-27B in pipeline and +tensor parallel, the owner's decisions of 2026-10-31, +[evidence](../reports/2026-10-31-public-cluster-models.md)). No operator posts +approvals, grants or public qualifications per build. A coordinator applies the +qualifications to each declared family on any Apple silicon pair: the declared +placement names the evidence, not a limit, and GLM-5.3-Flash's schedule 2 +entries are inert because its runtime serves only the serial schedule +([details](../reference/configuration.md#cluster-runtime-facts)). The block +format and its rules are in the same reference. + +Every lane (dev branch, staging, prod) runs the step +`Compute cluster runtime facts from the final signed app` of job +`build-and-release`: + +1. It runs after notarization, stapling and the final-archive checks, and before + `prepare`. +2. It reads no secret. It removes the two secret-derived values in the job's + `GITHUB_ENV` (`r2_public_url`, `coordinator_url`) and deletes the signing + keychain before any release code runs. The step fails unless the keychain + file is gone and `security find-identity -p codesigning` no longer lists + `$DEVELOPER_ID`. +3. It checks the archive against `BUNDLE_HASH` and extracts it into a new + folder. Steps 4 to 6 are `scripts/provider-cluster-runtime-facts.sh`; the + app's own CLI runs with an empty environment (`env -i`), so the public + declaration and the qualification records are those of the build being + released. +4. The final CLI prints the build's model list: + ` cluster runtime-facts --list-release-models`. It holds every model + with a cluster stage adapter and a passing pair qualification record in the + build (`ClusterRuntimeApprovalFacts.releaseModels`). +5. `scripts/provider-cluster-runtime-models.py --environment ` reads the + public catalog and model CDN of the lane's environment, the ones its app + reads (`provider-swift/identity/provider-identity.json`). For each listed + artifact it fetches the `manifest.json` encodings the provider reads (CDN, + then coordinator) and `config.json` from the CDN, never weights, and saves + the catalog entry's `id` and `input_modalities` beside them + (`catalog.json`). A listed model that catalog does not have is left out and + named in the job summary. Any other fetch or integrity failure fails the + step. +6. The final CLI computes the facts: + ` cluster runtime-facts --app --release-candidates `. The + app's own worker describes each candidate (`--describe-runtime`); every + catalog model ID of a listed artifact that it describes as the listed model + gets one entry, with its pair-serving grant. A declared model gets one + parity qualification per declared family and schedule; a tensor-parallel + envelope admits the media its catalog entry lists, a pipeline's text only. A + declared pipeline whose `config.json` has no layer count is left out and + named on standard error, in the job log. One artifact can be two registered + models that only the manifest tells apart (production lists `gemma-4-26b` + and `gemma-4-26b-8bit` for one artifact): a catalog model ID whose + candidates the worker describes only as another registered model is that + model's, so it is left out and named on standard error too. The step fails + when the worker describes no candidate of a catalog model ID of a listed + artifact at all, when no model is left, or when an ID a coordinator would + derive exceeds 128 bytes. + +The steps `Show the cluster runtime facts` and `Retain the cluster runtime facts` +then write the block (or the failure) to the job summary and upload +`cluster-runtime---` (30 days), in every lane +and whether or not the block is sent. + +Whether the payload carries the block is decided by one repository variable per +environment. The job reads it as `CLUSTER_RUNTIME_SEND`, which is `true` only +when the run registers a release and the variable is set to `true` (GitHub +compares the strings case-insensitively, so `True` counts too): + +| Variable | Lane | Unset or not `true` | `true` | +|---|---|---|---| +| `DEV_CLUSTER_RUNTIME_ENABLED` | dev branch (`release-dev-branch.yml`) | The payload is byte for byte the same as without this feature; a failure of the facts step only warns (`continue-on-error`) and the release continues | `prepare --cluster-runtime ` adds the block; a failure of the facts step fails the release before staging and registration | +| `STAGING_CLUSTER_RUNTIME_ENABLED` | staging (`release-swift.yml`, master push) | as above | as above | +| `PROD_CLUSTER_RUNTIME_ENABLED` | prod (`release-swift.yml`, tag) | as above | as above | + +Staging publication is refused today ("Unknown publication environment": no +staging coordinator yet), so `STAGING_CLUSTER_RUNTIME_ENABLED` takes effect once +staging publishes. `validate` (in `prepare`, `stage` and `publish`) accepts a valid block in any +environment and refuses an invalid one, and one whose derived IDs +(`release///s<1|2>`, `/grant` for a model with a +grant, and `/q` for each parity qualification) exceed 128 +bytes. It also refuses a payload whose registration body (the bytes +`POST /v1/releases` sends, block included) exceeds the coordinator's 64 KiB +limit (`MaxReleaseRegisterBodyBytes`), so an oversized body stops before +staging. `prepare` also refuses a block file that is not canonical, and +registration sends the block in that canonical form (a body without the block +is sent exactly as before). + +With the variable set to `true`, a failure of the facts step stops the release +before `prepare`, so nothing is staged or registered. Fix the cause (for +example a catalog or CDN outage) and re-run the failed job, or first set the +variable to anything but `true` to release without the block; for a tag, sign +again with +[Resume Signing From A Retained Unsigned Build](#resume-signing-from-a-retained-unsigned-build). + +Turn a variable on only after the coordinator of that environment accepts the +block (`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES`, darkbloom-platform); +a coordinator that does not accept it yet must never receive it. Public cluster +routing also needs `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` on that +coordinator. + +Before a release with the block registers, make sure the coordinator's catalog +has room. It holds at most 64 approvals (the operator's per-build and per-model +approvals included), 64 pair-serving grants and 256 parity qualifications. A +release adds 2 approvals per model of its block (and up to 2 grants and 8 +qualifications per model). Releases are taken newest first, each whole: a +release that would pass a bound is left out, so older releases' entries drop +first, and the operator's entries are never displaced +([`NativeRuntimeCatalogWithReleases`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_release_approvals.go)). +When the catalog is short, prune the hand-posted per-build approvals of retired +builds. After the first registration, check the coordinator log: the warning +`release cluster approvals omitted` names a release left out and why, and +`cluster pair catalog replaced` reports `approvals` and `omitted_releases`; +`GET /v1/cluster/approvals` lists the derived `release///s<1|2>` +approvals. On DevNet on 2026-10-31 the coordinator served 26 approvals (25 +per-model and 1 per-build) and the catalog listed 4 models, so each dev-branch +release adds 8 approvals: the 4 newest releases fit (58 of 64) and a fifth is +left out. Check the production catalog the same way before +`PROD_CLUSTER_RUNTIME_ENABLED` is set. + +Rollout order: + +1. The platform change merges to the platform's `dev`, and DevNet deploys it. +2. A person makes room in DevNet's catalog, if needed, and sets + `DEV_CLUSTER_RUNTIME_ENABLED=true`. +3. This change merges to `dev`. The next dev-branch release registers with the + block; check the coordinator log for an omitted release. A pair registers by + itself after it updates. +4. Both repositories go `dev` to `master`. The production coordinator deploys + with its switch on, a person checks its catalog's room and sets + `PROD_CLUSTER_RUNTIME_ENABLED=true`, and the release tag follows. + +To compute the facts of an installed or downloaded app by hand, give the models +explicitly. Run that app's own CLI, so the public declaration and the records +are that build's. A model given by hand has no catalog entry, so a declared +model's request envelope then admits text only: + +```bash +"/Applications/Darkbloom.app/Contents/MacOS/darkbloom" cluster runtime-facts \ + --app /Applications/Darkbloom.app --model Qwen3.5-9B=/path/to/Qwen3.5-9B-folder +``` + ## Recovery ### Resume Signing From A Retained Unsigned Build diff --git a/docs/provider/cli-reference.md b/docs/provider/cli-reference.md index 557fb57fb4..abab9afda0 100644 --- a/docs/provider/cli-reference.md +++ b/docs/provider/cli-reference.md @@ -1,6 +1,6 @@ # Provider CLI reference -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Reference for the `darkbloom` command-line tool: every subcommand and flag, the files and identifiers it creates, the `provider.toml` keys it reads with their @@ -2453,7 +2453,7 @@ defines the response and supported saved widths. Source: ### Qwen27 TP assistant setup and native diagnostics -Run the normal `darkbloom cluster` setup for the catalog Qwen3.8 27B model. Its embedded assistant is discovered and fully priced under the existing `backend.mtp_mode` setting; no internal verification or inventory option is required in the normal flow. Verify the saved policy against both workers' actual READY before serving. Explicit `off` retains the ordinary target with its complete width-one quote. See [configuration](../reference/configuration.md#qwen27-tp-assistant-policy) and [native ownership](../architecture/inference.md#qwen27-tensor-parallel-resident-assistant). +Run `darkbloom cluster local` for the catalog Qwen3.8 27B model to serve it with its embedded assistant. The assistant is discovered and fully priced under the existing `backend.mtp_mode` setting; no internal verification or inventory option is required in the normal flow. Verify the saved policy against both workers' actual READY before serving. Plain `darkbloom cluster` serves through Darkbloom, and under the default `auto` it plans the model without the assistant, because a setup registered with the coordinator carries none (the assistant is not qualified for public traffic). Explicit `on` keeps the assistant there too, and the pair is then not offered to the coordinator. Explicit `off` retains the ordinary target with its complete width-one quote. See [configuration](../reference/configuration.md#qwen27-tp-assistant-policy), [the speed tradeoff](two-mac-cluster.md#the-steps-once) and [native ownership](../architecture/inference.md#qwen27-tensor-parallel-resident-assistant). The internal worker still accepts diagnostic `--mtp-depth N` in 1...4 for keyed 9B or 27B Qwen TP with paged KV (the A3B rows' heads are not loaded, so an explicit depth is refused for them). Installed launches also carry the pinned inventory and typed verification mode from the saved policy; these are implementation arguments, not user setup choices. Omitted policy preserves the legacy ordinary contract. Unsupported model, memory, backend, startup and conflicting speculative controls are refused before serving. diff --git a/docs/provider/cluster-always-on.md b/docs/provider/cluster-always-on.md index 4d17cf1a98..d4b21423f9 100644 --- a/docs/provider/cluster-always-on.md +++ b/docs/provider/cluster-always-on.md @@ -1,6 +1,6 @@ # Keep a cluster member always on -> Last updated: 2026-10-20 +> Last updated: 2026-10-31 `darkbloom cluster` on each Mac does all of this. Nothing below is needed: it explains what the onboarding sets up and how to check it. @@ -27,10 +27,18 @@ the cluster comes back by itself, with no command run on either Mac (see [After a restart or a power cut](#after-a-restart-or-a-power-cut)). - launchd runs `darkbloom cluster service --supervise`: the same supervisor as - below, around `darkbloom cluster service`. A service that ends is restarted - after 15 s, doubling to 300 s; three runs in a row each shorter than 120 s - park it (nothing runs) until `darkbloom cluster` is run again, which - restarts it and resets the budget. + below, around `darkbloom cluster service`, without its update slot. A service + that ends is restarted after 15 s, doubling to 300 s; three runs in a row each + shorter than 120 s park it (nothing runs) until `darkbloom cluster` is run + again, which restarts it and resets the budget. +- Nothing updates Darkbloom on these Macs: the supervisor runs with automatic + updates off (`provider-swift/Sources/darkbloom/ClusterServiceCommand.swift`, + `runSupervisor`), this Mac's part runs no updater + (`provider-swift/Sources/ProviderCore/ProviderLoop+Serve.swift`, which starts + `startAutoUpdateMonitor` only for a single-Mac provider), and the single-Mac + provider does not run beside the cluster. Run `darkbloom update` on both Macs + ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)); + automatic updates for a pair are a follow-up. - `RunAtLoad`, and `KeepAlive` only after an unsuccessful exit (throttled to the budget's first backoff): launchd brings back a supervisor that crashed, never one that was stopped. @@ -246,7 +254,7 @@ it. It documents the developer route that runs `darkbloom start | The leader's pair engine stays wedged (its own watchdog's verdict) for 180 s | Same recycle | | An active request made no progress at all for `clamp(120, 120 + prompt tokens / 1000, 900)` s (when the member reports one) | Same recycle | | A pair forms | The leader runs one greedy 8-token warmup request before the pair accepts work; if it fails or takes over 300 s the pair is retired and formed again (`DARKBLOOM_CLUSTER_WARMUP=0` turns this off) | -| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together | +| Cluster update slot (every 30 min, at an offset fixed by the cluster ID, the same on both Macs), on this route only, with `auto_update` on (the default) | If a release is available: drains the member, installs, restarts from the new binary; both Macs do this together. The cluster service of `darkbloom cluster` has no update slot ([updating Darkbloom on the pair](two-mac-cluster.md#updating-darkbloom-on-the-pair)) | | `darkbloom stop` | Drains, stops the member and keeps it stopped across reboots | | Before every run, and at the member's own start and end | Orphan sweep: a worker or owner whose parent is gone is given its own contract to end, then SIGTERM, SIGKILL only after the kill margin; a stranded device journal is cleared once nothing it names runs; bootstrap directories whose socket no process holds any more are removed (read from the descriptor tables; nothing connects). One log line when it found something (`darkbloom cluster reap --json` runs the same sweep by hand) | diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index 3da69fd26d..74ec3a42d6 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-26 +> Last updated: 2026-10-31 Run the provider's inference engine as an OpenAI-compatible HTTP server on your own Mac, either standalone (`darkbloom start --local`, no coordinator, no @@ -53,7 +53,10 @@ See [inference and logprob admission](../architecture/inference.md). when `[backend] startup_preload` is enabled (the default). When a load is short of headroom the server first releases retained paged KV segments and drops the MLX buffer cache once, then evicts the least recently used idle - slot (`StandaloneServer.ensureMemoryHeadroomForLoad`). The explicit + slot (`StandaloneServer.ensureMemoryHeadroomForLoad`). Resident models share + the KV budget as [KV slot grants](../architecture/hardware-support.md#kv-slot-grants) + describes; a load that would leave any model below its minimum grant fails + with HTTP 503 (`StandaloneServer.resliceKeepsSlotsServiceable`). The explicit `preload_models` list takes precedence; slot and memory limits can skip a model, which still loads on request. A local GLM qualification load reads its weights for its own per-file SHA-256 verification and the tensor reads only; diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 57473bd6cf..28ca6d7b72 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -1,6 +1,6 @@ # Two Macs as one provider (guided setup) -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Two Apple Silicon Macs joined by one Thunderbolt 5 cable serve a model together: each Mac holds part of its layers, and the pair serves as one provider. Setting @@ -74,6 +74,35 @@ cluster plan` says how many records it left out). A request that answers fewer than 64 tokens (the setup's test answer, a quick "Say hi") is not counted as a speed and does not shape the plan. +Qwen3.8 27B in tensor parallel can also decode with the speculative assistant +its artifact ships, but only on a cluster that serves locally only. The +assistant is not qualified for public traffic, and a setup registered with the +coordinator never carries it. So, with the default `[backend] mtp_mode` of +`auto`: + +| You run | Qwen3.8 27B decodes | One request on two M5 Ultras (2026-10-31) | The coordinator | +|---|---|---|---| +| `darkbloom cluster` | without the assistant | about 40 tokens/s | the pair registers when the coordinator serves a matching approval | +| [`darkbloom cluster local`](#serving-locally-only) | with the assistant | about 93 tokens/s | never contacted | + +With `mtp_mode = "on"`, `darkbloom cluster` keeps the assistant too. That pair +is then not offered to the coordinator: its plan says "not offered for public +traffic", and it serves on the leader's local API. A serving cluster switched +with `l` or `p` keeps the setup it has; press `m` to plan the model again for +the new way of serving. Public speculative decoding for Qwen pairs needs +qualification evidence of its own, which no record holds yet. Rules: +[Qwen27 TP assistant policy](../reference/configuration.md#qwen27-tp-assistant-policy). + +A JSON `response_format` request that a single Mac would answer under a grammar +(no tools or `tool_choice`, no media, a schema the grammar covers) is refused on +a Qwen pair before any output: a pair's ranks cannot apply the grammar +(`constrained_decoding_unsupported`, HTTP 400). The coordinator moves a public +request refused this way to a single Mac, which constrains it +(darkbloom-platform `fix/coord-pair-refusal-failover`); a request to the owner's +local cluster API gets the refusal. Other JSON requests are served with the +format instruction only, as on one Mac +([constrained Qwen JSON answers](../architecture/inference.md#constrained-qwen-json-answers)). + | # | Where | What you do | What it asks | |---|---|---|---| | 1 | the first Mac | Run `darkbloom cluster`. It checks the Thunderbolt cable ("Cable found.", "Cable ready."). Nobody waits on the cable yet, so it says **"On your other Mac, run `darkbloom cluster`."** and waits (q cancels). With two cables it asks which one to use. | one macOS administrator approval when the selected port needs configuration ("Darkbloom needs network access for the cluster cable") | @@ -150,10 +179,16 @@ The pair also serves on the leader's local API, both Macs without the approval, when the coordinator gives no answer for the absence grace (10 minutes, the same grace as in [if a Mac goes away](#if-a-mac-goes-away)), when it no longer lists the approval, or when the coordinator-paired parts end three -times in a row right after starting. When the coordinator lists a matching -approval again, the pair registers again (after repeated failures, only with a -later approval). Both Macs carry the same approval, or neither does: the leader -compares the two at every check. +times in a row right after starting. An end the coordinator decides is not +counted: one because it could not be reached, or because it did not accept the +part's registration in time, as during a coordinator deploy. This complements +the coordinator's side: a coordinator that ends each pair session before its +shutdown closes the members' connections gives a deploy cleaner ends, and this +rule still covers a coordinator without that change, a coordinator crash and a +slow registration. When the coordinator lists a matching approval again, the +pair registers again (after repeated failures, with the same approval an hour +later, or at once with a later one). Both Macs carry the same approval, or +neither does: the leader compares the two at every check. What `darkbloom cluster` status says in each mode: @@ -162,7 +197,7 @@ What `darkbloom cluster` status says in each mode: | Registered | `Registered with the coordinator as a cluster member: approval , until .` | | Coordinator gave no answer for the grace | The API line, then `The coordinator has not answered for 10 minutes: the pair serves on the leader's local API until it answers again, then it is offered again with approval .` | | Approval no longer listed | The API line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | -| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API until the coordinator lists a later one.` | +| Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | | Approval ended | The API line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | | No approval (production, staging, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | @@ -190,7 +225,9 @@ to keep waiting (it leads) and the other says so and joins it. choice, planner, copies, speculative decoding, caches, failover and stop as `darkbloom cluster`, but no Mac of the cluster contacts a coordinator. Nothing registers, sends heartbeats, takes public traffic or bills, and serving needs -no network beyond the cable. +no network beyond the cable. It is also where Qwen3.8 27B in tensor parallel +decodes with its speculative assistant under the default `mtp_mode` +([above](#the-steps-once)). 1. On the leader, run: @@ -482,12 +519,37 @@ a restart, and writes why to `~/.darkbloom/cluster-setup/service.log`. After a restart or power cut a Mac serves again once it is logged in. With automatic login on (System Settings → Users & Groups; needs FileVault off) that -happens by itself; `darkbloom cluster` says which applies to each Mac. After a -Darkbloom update, the cluster sets itself up again by itself ("Updating the -cluster setup after a Darkbloom update."). The leader checks for an update -every minute; while a Mac serves, those checks and any plan made then use the -speed it measured while idle and never run a GPU benchmark beside the model -([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +happens by itself; `darkbloom cluster` says which applies to each Mac. + +## Updating Darkbloom on the pair + +The Macs of a pair do not update by themselves. The cluster service runs with +automatic updates off, its parts run no updater, and the single-Mac provider, +whose updater keeps one Mac current, does not run beside the cluster. +Automatic updates for a pair are a follow-up. Until then, update by hand: + +1. On each Mac, run: + + ```bash + darkbloom update + ``` + + It installs the release. Its last line, "Restart the provider for the new + version to take effect.", does not apply here: no single-Mac provider runs on + a pair Mac. +2. Wait. The leader compares each Mac's installed cluster worker with the saved + setup every minute while the cluster serves. When one changed, it stops both + parts, plans the same model again and serves it from the new release + ("Updating the cluster setup after a Darkbloom update."). Its log, + `~/.darkbloom/cluster-setup/service.log`, says + `Darkbloom changed on the other Mac: setting the cluster up again for ` + (or this Mac, or both Macs). An update of the second Mac sets it up once more. + While a Mac serves, these checks and any plan made then use the speed it + measured while idle and never run a GPU benchmark beside the model + ([device profile](../architecture/inference.md#automatic-local-cluster-batching)). +3. Log out and back in on each Mac, or restart it. The cluster service itself + keeps running the release it started with until it starts again, as it does + at login. ## When something is in the way @@ -548,6 +610,8 @@ and they must match. ## Not yet in this build +- A pair does not update itself: run `darkbloom update` on both Macs + ([updating Darkbloom on the pair](#updating-darkbloom-on-the-pair)). - The login agent and macOS's one Local Network approval need the signed Darkbloom.app ([always on](cluster-always-on.md)). - A setup with unequal tensor-parallel shares cannot register with the diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0c836383e8..f3cc785efd 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-30 +> Last updated: 2026-10-31 Provider CLI and native-runtime environment variables, compiled defaults and reading symbols. Secrets are named, never valued. Unless specified otherwise, values are read at process start. @@ -920,37 +920,99 @@ pair. ### Cluster runtime facts -The cluster runtime facts are the digests of one installed app's cluster -helpers and, for each model, of the capability its own worker describes. The -coordinator operator copies them into a cluster approval in the operator -approval file. After the Test stage, the guided setup reads the approvals the -coordinator serves (`GET /v1/cluster/approvals`) and takes the one whose -digests equal this Mac's facts -([coordinator-paired member](#coordinator-paired-member)), and each member -checks it against its own installed files with the same computation. One type computes every value: +The cluster runtime facts are the digests of one app's cluster helpers and, for +each model, of the capability its own worker describes, with each model's +pair-serving grant and the parity qualifications of the models that build +declares public. A signed release registers them as `cluster_runtime` in its +`POST /v1/releases` payload when its environment's variable is on +([release lane](../operations/provider-release.md#cluster-runtime-facts)), and a +coordinator that accepts the block derives that build's cluster approvals, their +pair-serving grants and their parity qualifications from it. An operator may +still copy the digests into a cluster approval in the operator approval file. +After the Test stage, the guided setup reads the approvals the coordinator +serves (`GET /v1/cluster/approvals`) and takes the one whose digests equal this +Mac's facts ([coordinator-paired member](#coordinator-paired-member)), and each +member checks it against its own installed files with the same computation. One +type computes every value: `provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift` (`ClusterRuntimeApprovalFacts`). The hidden command `darkbloom cluster runtime-facts --app --model =` prints them -in their canonical form. No value is typed by hand. Only a build-pinned entry -needs these facts. A model approval names no runtime digest, and the provider -computes no facts for it ([model approvals](#model-approvals)). +in their canonical form; run the app's own CLI, so the declaration and the +records are that build's. With `--release-candidates ` (the release +lane) it describes every model the build lists from its environment's catalog +metadata (`ClusterRuntimeApprovalFacts.release`). One artifact can be two +registered models that only the manifest tells apart (production lists +`gemma-4-26b` and `gemma-4-26b-8bit` for one artifact): a catalog model ID +whose candidates the worker describes only as another registered model is that +model's, so it is left out and named on standard error. No value is typed by +hand. Only a build-pinned entry needs these facts. A model approval names no +runtime digest, and the provider computes no facts for it +([model approvals](#model-approvals)). | Field | Value | |---|---| -| `schema` | `darkbloom_cluster_runtime_v1` | +| `schema` | `darkbloom_cluster_runtime_v2` | | `native_runtime_sha256` | SHA-256 of the signed `Contents/Helpers/darkbloom-cluster-worker` | | `metallib_sha256` | SHA-256 of `Contents/Helpers/mlx.metallib` | | `resource_library_sha256` | SHA-256 of `Contents/Helpers/pagedattention.metal` | | `placement_policy_sha256` | SHA-256 of the signed `Contents/Helpers/darkbloom-cluster-plan` | -| `models` | 1 to 32 entries, sorted by `model` in byte order, unique | +| `models` | 1 to 64 entries, sorted by `model` in byte order, unique | | `models[].model` | the catalog model ID the manifest names (`model_id`); 1 to 128 printable ASCII bytes | | `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[].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`, then `tensor_parallel`) and schedule (ascending), with the fields below. At most 8 | +| `…schedule` | `1` or `2`: the derived approval it qualifies | +| `…numerics_classes` | each rank's `ClusterMemberDeviceProfile.numericsClass` of the evidence placement with this block's `metallib_sha256`, for example `g17d-nax1-mlx-98bab9d7-macos27.0` (Apple M5 Ultra, NAX on, macOS 27.0); two, the members of a derived approval | +| `…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); without a layer count the pipeline's qualifications are left out and the command names the family on standard error. `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-10-31T00:00:00Z` | +| `…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`: both declared models 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`, +`glm-5.3-flash`) and Qwen3.8-27B (`registered_qwen38_27b`, +`EigenLabs/Qwen3.8-27B-4bit-mtp`), each in `pipeline` and `tensor_parallel` on +schedules 1 and 2, on the owner's decisions of 2026-10-31 +([evidence](../reports/2026-10-31-public-cluster-models.md)). Every other +model's clusters serve their owner only. + +The declared placement names the evidence; it does not limit public traffic. A +coordinator applies a promotable parity qualification to its approval's whole +mode family: a session whose placement no record matches exactly takes the +family's promotable records, merged under the request envelope they all allow, +on any numerics classes, cuts and shares, unless a diverged record of the same +numerics-class combination withholds it +([`parityQualification`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_parity_qualification.go)). +Under a derived approval, public traffic for GLM-5.3-Flash and Qwen3.8-27B is +therefore admitted in pipeline and tensor parallel on any Apple silicon pair, +within the envelope. No pipeline of either model ran on two Apple M5 Ultras, +and GLM-5.3-Flash has no tensor-parallel cross-cable record: both rest on the +owner's decision of 2026-10-31 and the DevNet serving results. GLM-5.3-Flash's +runtime serves only the serial prefill schedule (`supportedPrefillSchedules` +of its registered specification), so its schedule 2 approval, grant and +qualifications are inert. The setup's public-traffic line says a +declared model is qualified for public traffic in its declared families, with +or without a bundled record of them (`ClusterPairServingGrants.publicTrafficLine`). +Every model the records or the declaration qualify needs its grant: without one +a coordinator holds each member of a pair to the model's single-Mac +requirements ([why](../architecture/inference.md#cluster-runtime-facts-of-an-installed-app)). Every digest is 64 lowercase hex and nonzero. The canonical form is JSON with -sorted keys and no whitespace. Why each digest is the one a member compares: +keys sorted by byte, no whitespace and no trailing newline; `null` is written, +never omitted. The strict decoder (`init(canonical:releaseVersion:)`) refuses an +unknown, missing or repeated field, another schema (v1 included) and a model whose +derived IDs for the release version exceed 128 bytes: `release///s<1|2>`, +for a model with a grant `/grant`, and for each parity +qualification `/q`, n counting that schedule's +qualifications from 1 in block order (a declared model's `q1` is its pipeline, +`q2` tensor parallel). `scripts/provider-release-publication.py` applies the +same rules to the block, requires its canonical bytes and sends it in that form +within the registration body, but computes no digest. Why each digest is the +one a member compares: [cluster runtime facts of an installed app](../architecture/inference.md#cluster-runtime-facts-of-an-installed-app). ### Sharded placement and the hand-off opt-in @@ -1012,12 +1074,13 @@ with an optional `nativeMember` object and runs `darkbloom start selector matches the two registrations itself (see [pair formation](cluster-control-protocol.md#pair-formation)). -**Automatic (guided setup).** The coordinator operator adds a cluster approval -by hand to the operator approval file +**Automatic (guided setup).** The coordinator derives build-pinned cluster +approvals from a signed release that carries `cluster_runtime` +([cluster runtime facts](#cluster-runtime-facts)), or the coordinator operator +adds a cluster approval by hand to the operator approval file ([`EIGENINFERENCE_CLUSTER_PAIR_CATALOG`](#experimental-cluster-pairs)). A build-pinned entry has the digests that `darkbloom cluster runtime-facts --app - --model =,` prints -([cluster runtime facts](#cluster-runtime-facts)). A model approval has no + --model =,` prints. A model approval has no runtime digests ([model approvals](#model-approvals)). The coordinator serves the loaded entries. After the Test stage of `darkbloom cluster` passes, the control leader takes the entry for this pair and @@ -1036,9 +1099,9 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Save | Both parts stop. The leader checks the entry, sends it to the other Mac over the cable (service command `approval`), and saves it only after the other Mac checked and saved it. A refusal on either Mac saves it on neither. Both parts then start as cluster members | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift` (`run`, `receive`) | | When | After the guided setup's Test stage passed (control operation `register`, run by the control leader: `OnboardingLive.localRegister`), once at each start of the control leader's cluster service and after an update re-adopted the setups (the re-adopted setups find the same model approval again, because it names no build), and every minute while a serving pair is offered or has its approval kept aside (`ClusterService.checkApproval`). A local-only cluster never asks (`ClusterApprovalSync.asks`) | as named | | 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 because the coordinator was out of reach is not counted). When either Mac cannot save, both keep the approval and the next check tries again. The leader keeps the approval, the reason and the setup's worker digest in its setup record (`approvalSetAside`, `runtimeBinarySHA256`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, only a later entry, or the same entry after an update installs another worker (a record without the worker digest keeps the same entry aside on every build) | `ClusterApprovalCheck.step`, `ClusterApprovalSync.serveLocally`; `ClusterService.checkApproval` | +| 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, so no part stops for an approval it refuses. A busy command lock waits for the next check, a minute later | `ClusterService.checkApproval`, `ClusterApprovalSync.apply` | +| 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` | 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 @@ -1565,12 +1628,12 @@ For the existing `qwen35-dense-layer-stage` / `registered_qwen38_27b` / `registe ### Qwen27 TP assistant policy -Normal setup discovers the embedded assistant from the native quote; the saved fields below bind that decision through both workers' actual READY. +Normal setup discovers the embedded assistant from the native quote on a cluster that serves locally only; the saved fields below bind that decision through both workers' actual READY. The assistant's speculative decoding has no parity qualification, so a setup saved for coordinator pairing carries none; public speculative decoding for Qwen pairs needs qualification evidence of its own. | Setting | Bound and behavior | Source | |---|---|---| -| `[backend] mtp_mode` | Existing `auto`/`on` allow embedded-assistant discovery for the 9B and the 27B (`ClusterQwenTensorAssistantPolicy.runtimeModelIDs`); `off` retains the ordinary fully quoted target. Automatic discovery selects depth `3` and admitted-cohort verification. | `provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift`, `automaticCandidate`, `automaticDepth` | -| Saved `tensorAssistant` | Optional `qwen27_tensor_assistant_v1` object containing `depth` 1...4 and native `inventorySHA256`; omitted policy preserves legacy ordinary setup bytes. | `libs/darkbloom-cluster/Sources/DarkbloomClusterProtocol/ClusterQwenTensorAssistantPolicy.swift`, `ClusterQwenTensorAssistantPolicy` | +| `[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`) | | 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/reports/2026-10-31-public-cluster-models.md b/docs/reports/2026-10-31-public-cluster-models.md new file mode 100644 index 0000000000..5c2781fbf0 --- /dev/null +++ b/docs/reports/2026-10-31-public-cluster-models.md @@ -0,0 +1,128 @@ +# Public cluster models: GLM-5.3-Flash and Qwen3.8-27B + +> Last updated: 2026-10-31 + +This record is the evidence document of the provider's public cluster model +declaration (`ClusterPublicModels`): the declaration's `evidenceSHA256` is the +SHA-256 of this file, and every release's cluster runtime facts name it. It +records the owner's decisions and the checks they rest 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-10-31: + +- "public traffic should not be manual" +- "only glm 5.3 flash should be serving public & qwen 3.8 27b they are both good + to go they should be approved for serving" +- on the mode families: "It should be tensor or pipeline obviously but that + shouldn't matter for the coordinator" + +The owner approved both modes, pipeline and tensor parallel, for both models, +and the public qualification of both models is done. No other model serves +public cluster traffic: a cluster of any other model serves its owner only. + +## Declared models + +| Runtime model | Catalog model | Artifact | Mode families | Schedules | +|---|---|---|---|---| +| `registered_glm53_flash` | `glm-5.3-flash` | `3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | +| `registered_qwen38_27b` | `EigenLabs/Qwen3.8-27B-4bit-mtp` | `bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463` | `pipeline`, `tensor_parallel` | 1 (serial), 2 (one-chunk lookahead) | + +The artifacts are the ones the cluster runtime registers for the two models. +Each family is qualified on 2 ranks, each an Apple M5 Ultra (GPU architecture +`applegpu_g17d`, NAX on) on macOS 27.0, at 2026-10-31T00:00:00Z: + +| Family | Mode | Cuts | Shares | +|---|---|---|---| +| `pipeline` | `pipeline_v1` | `[num_hidden_layers / 2]` (integer division): `[22]` for GLM-5.3-Flash (45 layers), `[32]` for Qwen3.8-27B (64 layers) | not applicable | +| `tensor_parallel` | `tensor_parallel_v1` | `[]` | equal | + +Both models' `config.json` give the layer count as `text_config.num_hidden_layers`; +neither has a top-level `num_hidden_layers`. + +## What was run + +Recorded by the owner's team on DevNet; this record restates the results and +does not re-run them. + +- GLM-5.3-Flash and Qwen3.8-27B served in tensor parallel on two Apple M5 Ultra + Macs with 256 GB each, connected over Thunderbolt 5, on DevNet builds + 0.10.5-dev.branch.14 to 0.10.5-dev.branch.16. The guided setup's test request + "Name three colors." was answered "Red, blue, and green."; GLM-5.3-Flash + decoded at 120 to 128 tokens per second in that test. +- The fixed greedy answers of both models were identical across the build + changes of 2026-10-30 (12 of 12). +- `ClusterAPIParityTests` + (`provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityTests.swift`: + the cluster endpoint answers the same requests as the single-Mac endpoint) + passed 12 of 12 local runs. +- Best measured speeds: + +| Model | Decode, one request | Decode, 8 concurrent requests | Prefill | +|---|---|---|---| +| GLM-5.3-Flash | about 118 tok/s | about 150 tok/s | about 4,100 tok/s | +| Qwen3.8-27B | about 82 tok/s | about 98 tok/s | about 1,465 tok/s | + +This record holds no pipeline run on two Apple M5 Ultras. + +## Bundled cross-cable records + +The qualification records the build bundles +(`ClusterPairQualificationRecordsBundled`) for these artifacts: + +- Qwen3.8-27B, `tensor_parallel_v1`: 15 passing records over `jaccl`, 13 with + the `one_chunk_lookahead_v1` schedule (prompts up to 32,768 tokens) and 2 with + `serial_v1`, run on an Apple M3 Ultra with an Apple M5 Max (13) or with an + Apple M5 Ultra (2). +- Qwen3.8-27B, `pipeline_v1`: 6 passing records over `jaccl`, all with the + `one_chunk_lookahead_v1` schedule (prompts up to 30,720 tokens): 5 on an + Apple M3 Ultra with an Apple M5 Max (cuts 16, 32, 48 and 60) and 1 with an + Apple M5 Ultra (cut 8). The `pipeline` family also has 6 passing + `pipeline_compact_decode_v1` records. +- GLM-5.3-Flash: 1 passing `pipeline_v1` record (an Apple M3 Ultra with an + Apple M5 Max, cut 39, `serial_v1`) and no `tensor_parallel_v1` record. Its + pipeline rests on that run and the owner's ruling; its tensor parallel rests + on the owner's decision and the DevNet serving results above. + +## Pair-serving grants + +A pair member reports only hardware capabilities +(`DistributedServingEligibility.memberCapabilities`, called from +`provider-swift/Sources/darkbloom/StartCommand+ClusterMember.swift`): `apple_m5` +on an M5, never `mlx_nax` or `glm5_next_v1`. A coordinator holds each member of +a pair without a pair-serving grant to the model's single-Mac requirements +([`providerMeetsServingRequirementsLocked`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/registry/cluster_pair_serving_grant.go)), +which no member meets for GLM-5.3-Flash (`mlx_nax`, `glm5_next_v1`) or +Qwen3.8-27B (`mlx_nax`). Without a grant no pair of either model forms, for its +owner or the public (David's finding, 2026-10-31). + +A release's cluster runtime facts therefore carry a pair-serving grant for each +model. A declared model's grant names its declared families, with this file as +its evidence. Any other model's grant is the one the build's bundled records +give its artifact (`ClusterPairServingGrants.grant`), with the SHA-256 of those +records as its evidence; a model the records grant nothing has none. + +## Request envelope + +Both models, both families: sampling and tool calls are allowed, and +`max_prompt_tokens` and `max_output_tokens` are 1,048,576 (the coordinator's +maximum, so only the model's own limits apply). Media follows what the +placement serves (`ClusterModelFeaturePolicy.mediaContract`). In tensor +parallel both models take media as the single-Mac product does +(`ClusterGLMMedia`, `ClusterQwenMedia`): `vision` holds when the model's +catalog entry in the release's environment lists `image` in +`input_modalities`, and `video` when it also lists `video`. A pipeline serves +text only, so its envelope admits neither. GLM-5.3-Flash's DevNet catalog entry +lists `text`, `image` and `video`; Qwen3.8-27B's lists `text` and `image`. + +## Where it is used + +`provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift` +declares the two models with this file's SHA-256. A release's cluster runtime +facts (`cluster_runtime`) carry, for a declared model, the grant of its declared +families and one parity qualification for each declared family and schedule: +`pipeline` first, then `tensor_parallel`. A coordinator that derives approvals +from releases derives their grants and parity qualifications from them +([provider release](../operations/provider-release.md#cluster-runtime-facts)). diff --git a/docs/reports/README.md b/docs/reports/README.md index ec125e58f1..96e0b79cef 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -1,9 +1,10 @@ # Provider And Native Evidence -> Last updated: 2026-10-22 +> Last updated: 2026-10-31 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. +- [Public cluster models](2026-10-31-public-cluster-models.md) - the owner's declaration of GLM-5.3-Flash and Qwen3.8-27B 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) - [Startup shape warmup: first-request TTFT](2026-10-21-startup-shape-warmup-first-request.md) diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift index 9470e84406..eb481decf4 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterConfiguration.swift @@ -104,6 +104,14 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { /// run different Darkbloom builds); the onboarding says it in plain words (`ClusterSetupPlanning.differentBuilds`). static let peerBuildDiffers = "Peer native build differs from the capability" + /// The refusal of a tensor assistant beside `nativeMember`. Its speculative decoding has no parity qualification, + /// so it serves local clusters only; the guided setup plans a cluster served through Darkbloom without it under + /// `auto` (`ClusterPlacementTensorAssistantSelection.discoveryMode`). The leader's check of a coordinator's + /// approval runs this rule before any part stops (`ClusterApprovalAttachment.attachment`). Short enough to reach + /// the leader whole through the other Mac's refusal (`ClusterSetupFailure` keeps 240 characters). + static let tensorAssistantServesLocally = "Qwen's speculative assistant serves local clusters only (not qualified for " + + "public traffic); with mtp_mode \"auto\", press m in `darkbloom cluster` to plan without it" + func validate(capability: ClusterRuntimeCapability, rawCapabilitySHA256: String) throws { func require(_ value: Bool, _ message: String) throws { guard value else { throw ClusterConfigurationError.invalid(message) } @@ -161,8 +169,9 @@ public struct ClusterConfiguration: Codable, Sendable, Equatable { try require(ClusterQwenTensorAssistantPolicy.runtimeModelIDs.contains(capability.runtimeModelID) && capability.adapterID == ClusterRuntimeAdapter.qwen35Dense.rawValue && selectedGenerationMode == .tensorParallel && selectedPrefillSchedule == .serial - && !capability.hasPrivateImages && nativeMember == nil, - "A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup") + && !capability.hasPrivateImages, + "A tensor assistant requires Qwen TP on a row with an inline head and serial prefill") + try require(nativeMember == nil, Self.tensorAssistantServesLocally) } try require(ClusterConfigurationSyntax.ipv4(coordinator.address) && (1...65535).contains(coordinator.port), "Invalid JACCL coordinator address") if let linkControl { diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift new file mode 100644 index 0000000000..8e43fc4489 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts+Release.swift @@ -0,0 +1,107 @@ +import Foundation +import DarkbloomClusterProtocol + +/// The facts a signed release registers (`cluster_runtime`), computed by the +/// release's own CLI and worker from its final signed app: the models this +/// build qualifies on a cluster, described from the metadata of the target +/// environment's catalog (`scripts/provider-cluster-runtime-facts.sh`), with +/// each model's pair-serving grant and the parity qualifications of the models +/// this build declares public. +extension ClusterRuntimeApprovalFacts { + /// A model a release describes: a registered model with a cluster stage + /// adapter and a passing pair qualification record on this artifact. + public struct ReleaseModel: Codable, Hashable, Sendable { + public let runtimeModelID: String + public let artifactSHA256: String + + public init(runtimeModelID: String, artifactSHA256: String) { + self.runtimeModelID = runtimeModelID; self.artifactSHA256 = artifactSHA256 + } + + enum CodingKeys: String, CodingKey { + case runtimeModelID = "runtime_model_id" + case artifactSHA256 = "artifact_sha256" + } + } + + /// The models this build qualifies on a cluster, from its own bundled + /// qualification records (`ClusterPairServingGrants.records`): the one + /// source of a release's model list. + public static var releaseModels: [ReleaseModel] { qualifiedModels(records: ClusterPairServingGrants.records) } + + static func qualifiedModels(records: [ClusterPairQualificationRecord]) -> [ReleaseModel] { + Set(records.filter { + $0.isConsistent && $0.outcome == .passed && ClusterPairServingGrants.hasStageAdapter(runtimeModelID: $0.runtimeModelID) + }.map { ReleaseModel(runtimeModelID: $0.runtimeModelID, artifactSHA256: $0.artifactSHA256) }) + .sorted { ($0.runtimeModelID, $0.artifactSHA256) < ($1.runtimeModelID, $1.artifactSHA256) } + } + + /// The facts a release registers. For every model in `models` and every + /// catalog model ID among the candidates of its artifact (a member may have + /// installed the artifact under any of them), the first candidate the + /// worker describes as that model. One artifact can be two registered + /// models, told apart by the manifest (`gemma-4-26b` and `gemma-4-26b-8bit`): + /// a catalog model ID whose candidates the worker describes only as another + /// registered model is that model's, so it is left out and named through + /// `note`. Candidates of an artifact not in `models` are never described, + /// and a listed model with no candidate is left out: the environment's + /// catalog does not have it, and the fetch step names it. Each candidate's + /// catalog entry gives a declared model's request envelope its media. Fails + /// naming every catalog model ID of which the worker describes no candidate + /// at all, and when no model is left (naming what was left out). + public static func release(installation: Installation, candidates: [ModelFiles], + models: [ReleaseModel] = ClusterRuntimeApprovalFacts.releaseModels, + publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, + decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions, + note: (String) -> Void = { _ in }) throws -> Self { + let installed = try HashedInstallation(installation) + let parsed = try candidates.map { ($0, try catalogArtifact($0)) } + var entries: [Model] = [], failures: [String] = [], leftOut: [String] = [] + for listed in models { + let ofArtifact = parsed.filter { $0.1.aggregateSHA256 == listed.artifactSHA256 } + var catalogIDs: [String] = [] + for (_, artifact) in ofArtifact where !catalogIDs.contains(artifact.modelID) { catalogIDs.append(artifact.modelID) } + for catalogID in catalogIDs { + var refusals: [String] = [], chosen: Model?, describedAsAnother = false + for (files, artifact) in ofArtifact where artifact.modelID == catalogID { + do { + let described = try installed.describe(files, publicModels: publicModels, decisions: decisions) + if described.runtimeModelID == listed.runtimeModelID { chosen = described.entry; break } + describedAsAnother = true + refusals.append("\(files.manifest.path) is \(described.runtimeModelID)") + } catch { + refusals.append("\(files.manifest.path): \(error)") + } + } + let reasons = "\(catalogID) (\(listed.runtimeModelID), \(listed.artifactSHA256)): " + refusals.joined(separator: "; ") + if let chosen { entries.append(chosen) } + else if describedAsAnother { leftOut.append("left out, the catalog model ID of another registered model: " + reasons) } + else { failures.append(reasons) } + } + } + guard failures.isEmpty else { + throw ClusterConfigurationError.invalid("Qualified cluster models the release cannot describe: " + failures.joined(separator: " | ")) + } + guard !entries.isEmpty else { + throw ClusterConfigurationError.invalid("No candidate folder holds a model this build qualifies on a cluster" + + leftOut.map { "; \($0)" }.joined()) + } + leftOut.forEach(note) + return try installed.facts(entries) + } + + /// The candidate folders of a release: every subfolder of `directory`, in + /// name order, each with its `config.json`, `manifest.json` and the + /// catalog entry it came from (`catalog.json`). + public static func candidates(in directory: URL) throws -> [ModelFiles] { + let names: [String] + do { names = try FileManager.default.contentsOfDirectory(atPath: directory.path) } + catch { throw ClusterConfigurationError.invalid("Cannot list the candidate folder \(directory.path)") } + return names.filter { !$0.hasPrefix(".") }.sorted().map { + let folder = directory.appendingPathComponent($0, isDirectory: true) + return ModelFiles(configuration: folder.appendingPathComponent("config.json"), + manifest: folder.appendingPathComponent("manifest.json"), + catalog: folder.appendingPathComponent("catalog.json")) + } + } +} diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift index 10f04d9230..dc8dcd80d5 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift @@ -2,24 +2,34 @@ import Darwin import Foundation import DarkbloomClusterProtocol -/// The cluster runtime facts of one installed app (`darkbloom_cluster_runtime_v1`): -/// the digests of the cluster helpers it ships and, for each model, the -/// digests of the capability its own worker describes. The coordinator operator -/// copies them into a cluster approval (`darkbloom cluster runtime-facts`); the -/// guided setup takes the served approval whose digests equal this Mac's facts -/// (`ClusterApprovalLifetime.select`), and each member checks it against its own -/// installed files with the same computation. Every digest is computed by the code the -/// member's checks use (`DistributedInstalledFiles.digest`, the worker's -/// `--describe-runtime`, `DistributedInstalledNativeStart.resourcePolicySHA256`). +/// The cluster runtime facts of one app (`darkbloom_cluster_runtime_v2`): the +/// digests of the cluster helpers it ships and, for each model, the digests of +/// the capability its own worker describes, its pair-serving grant and the +/// parity qualifications of a model the owner declared public +/// (`ClusterPublicModels`). A signed release registers them as `cluster_runtime` +/// (the release lane computes them from its final signed app, `release`); a +/// coordinator derives that build's cluster approvals, their grants and their +/// parity qualifications from them. The guided setup takes +/// the served approval whose digests equal this Mac's facts +/// (`ClusterApprovalLifetime.select`), and each member checks it against its +/// own installed files with the same computation. Every digest is computed by +/// the code the member's checks use (`DistributedInstalledFiles.digest`, the +/// worker's `--describe-runtime`, `DistributedInstalledNativeStart.resourcePolicySHA256`). /// The facts approve nothing by themselves. public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { - public static let schema = "darkbloom_cluster_runtime_v1" - /// Each model gives two approvals (schedules 1 and 2): 64 at most, the - /// coordinator's cluster catalog bound for one file. - public static let maximumModels = 32 + public static let schema = "darkbloom_cluster_runtime_v2" + public static let maximumModels = 64 public static let maximumModelBytes = 128 + /// The canonical form is far smaller; anything larger is refused unread. + public static let maximumEncodedBytes = 64 * 1024 + /// The longest ID a coordinator derives from the facts of a release and + /// registers (`derivedIDs`). + public static let maximumDerivedIDBytes = 128 + /// The members a derived approval admits, so the ranks of a qualification. + static let derivedApprovalMembers = 2 - /// One model: what a member's saved setup pins for it. + /// One model: what a member's saved setup pins for it, its grant and its + /// public qualifications. public struct Model: Codable, Equatable, Sendable { /// The catalog model ID the installed manifest names (`model_id`). public let model: String @@ -31,19 +41,145 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { public let profileSHA256: String /// `DistributedInstalledNativeStart.resourcePolicySHA256` of the capability. public let resourcePolicySHA256: String + /// The families a coordinator lets a pair of this build serve the + /// model in: the declared families of a declared model, else the grant + /// of this build's records for the artifact; nil, written as `null`, + /// when they grant none. + public let pairServingGrant: PairServingGrant? + /// One per declared family and schedule of a declared model + /// (`parityQualifications`); empty for every other model. + public let parityQualifications: [ParityQualification] - public init(model: String, artifactSHA256: String, capabilitySHA256: String, - profileSHA256: String, resourcePolicySHA256: String) { + public init(model: String, artifactSHA256: String, capabilitySHA256: String, profileSHA256: String, + resourcePolicySHA256: String, pairServingGrant: PairServingGrant? = nil, + parityQualifications: [ParityQualification] = []) { self.model = model; self.artifactSHA256 = artifactSHA256; self.capabilitySHA256 = capabilitySHA256 self.profileSHA256 = profileSHA256; self.resourcePolicySHA256 = resourcePolicySHA256 + self.pairServingGrant = pairServingGrant; self.parityQualifications = parityQualifications } - enum CodingKeys: String, CodingKey { + enum CodingKeys: String, CodingKey, CaseIterable { case model case artifactSHA256 = "artifact_sha256" case capabilitySHA256 = "capability_sha256" case profileSHA256 = "profile_sha256" case resourcePolicySHA256 = "resource_policy_sha256" + case pairServingGrant = "pair_serving_grant" + case parityQualifications = "parity_qualifications" + } + static let fields = Set(CodingKeys.allCases.map(\.rawValue)) + + /// Every member is written: a model without a grant has `"pair_serving_grant":null`. + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(model, forKey: .model) + try container.encode(artifactSHA256, forKey: .artifactSHA256) + try container.encode(capabilitySHA256, forKey: .capabilitySHA256) + try container.encode(profileSHA256, forKey: .profileSHA256) + try container.encode(resourcePolicySHA256, forKey: .resourcePolicySHA256) + if let pairServingGrant { try container.encode(pairServingGrant, forKey: .pairServingGrant) } + else { try container.encodeNil(forKey: .pairServingGrant) } + try container.encode(parityQualifications, forKey: .parityQualifications) + } + } + + /// A model's pair-serving grant as a release names it: the mode families + /// sorted by byte and the SHA-256 of the evidence they rest on. Without a + /// grant a coordinator holds each member to the model's single-Mac + /// requirements, which a member, reporting only hardware capabilities, + /// does not meet for GLM-5.3-Flash or Qwen3.8-27B. + public struct PairServingGrant: Codable, Equatable, Sendable { + public let evidenceSHA256: String + /// `ClusterPairServingModeFamily` raw values, sorted by byte, unique. + public let modeFamilies: [String] + + /// As written; `validate` holds the families to the rules. + public init(evidenceSHA256: String, modeFamilies: [String]) { + self.evidenceSHA256 = evidenceSHA256; self.modeFamilies = modeFamilies + } + + /// `families`, sorted by byte and unique. + public init(evidenceSHA256: String, families: [ClusterPairServingModeFamily]) { + self.init(evidenceSHA256: evidenceSHA256, + modeFamilies: Set(families.map(\.rawValue)).sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) }) + } + + /// The grant `grant` gives: its families and the digest of the records + /// it rests on (`ClusterPairServingGrant.evidenceSHA256`). + public init(_ grant: ClusterPairServingGrant) throws { + self.init(evidenceSHA256: try grant.evidenceSHA256(), families: grant.families) + } + + enum CodingKeys: String, CodingKey, CaseIterable { + case evidenceSHA256 = "evidence_sha256" + case modeFamilies = "mode_families" + } + static let fields = Set(CodingKeys.allCases.map(\.rawValue)) + } + + /// The statement that one placement of a declared model serves public + /// traffic (contract D): a coordinator makes it the parity qualification + /// of the model's derived approval of `schedule`. Its equal shares are + /// written as `"tensor_parallel_shares":null`. + public struct ParityQualification: Codable, Equatable, Sendable { + public let schedule: UInt8 + /// Each rank's numerics class, in rank order. + public let numericsClasses: [String] + public let cuts: [Int] + public let mode: ClusterGenerationMode + public let promotable: Bool + public let diverged: Bool + public let evidenceSHA256: String + public let qualifiedAt: String + public let requestEnvelope: ClusterRequestEnvelope + + public init(schedule: UInt8, numericsClasses: [String], cuts: [Int], mode: ClusterGenerationMode, promotable: Bool, + diverged: Bool, evidenceSHA256: String, qualifiedAt: String, requestEnvelope: ClusterRequestEnvelope) { + self.schedule = schedule; self.numericsClasses = numericsClasses; self.cuts = cuts; self.mode = mode + self.promotable = promotable; self.diverged = diverged; self.evidenceSHA256 = evidenceSHA256 + self.qualifiedAt = qualifiedAt; self.requestEnvelope = requestEnvelope + } + + enum CodingKeys: String, CodingKey, CaseIterable { + case schedule, cuts, mode, promotable, diverged + case numericsClasses = "numerics_classes" + case tensorParallelShares = "tensor_parallel_shares" + case evidenceSHA256 = "evidence_sha256" + case qualifiedAt = "qualified_at" + case requestEnvelope = "request_envelope" + } + static let fields = Set(CodingKeys.allCases.map(\.rawValue)) + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + // Equal shares only: anything but null is refused. + guard try container.decodeNil(forKey: .tensorParallelShares) else { + throw DecodingError.dataCorruptedError(forKey: .tensorParallelShares, in: container, + debugDescription: "tensor_parallel_shares must be null (equal shares)") + } + self.init(schedule: try container.decode(UInt8.self, forKey: .schedule), + numericsClasses: try container.decode([String].self, forKey: .numericsClasses), + cuts: try container.decode([Int].self, forKey: .cuts), + mode: try container.decode(ClusterGenerationMode.self, forKey: .mode), + promotable: try container.decode(Bool.self, forKey: .promotable), + diverged: try container.decode(Bool.self, forKey: .diverged), + evidenceSHA256: try container.decode(String.self, forKey: .evidenceSHA256), + qualifiedAt: try container.decode(String.self, forKey: .qualifiedAt), + requestEnvelope: try container.decode(ClusterRequestEnvelope.self, forKey: .requestEnvelope)) + } + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(schedule, forKey: .schedule) + try container.encode(numericsClasses, forKey: .numericsClasses) + try container.encode(cuts, forKey: .cuts) + try container.encode(mode, forKey: .mode) + try container.encodeNil(forKey: .tensorParallelShares) + try container.encode(promotable, forKey: .promotable) + try container.encode(diverged, forKey: .diverged) + try container.encode(evidenceSHA256, forKey: .evidenceSHA256) + try container.encode(qualifiedAt, forKey: .qualifiedAt) + try container.encode(requestEnvelope, forKey: .requestEnvelope) } } @@ -95,8 +231,15 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { public struct ModelFiles: Equatable, Sendable { public let configuration: URL public let manifest: URL + /// The model's catalog entry as the release lane fetched it + /// (`catalog.json`: its `id` and `input_modalities`). Nil for a model + /// given by hand or installed, whose declared request envelope then + /// admits text only. + public let catalog: URL? - public init(configuration: URL, manifest: URL) { self.configuration = configuration; self.manifest = manifest } + public init(configuration: URL, manifest: URL, catalog: URL? = nil) { + self.configuration = configuration; self.manifest = manifest; self.catalog = catalog + } /// `config.json` and `manifest.json` of a model folder. public init(directory: URL) { @@ -105,19 +248,32 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { } } - /// The facts of `installation` for exactly `models`. - public static func compute(installation: Installation, models: [ModelFiles]) throws -> Self { + /// One model as this build's worker describes it. + struct Described: Equatable, Sendable { + let entry: Model + let runtimeModelID: String + } + + /// The facts of `installation` for exactly `models`: a model `publicModels` + /// declare (this build's declaration by default) has the declared grant and + /// parity qualifications, any other the grant of `decisions` (this build's + /// bundled records by default). + public static func compute(installation: Installation, models: [ModelFiles], + publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, + decisions: ClusterPairServingDecisions = ClusterPairServingGrants.decisions) throws -> Self { let installed = try HashedInstallation(installation) - return try installed.facts(models.map { try installed.describe($0) }) + return try installed.facts(models.map { try installed.describe($0, publicModels: publicModels, decisions: decisions).entry }) } /// One model's entry, described by `worker` pinned to `workerSHA256`. - static func describe(_ files: ModelFiles, worker: URL, workerSHA256: String, deadline: UInt64) throws -> Model { + static func describe(_ files: ModelFiles, worker: URL, workerSHA256: String, metallibSHA256: String, deadline: UInt64, + publicModels: [ClusterPublicModel], decisions: ClusterPairServingDecisions) throws -> Described { let configuration = try canonical(files.configuration), manifest = try canonical(files.manifest) let artifact = try catalogArtifact(ModelFiles(configuration: configuration, manifest: manifest)) guard modelIDIsValid(artifact.modelID) else { throw ClusterConfigurationError.invalid("The manifest's model ID is not 1 to \(maximumModelBytes) printable ASCII bytes") } + let inputModalities = try files.catalog.map { try catalogInputModalities($0, model: artifact.modelID) } ?? [] let bytes = try DistributedCapabilityProbe.run(executable: try canonical(worker), arguments: ["--describe-runtime", "--config", configuration.path, "--manifest", manifest.path, "--expected-executable-sha256", workerSHA256], deadline: deadline) @@ -126,14 +282,111 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { !capability.hasPrivateImages else { throw ClusterConfigurationError.invalid("The worker described another build, artifact or profile than \(manifest.path) names") } - return Model(model: artifact.modelID, artifactSHA256: capability.artifactSHA256, + let declared = declaration(model: artifact.modelID, runtimeModelID: capability.runtimeModelID, + artifactSHA256: capability.artifactSHA256, publicModels: publicModels) + let grant: PairServingGrant? + if let declared { + grant = PairServingGrant(evidenceSHA256: ClusterPublicModels.evidenceSHA256, families: declared.families) + } else { + // The public grant a member of this build reports for the installed artifact (`ClusterPairOwnerServing.publicGrant`). + grant = try (try? ClusterPairServingGrants.grant(runtimeModelID: capability.runtimeModelID, publicModelID: artifact.modelID, + artifactSHA256: capability.artifactSHA256, decisions: decisions)).map(PairServingGrant.init) + } + return Described(entry: Model(model: artifact.modelID, artifactSHA256: capability.artifactSHA256, capabilitySHA256: ClusterConfigurationCodec.sha256(bytes), profileSHA256: capability.profileFingerprint, - resourcePolicySHA256: NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability))) + resourcePolicySHA256: NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability)), + pairServingGrant: grant, + parityQualifications: declared.map { parityQualifications($0, metallibSHA256: metallibSHA256, inputModalities: inputModalities, + layers: layerCount(configuration), + servesMedia: { ClusterModelFeaturePolicy.mediaContract(capability: capability, mode: $0) != nil }) } ?? []), + runtimeModelID: capability.runtimeModelID) + } + + /// The declaration of a described model: `publicModels`' entry for its + /// runtime model, catalog ID and artifact; nil for any other model. + static func declaration(model: String, runtimeModelID: String, artifactSHA256: String, + publicModels: [ClusterPublicModel]) -> ClusterPublicModel? { + publicModels.first { + $0.runtimeModelID == runtimeModelID && $0.catalogModelID == model && $0.artifactSHA256 == artifactSHA256 + } + } + + /// The parity qualifications of a declared model: one per declared family + /// (byte order: `pipeline`, then `tensor_parallel`) and schedule + /// (ascending), so each approval's first is the pipeline and its second + /// tensor parallel. Each is placed as `ClusterPublicModels.placement` says + /// (a pipeline needs the model's `layers`: without them its records are + /// left out), its ranks in this build's numerics class, its envelope + /// admitting media only when its mode `servesMedia` for this model + /// (`ClusterModelFeaturePolicy.mediaContract`). + static func parityQualifications(_ declared: ClusterPublicModel, metallibSHA256: String, inputModalities: [String], + layers: Int?, servesMedia: (ClusterGenerationMode) -> Bool) -> [ParityQualification] { + let classes = numericsClasses(declared.ranks, metallibSHA256: metallibSHA256) + return declared.families.sorted { $0.rawValue.utf8.lexicographicallyPrecedes($1.rawValue.utf8) }.flatMap { family in + guard let placement = ClusterPublicModels.placement(of: family, layers: layers, ranks: declared.ranks.count) else { + return [ParityQualification]() + } + let envelope = ClusterPublicModels.requestEnvelope(inputModalities: inputModalities, servesMedia: servesMedia(placement.mode)) + return declared.schedules.sorted().map { schedule in + ParityQualification(schedule: schedule, numericsClasses: classes, cuts: placement.cuts, mode: placement.mode, + promotable: true, diverged: false, evidenceSHA256: ClusterPublicModels.evidenceSHA256, + qualifiedAt: ClusterPublicModels.qualifiedAt, requestEnvelope: envelope) + } + } + } + + /// The families a declared model of these facts carries no parity + /// qualification for (a pipeline whose config gives no layer count); none + /// for an undeclared model. A declared model is found by its catalog ID and + /// artifact, which the facts name. + static func familiesWithoutQualification(_ model: Model, publicModels: [ClusterPublicModel]) -> [ClusterPairServingModeFamily] { + guard let declared = publicModels.first(where: { $0.catalogModelID == model.model && $0.artifactSHA256 == model.artifactSHA256 }) + else { return [] } + let qualified = Set(model.parityQualifications.map(\.mode.servingFamily)) + return declared.families.filter { !qualified.contains($0) } + } + + /// One line for each declared family a model of these facts carries no + /// parity qualification for: the command prints them, so a release that + /// leaves one out says so. + public func unqualifiedDeclaredFamilies(publicModels: [ClusterPublicModel] = ClusterPublicModels.declared) -> [String] { + models.flatMap { model in + Self.familiesWithoutQualification(model, publicModels: publicModels).map { + "\(model.model) carries no parity qualification for its declared \($0.rawValue) family " + + "(a pipeline needs num_hidden_layers in config.json)" + } + } + } + + /// Each rank's numerics class on a build whose Metal library is + /// `metallibSHA256`: what the members register (`ClusterMemberDeviceProfile.numericsClass`). + static func numericsClasses(_ ranks: ClusterPublicModel.Ranks, metallibSHA256: String) -> [String] { + let os = OperatingSystemVersion(majorVersion: ranks.macOSMajor, minorVersion: ranks.macOSMinor, patchVersion: 0) + return Array(repeating: ClusterMemberDeviceProfile.numericsClass(architecture: ranks.gpuArchitecture, + metallibSHA256: metallibSHA256, os: os), count: ranks.count) + } + + /// The model's layer count from its config.json: `num_hidden_layers`, at + /// the top level or in `text_config` (where a model with images keeps its + /// language model's); nil when neither names a positive count. + static func layerCount(_ configuration: URL) -> Int? { + guard let handle = try? FileHandle(forReadingFrom: configuration) else { return nil } + defer { try? handle.close() } + guard let data = try? handle.read(upToCount: ClusterConfigurationFiles.maximumModelConfigurationBytes + 1), + data.count <= ClusterConfigurationFiles.maximumModelConfigurationBytes, + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } + for source in [object, object["text_config"] as? [String: Any]] { + if let number = source?["num_hidden_layers"] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), + let layers = Int(exactly: number.doubleValue), layers > 0 { + return layers + } + } + return nil } // MARK: - Canonical form - private struct Document: Encodable { + private struct Document: Codable { let schema: String let nativeRuntimeSHA256: String let metallibSHA256: String @@ -141,13 +394,14 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { let placementPolicySHA256: String let models: [Model] - enum CodingKeys: String, CodingKey { + enum CodingKeys: String, CodingKey, CaseIterable { case schema, models case nativeRuntimeSHA256 = "native_runtime_sha256" case metallibSHA256 = "metallib_sha256" case resourceLibrarySHA256 = "resource_library_sha256" case placementPolicySHA256 = "placement_policy_sha256" } + static let fields = Set(CodingKeys.allCases.map(\.rawValue)) } /// The canonical bytes: JSON with sorted keys, no whitespace, no escaped @@ -161,11 +415,70 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { placementPolicySHA256: placementPolicySHA256, models: models)) } - /// Every digest 64 lowercase hex and nonzero; 1 to 32 models with valid, - /// strictly ascending (byte order, so unique) model IDs. + /// Strict: an unknown, missing or repeated field (a model's + /// `pair_serving_grant` is written, `null` or the grant), another schema, a + /// value outside the rules or a model whose derived IDs for + /// `releaseVersion` exceed `maximumDerivedIDBytes` is refused. + public init(canonical data: Data, releaseVersion: String = ProviderCore.version) throws { + func object(_ value: Any?, fields: Set) -> [String: Any]? { + (value as? [String: Any]).flatMap { Set($0.keys) == fields ? $0 : nil } + } + guard data.count <= Self.maximumEncodedBytes, + let top = object(try? JSONSerialization.jsonObject(with: data), fields: Document.fields), + top["schema"] as? String == Self.schema, + let entries = top["models"] as? [Any], + entries.allSatisfy({ entry in + guard let model = object(entry, fields: Model.fields), + model["pair_serving_grant"] is NSNull || object(model["pair_serving_grant"], fields: PairServingGrant.fields) != nil, + let qualifications = model["parity_qualifications"] as? [Any] else { return false } + return qualifications.allSatisfy { value in + guard let qualification = object(value, fields: ParityQualification.fields) else { return false } + return qualification["tensor_parallel_shares"] is NSNull + && object(qualification["request_envelope"], fields: ClusterRequestEnvelope.fields) != nil + } + }) else { + throw ClusterConfigurationError.invalid("Cluster runtime facts have unknown or missing fields or another schema") + } + guard !Self.repeatsAKey(data) else { + throw ClusterConfigurationError.invalid("Cluster runtime facts repeat a field") + } + let document: Document + do { document = try JSONDecoder().decode(Document.self, from: data) } + catch { throw ClusterConfigurationError.invalid("Cluster runtime facts have a field of the wrong type") } + try self.init(nativeRuntimeSHA256: document.nativeRuntimeSHA256, metallibSHA256: document.metallibSHA256, + resourceLibrarySHA256: document.resourceLibrarySHA256, + placementPolicySHA256: document.placementPolicySHA256, models: document.models) + guard models.allSatisfy({ Self.derivedIDs($0, releaseVersion: releaseVersion) + .allSatisfy { $0.utf8.count <= Self.maximumDerivedIDBytes } }) else { + throw ClusterConfigurationError.invalid("An ID a coordinator derives from these facts exceeds \(Self.maximumDerivedIDBytes) bytes") + } + } + + /// The IDs a coordinator derives for `model` from the facts of release + /// `releaseVersion`: its approvals `release///s<1|2>`, + /// for a model with a grant each approval's `/grant`, and for + /// each parity qualification `/q`, n counting + /// that schedule's qualifications from 1 in block order. + static func derivedIDs(_ model: Model, releaseVersion: String) -> [String] { + func approval(_ schedule: UInt8) -> String { "release/\(releaseVersion)/\(model.model)/s\(schedule)" } + let approvals = [approval(1), approval(2)] + var counts: [UInt8: Int] = [:] + return approvals + (model.pairServingGrant == nil ? [] : approvals.map { $0 + "/grant" }) + + model.parityQualifications.map { qualification in + counts[qualification.schedule, default: 0] += 1 + return approval(qualification.schedule) + "/q\(counts[qualification.schedule]!)" + } + } + + /// Every digest 64 lowercase hex and nonzero; 1 to 64 models with valid, + /// strictly ascending (byte order, so unique) model IDs; each grant with 1 + /// to 4 known mode families in byte order; every parity qualification as + /// a coordinator validates one. func validate() throws { let digests = [nativeRuntimeSHA256, metallibSHA256, resourceLibrarySHA256, placementPolicySHA256] + models.flatMap { [$0.artifactSHA256, $0.capabilitySHA256, $0.profileSHA256, $0.resourcePolicySHA256] } + + models.compactMap(\.pairServingGrant?.evidenceSHA256) + + models.flatMap { $0.parityQualifications.map(\.evidenceSHA256) } guard digests.allSatisfy({ ClusterConfigurationSyntax.hash($0) && $0 != String(repeating: "0", count: 64) }) else { throw ClusterConfigurationError.invalid("Cluster runtime facts digests must be 64 lowercase hex characters, not zero") } @@ -175,6 +488,48 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { guard zip(models, models.dropFirst()).allSatisfy({ Self.inByteOrder($0, $1) }) else { throw ClusterConfigurationError.invalid("Cluster runtime facts models must be sorted by model ID and unique") } + let known = Set(ClusterPairServingModeFamily.allCases.map(\.rawValue)) + guard models.compactMap(\.pairServingGrant).allSatisfy({ grant in + !grant.modeFamilies.isEmpty && grant.modeFamilies.allSatisfy(known.contains) + && zip(grant.modeFamilies, grant.modeFamilies.dropFirst()).allSatisfy { $0.utf8.lexicographicallyPrecedes($1.utf8) } + }) else { + throw ClusterConfigurationError.invalid("A pair-serving grant names 1 to \(known.count) known mode families, sorted by byte and unique") + } + for model in models { + try Self.validate(model.parityQualifications, of: model.model) + } + } + + /// A model's parity qualifications as a coordinator validates them for its + /// derived approvals (two members each): schedule 1 or 2, one numerics + /// class per member, the cuts the mode has, never diverged and promotable, + /// an RFC 3339 `qualified_at`, an envelope of 1 to `ClusterPublicModels.maximumTokens` + /// tokens with video only with vision, and no placement twice. + static func validate(_ qualifications: [ParityQualification], of model: String) throws { + let refuse = { (rule: String) in ClusterConfigurationError.invalid("A parity qualification of \(model) \(rule)") } + guard qualifications.count <= 2 * ClusterPairServingModeFamily.allCases.count else { throw refuse("is one too many") } + for (index, q) in qualifications.enumerated() { + guard [1, 2].contains(q.schedule) else { throw refuse("names schedule \(q.schedule), not 1 or 2") } + guard q.numericsClasses.count == derivedApprovalMembers, q.numericsClasses.allSatisfy({ + (1...64).contains($0.utf8.count) && $0.utf8.allSatisfy { (0x21...0x7E).contains($0) } + }) else { throw refuse("needs one numerics class of 1 to 64 printable ASCII bytes per member") } + guard q.cuts.count == q.mode.layerCutCount(ranks: q.numericsClasses.count), q.cuts.allSatisfy({ $0 > 0 }), + zip(q.cuts, q.cuts.dropFirst()).allSatisfy({ $0 < $1 }) else { + throw refuse("needs the cuts its mode has, positive and ascending") + } + guard !(q.diverged && q.promotable) else { throw refuse("is diverged and promotable") } + guard ClusterPairApproval.unixNanoseconds(rfc3339: q.qualifiedAt) != nil else { + throw refuse("has a qualified_at that is not an RFC 3339 instant") + } + let envelope = q.requestEnvelope, bounds = 1...ClusterPublicModels.maximumTokens + guard bounds.contains(envelope.maxPromptTokens), bounds.contains(envelope.maxOutputTokens), + !envelope.video || envelope.vision else { + throw refuse("needs token bounds of 1 to \(ClusterPublicModels.maximumTokens) and vision for video") + } + guard !qualifications[.. [String] { + let refused = ClusterConfigurationError.invalid("The catalog entry \(url.path) is not the entry of \(model) with its input modalities") + let data: Data + do { + let handle = try FileHandle(forReadingFrom: try canonical(url)) + defer { try? handle.close() } + data = try handle.read(upToCount: 4097) ?? Data() + } catch { throw refused } + guard data.count <= 4096, let entry = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + Set(entry.keys) == ["id", "input_modalities"], entry["id"] as? String == model, + let modalities = entry["input_modalities"] as? [String], modalities.count <= 16, + modalities.allSatisfy({ (1...32).contains($0.utf8.count) && $0.utf8.allSatisfy { (0x21...0x7E).contains($0) } }) + else { throw refused } + return modalities + } + + /// True when an object in `data` (already parsed as JSON) names one key + /// twice. Keys compare after unescaping, as a JSON reader sees them. + private static func repeatsAKey(_ data: Data) -> Bool { + let bytes = [UInt8](data) + var open: [(isObject: Bool, keys: Set)] = [], expectingKey = false, index = 0 + while index < bytes.count { + switch bytes[index] { + case UInt8(ascii: "{"): open.append((true, [])); expectingKey = true + case UInt8(ascii: "["): open.append((false, [])); expectingKey = false + case UInt8(ascii: "}"), UInt8(ascii: "]"): _ = open.popLast(); expectingKey = false + case UInt8(ascii: ","): expectingKey = open.last?.isObject == true + case UInt8(ascii: "\""): + let start = index + index += 1 + while index < bytes.count, bytes[index] != UInt8(ascii: "\"") { + index += bytes[index] == UInt8(ascii: "\\") ? 2 : 1 + } + guard expectingKey, !open.isEmpty else { break } + expectingKey = false + guard index < bytes.count, + let key = try? JSONSerialization.jsonObject(with: Data(bytes[start...index]), options: .fragmentsAllowed) as? String, + open[open.count - 1].keys.insert(key).inserted else { return true } + default: break + } + index += 1 + } + return false + } + /// An installation's four helpers, each resolved to its real path and /// then hashed under the installed-file rules, and the worker that /// describes models pinned to the digest just computed. - private struct HashedInstallation { + struct HashedInstallation { let worker: URL let nativeRuntimeSHA256, metallibSHA256, resourceLibrarySHA256, placementPolicySHA256: String @@ -216,9 +618,10 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { resourceLibrarySHA256 = digests[2]; placementPolicySHA256 = digests[3] } - func describe(_ files: ModelFiles) throws -> Model { + func describe(_ files: ModelFiles, publicModels: [ClusterPublicModel], decisions: ClusterPairServingDecisions) throws -> Described { try ClusterRuntimeApprovalFacts.describe(files, worker: worker, workerSHA256: nativeRuntimeSHA256, - deadline: ClusterRuntimeApprovalFacts.deadline(seconds: 30)) + metallibSHA256: metallibSHA256, deadline: ClusterRuntimeApprovalFacts.deadline(seconds: 30), + publicModels: publicModels, decisions: decisions) } /// The facts of this installation for `models`, in byte order. @@ -237,7 +640,7 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { /// The catalog identity a model folder's manifest names, bounded and /// checked (`ClusterCatalogArtifact.parse`: the aggregate is bound to the /// files' digests). - private static func catalogArtifact(_ files: ModelFiles) throws -> ClusterCatalogArtifact { + static func catalogArtifact(_ files: ModelFiles) throws -> ClusterCatalogArtifact { let data: Data do { let handle = try FileHandle(forReadingFrom: files.manifest) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift index b4fade5d30..be47f2ab48 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardLiveOperations.swift @@ -42,6 +42,9 @@ extension ClusterSetupOperations { /// An explicit test/qualification override. Normal setup discovers the /// catalog model's embedded assistant and pins the native quote. public var tensorAssistants: [String: ClusterQwenTensorAssistantPolicy] = [:] + /// How this run of `darkbloom cluster` was asked to serve (`darkbloom cluster local`); nil keeps the scope + /// the setup record saved. The onboarding plans for it (`OnboardingLive.planningScope`). + public var servingScope: ClusterServingScope? = nil public var privateImageQualification: Bool { privateMiMoImageQualification || privateGLMImageQualification } public init(providerConfiguration: URL, darkbloomExecutable: URL, sessionArguments: [String], @@ -517,8 +520,10 @@ final class LiveContext: @unchecked Sendable { // MARK: - Planning /// `keeping`: the mode each model id keeps when it is planned again after a Darkbloom update (the service's - /// re-plan), as `ClusterSetupPlanning.decide` takes it; empty for every other plan. - func plan(peer: ClusterSetupReport, keeping: [String: ClusterGenerationMode] = [:]) -> ClusterSetupPlansResult { + /// re-plan), as `ClusterSetupPlanning.decide` takes it; empty for every other plan. `coordinator`: the setup will + /// serve through the coordinator (the onboarding's public scope); the six-step wizard's local sessions leave it off. + func plan(peer: ClusterSetupReport, keeping: [String: ClusterGenerationMode] = [:], + coordinator: Bool = false) -> ClusterSetupPlansResult { let input = pairInput() guard let description = input.description, let memberID = input.pair?.memberID, let local = description.members.first(where: { $0.id == memberID }) else { @@ -555,6 +560,9 @@ final class LiveContext: @unchecked Sendable { let mtpMode: MTPMode do { mtpMode = try ConfigManager.loadOrDefaults(from: settings.providerConfiguration).backend.mtpMode } catch { return .failed("The provider configuration could not be read: \(clean(ClusterConsoleText.bounded(error)))") } + // A setup that serves through the coordinator carries no speculative assistant: under `auto` its plan quotes + // the ordinary target only. + let discovery = ClusterPlacementTensorAssistantSelection.discoveryMode(mtpMode, coordinator: coordinator) let readings = models.filter { settings.privateGLMImageQualification ? ClusterGLMOnboardingSelection.accepts($0) : ClusterMiMoOnboardingSelection.accepts($0, qualifying: settings.privateMiMoImageQualification) @@ -607,14 +615,14 @@ final class LiveContext: @unchecked Sendable { } else { let discovered = try ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: mtpMode, chunkTokens: chunk, deadline: deadline()) + mode: discovery, chunkTokens: chunk, deadline: deadline()) assistantQuote = discovered.map { .success($0) } // Capacity changes keep the shares, so the first widening's complete // quote steers the initial split; without it the choice is speed-only. if discovered != nil { discoveredWidening = try? ClusterPlacementTensorAssistantSelection.readAutomatic(tool: tool, modelDirectory: directory, publicModelID: model.modelID, capability: admitted, - mode: mtpMode, chunkTokens: chunk, deadline: deadline(), lanes: 2) + mode: discovery, chunkTokens: chunk, deadline: deadline(), lanes: 2) } // Only a discovered assistant may give way to the ordinary target (`assistantOrTarget`). if discovered?.assistant != nil { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift index 5b283848fe..111da1b1df 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardPlanning.swift @@ -180,7 +180,8 @@ enum ClusterSetupPlanning { var plan = summary(decided.result, chosen: chosen, lines: decided.lines, localMemberID: localMemberID, profiles: [localMemberID: localProfile, peerID: peerProfile]) plan.publicTraffic = ClusterPairServingGrants.publicTrafficLine(runtimeModelID: capability.record.runtimeModelID, - artifactSHA256: capability.record.artifactSHA256, mode: chosen.mode) + artifactSHA256: capability.record.artifactSHA256, mode: chosen.mode, + tensorAssistant: assistantQuote?.assistant != nil && chosen.mode == .tensorParallel) return .init(option: .init(model: reading.model, onOtherMac: onOther, blocker: nil, plan: plan), setup: decided.setup, capability: (capability.data, capability.sha256)) } catch is ClusterPairServingRefusal { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index 161f42053d..6314ae9957 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -97,16 +97,21 @@ public struct ClusterSetupRecord: Codable, Sendable, Equatable { public var approvalSetAside: ApprovalSetAside? = nil /// The cluster approval both Macs saved their setups without, and why (`ClusterApprovalCheck`): the leader checks - /// the coordinator every minute while it is set, and does not take an approval its parts kept failing with again. + /// the coordinator every minute while it is set, and does not take an approval its parts kept failing with again + /// for `ClusterApprovalFallback.failingSeconds`. public struct ApprovalSetAside: Codable, Sendable, Equatable { public var approval: ClusterRuntimeApproval public var reason: ClusterApprovalFallback /// The setup's worker digest (`capability.runtimeBinarySHA256`) when the approval was set aside: an approval /// its parts kept failing with is not taken again by the same build, but a model approval, which names no - /// build, is taken again after an update. Nil in a record from an older build: its `id` alone is not taken. + /// build, is taken again after an update. Nil in a record from an older build, which names no `setAt` either. public var runtimeBinarySHA256: String? - public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback, runtimeBinarySHA256: String? = nil) { - self.approval = approval; self.reason = reason; self.runtimeBinarySHA256 = runtimeBinarySHA256 + /// When the approval was set aside (wall-clock seconds since 1970): one its parts kept failing with is taken + /// again `ClusterApprovalFallback.failingSeconds` later. Nil in a record from an older build, which is past it. + public var setAt: Double? + public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback, runtimeBinarySHA256: String? = nil, + setAt: Double? = nil) { + self.approval = approval; self.reason = reason; self.runtimeBinarySHA256 = runtimeBinarySHA256; self.setAt = setAt } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift new file mode 100644 index 0000000000..bbc2914c27 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift @@ -0,0 +1,131 @@ +import Foundation +import DarkbloomClusterProtocol + +/// One model whose clusters serve public traffic (`ClusterPublicModels`): the +/// mode families and schedules the owner declared, and the ranks its evidence +/// ran on. +public struct ClusterPublicModel: Sendable, Equatable { + /// The runtime's own model identity (the worker's registered model). + public let runtimeModelID: String + /// The catalog model ID the owner declared: a release's facts carry the + /// grant and qualifications under this ID only. + public let catalogModelID: String + /// The artifact the runtime registers for the model, which the evidence ran. + public let artifactSHA256: String + /// The mode families the owner declared public, in order. + public let families: [ClusterPairServingModeFamily] + /// The prefill schedules qualified: 1 serial, 2 one-chunk lookahead. + public let schedules: [UInt8] + /// The ranks of the evidence placement. + public let ranks: Ranks + + /// The evidence placement's ranks: how many, each on one GPU architecture + /// and macOS version. + public struct Ranks: Sendable, Equatable { + public let count: Int + /// Metal's architecture name of each rank's GPU (`applegpu_g17d`: Apple M5 Ultra). + public let gpuArchitecture: String + public let macOSMajor: Int + public let macOSMinor: Int + } +} + +/// The models whose clusters serve public traffic: the owner's declaration +/// (jonathan308, 2026-10-31: "public traffic should not be manual"; "only glm +/// 5.3 flash should be serving public & qwen 3.8 27b they are both good to go +/// they should be approved for serving"), reviewed in PRs like any code. A +/// release's cluster runtime facts carry, for each of these models, a +/// pair-serving grant of the declared families and a parity qualification for +/// each declared family and schedule (`ClusterRuntimeApprovalFacts`), from +/// which a coordinator derives the grant and the parity qualifications of +/// their approvals. Any other model's grant comes from the build's bundled +/// records, and its clusters serve their owner only. The evidence is +/// `evidenceDocument`, whose SHA-256 is `evidenceSHA256` (a test holds them +/// equal), so a released CLI names it without carrying the file. +public enum ClusterPublicModels { + public static let evidenceDocument = "docs/reports/2026-10-31-public-cluster-models.md" + public static let evidenceSHA256 = "dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d" + public static let qualifiedAt = "2026-10-31T00:00:00Z" + /// A public request's prompt and output allowance: the coordinator's + /// maximum, so only the model's own limits apply. + public static let maximumTokens = 1_048_576 + + /// Two Apple M5 Ultras (Metal `applegpu_g17d`, NAX on) on macOS 27.0. + static let twoM5Ultras = ClusterPublicModel.Ranks(count: 2, gpuArchitecture: "applegpu_g17d", macOSMajor: 27, macOSMinor: 0) + + /// Owner ruling, 2026-10-31: "It should be tensor or pipeline obviously but that shouldn't matter for the coordinator". + public static let declared: [ClusterPublicModel] = [ + .init(runtimeModelID: "registered_glm53_flash", catalogModelID: "glm-5.3-flash", + artifactSHA256: "3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac", + families: [.pipeline, .tensorParallel], schedules: [1, 2], ranks: twoM5Ultras), + .init(runtimeModelID: "registered_qwen38_27b", catalogModelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", + artifactSHA256: "bbd0e0adcfe74e095073fefd0b9e116e4311d606ad9989cf81f8175e8ac18463", + families: [.pipeline, .tensorParallel], schedules: [1, 2], ranks: twoM5Ultras), + ] + + /// The placement a declared family is qualified at, for a model of + /// `layers` layers on `ranks` ranks: tensor parallel splits every layer + /// (`tensor_parallel_v1`, no cut); a pipeline (`pipeline_v1`) cuts the + /// layers evenly (two ranks: `[layers / 2]`), so it needs the layer count. + /// Nil for a family without such a placement here, or a pipeline without + /// enough layers. + static func placement(of family: ClusterPairServingModeFamily, layers: Int?, ranks: Int) + -> (mode: ClusterGenerationMode, cuts: [Int])? { + switch family { + case .tensorParallel: return (.tensorParallel, []) + case .pipeline: + guard let layers, ranks >= 2, layers >= ranks else { return nil } + return (.pipeline, (1.. ClusterRequestEnvelope { + let vision = servesMedia && inputModalities.contains("image") + return .init(sampling: true, tools: true, vision: vision, video: vision && inputModalities.contains("video"), + maxPromptTokens: maximumTokens, maxOutputTokens: maximumTokens) + } + + /// The families `models` declare for a runtime model's artifact (the + /// installed one, mapped as grants map it; nil: the model's own); none for + /// any other model or artifact. + static func families(runtimeModelID: String, artifactSHA256: String?, + in models: [ClusterPublicModel] = declared) -> [ClusterPairServingModeFamily] { + guard let model = models.first(where: { $0.runtimeModelID == runtimeModelID }), + artifactSHA256.map({ ClusterPairServingGrants.qualifyingArtifact(for: $0, runtimeModelID: runtimeModelID) + == model.artifactSHA256 }) ?? true else { return [] } + return model.families + } +} + +/// The request shape a qualified placement serves to the public, as a parity +/// qualification bounds it: greedy decoding only unless `sampling`, no tool +/// schemas unless `tools`, text only unless `vision`, no video unless `video` +/// (which needs `vision`), and prompt and output allowances. +public struct ClusterRequestEnvelope: Codable, Equatable, Sendable { + public let sampling: Bool + public let tools: Bool + public let vision: Bool + public let video: Bool + public let maxPromptTokens: Int + public let maxOutputTokens: Int + + public init(sampling: Bool, tools: Bool, vision: Bool, video: Bool, maxPromptTokens: Int, maxOutputTokens: Int) { + self.sampling = sampling; self.tools = tools; self.vision = vision; self.video = video + self.maxPromptTokens = maxPromptTokens; self.maxOutputTokens = maxOutputTokens + } + + enum CodingKeys: String, CodingKey, CaseIterable { + case sampling, tools, vision, video + case maxPromptTokens = "max_prompt_tokens" + case maxOutputTokens = "max_output_tokens" + } + static let fields = Set(CodingKeys.allCases.map(\.rawValue)) +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift index 29ec192050..5fba413b74 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift @@ -182,16 +182,28 @@ public struct ClusterPairServingGrant: Sendable, Equatable { /// The families with a diverged record and no passing one, and why: never /// served, on any chips, until a check of the family passes. public let withheldFamilies: [ClusterPairServingModeFamily: String] + /// The records the grant rests on, in the order they were given (the + /// bundle's): the passing records it is computed from, without a pass + /// that a divergence of the same shape contradicts. + public let records: [ClusterPairQualificationRecord] public init(runtimeModelID: String, qualifications: [ClusterPairServingQualification], evidence: String, - withheldFamilies: [ClusterPairServingModeFamily: String] = [:]) { + withheldFamilies: [ClusterPairServingModeFamily: String] = [:], records: [ClusterPairQualificationRecord] = []) { self.runtimeModelID = runtimeModelID; self.qualifications = qualifications; self.evidence = evidence - self.withheldFamilies = withheldFamilies + self.withheldFamilies = withheldFamilies; self.records = records } /// The mode families a pair may serve this model in, in order. public var families: [ClusterPairServingModeFamily] { Set(qualifications.map(\.family)).sorted() } + /// SHA-256 of `records` as canonical JSON Lines: each record's + /// `encodedLine` (sorted keys, no whitespace), joined by "\n", with no + /// trailing newline. A release's cluster runtime facts name it as the + /// grant's `evidence_sha256`. + public func evidenceSHA256() throws -> String { + ClusterConfigurationCodec.sha256(Data(try records.map { try $0.encodedLine() }.joined(separator: "\n").utf8)) + } + /// The chip classes the grant's passing checks ran on, in any role: what /// the evidence says in words. Not a list of allowed chips: any detected /// Apple silicon may run any rank of a granted family. @@ -460,7 +472,8 @@ public struct ClusterPairServingDecisions: Sendable, Equatable { $0.0.mode!.servingFamily }.mapValues { Self.withholding($0) } granted.append(ClusterPairServingGrant(runtimeModelID: model, qualifications: runs, - evidence: Self.evidence(records: evidence.count, placements: runs), withheldFamilies: closed)) + evidence: Self.evidence(records: evidence.count, placements: runs), withheldFamilies: closed, + records: evidence.map(\.0))) } self.granted = granted // A model is withheld as a whole only when no family of it is granted. @@ -631,23 +644,33 @@ public enum ClusterPairServingGrants { /// The owner's own serving of a model (owner, 2026-10-14 08:45): refused /// only when no cluster stage adapter runs it; memory is the planner's and /// each Mac's load gate's. Records add the public grant, if any, and the - /// shapes the planner steers away from. + /// shapes the planner steers away from; `publicModels` the families the + /// owner declared public. public static func ownerServing(runtimeModelID: String, publicModelID: String, artifactSHA256: String? = nil, - decisions: ClusterPairServingDecisions = decisions) throws -> ClusterPairOwnerServing { + decisions: ClusterPairServingDecisions = decisions, + publicModels: [ClusterPublicModel] = ClusterPublicModels.declared) throws -> ClusterPairOwnerServing { try requireStageAdapter(runtimeModelID: runtimeModelID, publicModelID: publicModelID) return .init(runtimeModelID: runtimeModelID, publicGrant: try? grant(runtimeModelID: runtimeModelID, publicModelID: publicModelID, artifactSHA256: artifactSHA256, decisions: decisions), - records: records(runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, decisions: decisions)) + records: records(runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, decisions: decisions), + declaredFamilies: ClusterPublicModels.families(runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, + in: publicModels)) } /// The one line a plan or the onboarding shows about public traffic for a - /// model served in `mode`. + /// model served in `mode`: qualified in the families its records grant or + /// the owner declared public (`ClusterPublicModels`), unless the placement + /// decodes with Qwen's speculative assistant (`tensorAssistant`), which no + /// qualification covers. public static func publicTrafficLine(runtimeModelID: String, artifactSHA256: String? = nil, mode: ClusterGenerationMode?, - decisions: ClusterPairServingDecisions = decisions) -> String { + tensorAssistant: Bool = false, decisions: ClusterPairServingDecisions = decisions, + publicModels: [ClusterPublicModel] = ClusterPublicModels.declared) -> String { let grant = try? grant(runtimeModelID: runtimeModelID, publicModelID: runtimeModelID, artifactSHA256: artifactSHA256, decisions: decisions) - return ClusterPairOwnerServing.publicTrafficLine(grant: grant, mode: mode) + return ClusterPairOwnerServing.publicTrafficLine(grant: grant, declared: ClusterPublicModels.families( + runtimeModelID: runtimeModelID, artifactSHA256: artifactSHA256, in: publicModels), mode: mode, + tensorAssistant: tensorAssistant) } /// One rank of a placement, checked on the Mac that runs it with that @@ -762,6 +785,11 @@ public enum ClusterPairServingGrants { public struct ClusterPairOwnerServing: Sendable, Equatable { /// The one line shown for a model or placement with no public grant. public static let notYetQualified = "not yet qualified for public traffic" + /// The one line shown for a placement of a qualified model and mode that decodes with Qwen's speculative + /// assistant: the assistant serves local clusters only, so the setup is never offered to the coordinator + /// (`ClusterConfiguration.tensorAssistantServesLocally`). + public static let tensorAssistantNotOffered = "not offered for public traffic: it decodes with Qwen's speculative " + + "assistant, which serves local clusters only (with [backend] mtp_mode \"auto\", a cluster served through Darkbloom is planned without it)" public let runtimeModelID: String /// The records' public grant; nil when no passing record of the installed @@ -769,18 +797,32 @@ public struct ClusterPairOwnerServing: Sendable, Equatable { public let publicGrant: ClusterPairServingGrant? /// Every check on record, for the shapes they steer away from. public let records: ClusterPairQualificationRecords + /// The families the owner declared public for the installed artifact + /// (`ClusterPublicModels`), with or without a record of them. + public let declaredFamilies: [ClusterPairServingModeFamily] + + init(runtimeModelID: String, publicGrant: ClusterPairServingGrant?, records: ClusterPairQualificationRecords, + declaredFamilies: [ClusterPairServingModeFamily] = []) { + self.runtimeModelID = runtimeModelID; self.publicGrant = publicGrant; self.records = records + self.declaredFamilies = declaredFamilies + } /// The model's public status in one line, whatever the mode. - public var publicTrafficLine: String { Self.publicTrafficLine(grant: publicGrant, mode: nil) } + public var publicTrafficLine: String { Self.publicTrafficLine(grant: publicGrant, declared: declaredFamilies, mode: nil) } /// The public status of serving it in `mode`, in one line. - public func publicTrafficLine(mode: ClusterGenerationMode?) -> String { Self.publicTrafficLine(grant: publicGrant, mode: mode) } + public func publicTrafficLine(mode: ClusterGenerationMode?) -> String { + Self.publicTrafficLine(grant: publicGrant, declared: declaredFamilies, mode: mode) + } - static func publicTrafficLine(grant: ClusterPairServingGrant?, mode: ClusterGenerationMode?) -> String { - guard let grant, !grant.families.isEmpty, mode.map({ grant.families.contains($0.servingFamily) }) ?? true else { + static func publicTrafficLine(grant: ClusterPairServingGrant?, declared: [ClusterPairServingModeFamily], + mode: ClusterGenerationMode?, tensorAssistant: Bool = false) -> String { + let families = Set((grant?.families ?? []) + declared).sorted() + guard !families.isEmpty, mode.map({ families.contains($0.servingFamily) }) ?? true else { return notYetQualified } - let families = (mode.map { [$0.servingFamily] } ?? grant.families).map(\.description).joined(separator: " and ") - return "qualified for public traffic in \(families) mode (the coordinator's parity qualification decides each placement)" + guard !tensorAssistant else { return tensorAssistantNotOffered } + let named = (mode.map { [$0.servingFamily] } ?? families).map(\.description).joined(separator: " and ") + return "qualified for public traffic in \(named) mode (the coordinator's parity qualification decides each placement)" } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift index ae8e63ce6d..76dd399aba 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift @@ -8,8 +8,8 @@ import DarkbloomClusterSecurity /// saves the setup without one. Nothing another Mac or a file says is taken on trust: a build-pinned approval's digests /// must be this Mac's cluster runtime facts (`ClusterRuntimeApprovalFacts`, every digest of the release's block), a /// model approval's artifact must be the saved setup's (the member takes the runtime from its own setup), the roster -/// must be the one this Mac countersigned when it paired (S17), and the saved setup's own checks -/// (`ClusterNativeMemberAttachment.validate`) run as at every load. +/// must be the one this Mac countersigned when it paired (S17), and the saved setup's own checks with the approval +/// attached (`ClusterConfiguration.validate`, which runs `ClusterNativeMemberAttachment.validate`) run as at every load. enum ClusterApprovalAttachment { /// The block digests of a build-pinned `approval` that are not this Mac's facts, by their contract names; `model` /// when the facts describe no entry for the approval's model. A model approval is never compared with facts. @@ -131,9 +131,12 @@ enum ClusterApprovalAttachment { let attachment = ClusterNativeMemberAttachment(ownerSHA256: owner, metallibPath: tools.metallib.path, resourceLibraryPath: tools.resourceLibrary.path, clusterApproval: approval, roster: paired.roster, memberPins: paired.pins, edges: edge.map { [$0] }) - // The saved setup's own checks, as at every load: the approval names this setup's model, artifact and schedule - // (and a build-pinned one its runtime, capability and profile), and the roster's pins are its members in rank order. - try attachment.validate(configuration: configuration.replacingNativeMember(attachment), capability: saved.capability) + // Every check the save runs on the setup with the attachment, as at every load: the approval names this setup's + // model, artifact and schedule (and a build-pinned one its runtime, capability and profile), the roster's pins + // are its members in rank order, and nothing the setup carries is refused beside an approval (a tensor + // assistant serves local clusters only). So no part stops for an approval either Mac must refuse at the save. + try configuration.replacingNativeMember(attachment).validate(capability: saved.capability, + rawCapabilitySHA256: configuration.capabilitySHA256) return attachment } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift index c6ee9cc525..04b5e8b75b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift @@ -7,10 +7,14 @@ public enum ClusterApprovalFallback: String, Codable, Equatable, Sendable { /// The coordinator answers (404, or a list without the saved approval) and serves no other matching entry. case withdrawn /// The coordinator-paired parts ended `ClusterControlSoloAdmission.maximumQuickEnds` times in a row right after - /// starting with the approval (the rule for a solo server that keeps ending). The approval itself is not taken - /// again; a later matching one is. + /// starting with the approval (the rule for a solo server that keeps ending; `ClusterApprovalCheck.memberQuickEnds`). + /// The approval itself is taken again `failingSeconds` after it was set aside; a later matching one at once. case failing + /// How long the same build does not take an approval set aside as `failing` again. Meanwhile each Mac's part that + /// serves locally starts its count of quick ends again (`ClusterService`), so the approval comes back with none. + public static let failingSeconds: Double = 3_600 + /// The one line for the screen, the log and the status. func line(_ approval: ClusterRuntimeApproval, grace: Double) -> String { switch self { @@ -22,8 +26,8 @@ public enum ClusterApprovalFallback: String, Codable, Equatable, Sendable { + "until it lists a matching one again" case .failing: return "The coordinator-paired parts ended \(ClusterControlSoloAdmission.maximumQuickEnds) times in a row right after " - + "starting with cluster approval \(approval.id): the pair serves on the leader's local API until the " - + "coordinator lists a later one" + + "starting with cluster approval \(approval.id): the pair serves on the leader's local API for " + + "\(Int(Self.failingSeconds / 60)) minutes, then it is offered again with it, or sooner with a later one the coordinator lists" } } } @@ -121,10 +125,13 @@ enum ClusterApprovalCheck { watch.unreachableSince = nil guard answered else { return .keep } // Not offered now: the first matching entry, or one listed again for a pair that serves locally. An approval its - // parts kept failing with is not taken again by the same build (by any build for a record without one). + // parts kept failing with is not taken again by the same build (by any build for a record without one) for + // `ClusterApprovalFallback.failingSeconds` after it was set aside. A record from an older build names no time + // and is past that bound, as is one whose time lies ahead of a clock that was set back. var answer = fetched if let setAside, setAside.reason == .failing, setAside.runtimeBinarySHA256.map({ $0 == saved.capability.runtimeBinarySHA256 }) ?? true, + let setAt = setAside.setAt, (0.. Int { if lastError?.contains(unreachableMemberEnd) == true { return 0 } + if lastError?.contains(notAcceptedMemberEnd) == true, ranSeconds < ClusterControlSoloAdmission.quickEndSeconds { return count } return ClusterControlSoloAdmission.quickEnds(after: count, ranSeconds: ranSeconds) } /// How a member's error line starts when its registration wait never reached the coordinator. static let unreachableMemberEnd = String(ClusterMemberControlError.coordinatorUnreachable.rawValue.prefix(40)) + /// A member's error line when the coordinator kept its registration open past the negotiation window without an + /// acknowledgement that fits it. + static let notAcceptedMemberEnd = ClusterMemberControlError.negotiationFailed.rawValue + + /// What the leader keeps once both Macs applied `step` (`ClusterSetupRecord.approvalSetAside`): the approval a + /// fallback set aside, with the saved setup's worker digest and the wall-clock seconds it was set aside at; nil for + /// any other step. + static func setAside(by step: Step, worker: String, now: Double) -> ClusterSetupRecord.ApprovalSetAside? { + guard case .serveLocally(let approval, let reason) = step else { return nil } + return .init(approval: approval, reason: reason, runtimeBinarySHA256: worker, setAt: now) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index b38f593264..0c36b8ddce 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -269,11 +269,11 @@ final class OnboardingLive: @unchecked Sendable { case .failure(let failure): return .init(lines: failure.lines, failed: true, leaderID: leaderID) } case .planModels: - switch localPlanModels() { + switch localPlanModels(scope: request.scope) { case .success(let choices): return .init(lines: [], failed: false, leaderID: leaderID, choices: choices) case .failure(let failure): return .init(lines: failure.lines, failed: true, leaderID: leaderID) } - case .adopt: return lines(localAdopt(request.index ?? -1, model: request.model)) + case .adopt: return lines(localAdopt(request.index ?? -1, model: request.model, scope: request.scope)) case .serve: return lines(localServe()) case .stop: return lines(localStop()) case .readiness: @@ -597,14 +597,23 @@ final class OnboardingLive: @unchecked Sendable { } func planModels() -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { - let result = routed(.init(op: .planModels), seconds: 240, acting: false, local: { localPlanModels() }) { $0.choices ?? [] } + let request = ClusterControlRequest(op: .planModels, scope: context.settings.servingScope) + let result = routed(request, seconds: 240, acting: false, local: { localPlanModels() }) { $0.choices ?? [] } if case .success(let listed) = result { lock.withLock { listedChoices = listed } } return result } + /// How the cluster will serve the setup being planned: the way a forwarded command names, else the one this run + /// was asked for (`darkbloom cluster local`), else the one saved on this Mac. A cluster served through Darkbloom + /// is planned for its coordinator (`ClusterPlacementTensorAssistantSelection.discoveryMode`). + func planningScope(_ named: ClusterServingScope? = nil) -> ClusterServingScope { + named ?? context.settings.servingScope ?? leadership?.scope ?? .publicServing + } + /// `keeping`: the mode each model id keeps (`LiveContext.plan`); the service's re-plan after an update passes the - /// mode the pair served the model in. - func localPlanModels(keeping: [String: ClusterGenerationMode] = [:]) -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { + /// mode the pair served the model in. `scope`: the way of serving a forwarded command names (`planningScope`). + func localPlanModels(keeping: [String: ClusterGenerationMode] = [:], + scope: ClusterServingScope? = nil) -> Result<[ClusterOnboardingModelChoice], ClusterOnboardingFailure> { // The plan judges each Mac by the memory its report sampled. A report taken before this Mac stopped the // cluster's parts still counts the other Mac's old part (the re-plan after an update stops them first): // ask again, so both Macs are priced with that memory given back. 2026-10-22: the other Mac's report was @@ -621,7 +630,7 @@ final class OnboardingLive: @unchecked Sendable { // Folders copied over the cable (no receipt on this Mac) are repaired before the plan describes them. ClusterProductModelStore.updateClusterStore(store, providerConfiguration: settings.service.wizard.providerConfiguration, accepts: context.workerAcceptsManifest) - switch context.plan(peer: peer, keeping: keeping) { + switch context.plan(peer: peer, keeping: keeping, coordinator: !planningScope(scope).isLocalOnly) { case .failed(let reason): return .failure(.init("Planning failed: \(reason)")) case .ready(let options): let localName = ClusterPairingProvider.displayName(chipName: context.snapshot().local.mac.chip) @@ -1036,16 +1045,18 @@ final class OnboardingLive: @unchecked Sendable { let model = lock.withLock { listedChoices.indices.contains(index) ? (listedChoices[index].modelID ?? listedChoices[index].title) : nil } // The leader may stop both parts (up to 5 minutes to drain), wait for their memory (`releaseWaitSeconds`), plan // again and retry the device lease: the reply can take that long. - return routed(.init(op: .adopt, index: index, model: model), seconds: 600, acting: true, local: { localAdopt(index) }) { $0.lines } + let request = ClusterControlRequest(op: .adopt, index: index, model: model, scope: context.settings.servingScope) + return routed(request, seconds: 600, acting: true, local: { localAdopt(index) }) { $0.lines } } /// `model`: the id of the model the list showed at `index` (a choice forwarded from another Mac). When this Mac's /// list is gone (its service restarted) or no longer shows that model there, it plans again and adopts it by id. - func localAdopt(_ index: Int, model: String? = nil) -> Result<[String], ClusterOnboardingFailure> { + /// `scope`: the way of serving the forwarded choice was listed for; every plan made here follows it. + func localAdopt(_ index: Int, model: String? = nil, scope: ClusterServingScope? = nil) -> Result<[String], ClusterOnboardingFailure> { var index = index if let model, lock.withLock({ !choices.indices.contains(index) || choices[index].title != model }) { if case .failure(let failure) = localReachMembers({ _ in }) { return .failure(failure) } - if case .failure(let failure) = localPlanModels() { return .failure(failure) } + if case .failure(let failure) = localPlanModels(scope: scope) { return .failure(failure) } guard let found = lock.withLock({ choices.firstIndex { $0.title == model } }) else { return .failure(.init("\(model) is not offered on these Macs any more; run `darkbloom cluster` again to choose.")) } @@ -1070,7 +1081,7 @@ final class OnboardingLive: @unchecked Sendable { // plan stands (a failed plan replaces neither `choices` nor the decisions `context.adopt` reads): it was // priced with less memory than there is now. awaitReleased() - if case .success(let replanned) = localPlanModels() { + if case .success(let replanned) = localPlanModels(scope: scope) { // `localPlanModels` set `choices` in the order of the list it returned. Both are read under one lock, // and the entry must still name the chosen model: a plan forwarded from the other Mac may replace // `choices` meanwhile. diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index f589880104..980bc6cf43 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -77,6 +77,8 @@ public final class ClusterService: @unchecked Sendable { /// The supervision loop's period: one supervise/publish cycle per interval. private let supervisionIntervalSeconds: Double private let beforePartStart: (@Sendable () -> Void)? + /// The environment this Mac's parts start from (`partEnvironment`); nil: this process's own at each start. + private let environment: [String: String]? /// Main supervision thread only; a pending stop cannot be acknowledged by /// a cycle that read the preceding serving intent. private var supervisedStopDrainID: UUID? @@ -161,12 +163,14 @@ public final class ClusterService: @unchecked Sendable { /// Internal composition of the service's existing stores. Public callers keep /// the canonical user namespace, the normal recovery deadline and the one-second supervision interval. init(settings: Settings, paths: ClusterUserPaths, recoveryGraceSeconds: Double = 300, - supervisionIntervalSeconds: Double = 1, beforePartStart: (@Sendable () -> Void)? = nil) { + supervisionIntervalSeconds: Double = 1, beforePartStart: (@Sendable () -> Void)? = nil, + environment: [String: String]? = nil) { precondition(recoveryGraceSeconds.isFinite && recoveryGraceSeconds >= 0) precondition(supervisionIntervalSeconds.isFinite && supervisionIntervalSeconds > 0) self.recoveryGraceSeconds = recoveryGraceSeconds self.supervisionIntervalSeconds = supervisionIntervalSeconds self.beforePartStart = beforePartStart + self.environment = environment pairingStore = .default(home: paths.homeDirectory) var wizard = settings.wizard wizard.derivedPlacement = true @@ -1124,8 +1128,9 @@ public final class ClusterService: @unchecked Sendable { try? self.store.updateRecord { stored in if let note = result.note { stored.approvalNote = note } // The approval set aside is kept while the pair serves locally and dropped once one is saved again. - if case .serveLocally(let approval, let reason) = step, result.changed { - stored.approvalSetAside = .init(approval: approval, reason: reason, runtimeBinarySHA256: decided.worker) + if result.changed, let setAside = ClusterApprovalCheck.setAside(by: step, worker: decided.worker, + now: Date().timeIntervalSince1970) { + stored.approvalSetAside = setAside } if case .save = step, result.changed { stored.approvalSetAside = nil } } @@ -1293,7 +1298,8 @@ public final class ClusterService: @unchecked Sendable { nextStart = Date().addingTimeInterval(ran >= 120 ? 3 : backoff) } // A coordinator-paired part that keeps ending right after its start makes the leader serve locally - // (`ClusterApprovalCheck.step`); an end because the coordinator was out of reach is not counted. + // (`ClusterApprovalCheck.step`); an end the coordinator decided (out of reach, or the member role not + // accepted in time) is not counted. if lock.withLock({ childIsMember }) { let lastError = Self.lastError(in: serviceFiles.rankLog, from: lock.withLock { childLogOffset }) lock.withLock { memberQuickEnds = ClusterApprovalCheck.memberQuickEnds(after: memberQuickEnds, ranSeconds: ran, lastError: lastError) } @@ -1419,6 +1425,8 @@ public final class ClusterService: @unchecked Sendable { let process = Process() process.executableURL = settings.wizard.darkbloomExecutable process.arguments = arguments + process.environment = Self.partEnvironment(environment ?? ProcessInfo.processInfo.environment, + serviceDirectory: store.paths.directory) process.standardInput = FileHandle.nullDevice let log = serviceFiles.rankLog if !FileManager.default.fileExists(atPath: log.path) { FileManager.default.createFile(atPath: log.path, contents: nil, attributes: [.posixPermissions: 0o600]) } @@ -1439,6 +1447,22 @@ public final class ClusterService: @unchecked Sendable { say("started \(what) (pid \(process.processIdentifier))") } + /// The environment of this Mac's part: this service's own, except the heartbeat file. Under its supervisor the + /// service beats into the file `ClusterSupervisionFiles.healthPathEnvironmentKey` names, and a coordinator-paired + /// part (`start --cluster-member`) beats into the file the same key names, with its own pid. Inherited as is, the + /// part overwrote the service's heartbeat, and the supervisor's liveness guard reads a beat of another pid as no + /// beat: whenever the part's beats landed last at the guard's probes for its down budget, the guard restarted a + /// healthy service and the pair dropped. The part beats into a file of its own instead; it keeps the key, so it + /// still waits for its registration as a supervised member does. + static func partEnvironment(_ environment: [String: String], serviceDirectory: URL) -> [String: String] { + var environment = environment + let key = ClusterSupervisionFiles.healthPathEnvironmentKey + if let path = environment[key], !path.isEmpty { + environment[key] = ClusterServiceAgent.partHealthPath(serviceDirectory: serviceDirectory).path + } + return environment + } + /// Saves this Mac's setup without its cluster approval (it ended, or the cluster serves locally only). A save /// that cannot run yet (the device lease of the part that just ended) is tried again after the restart backoff. private func removeEndedApproval(key: String, localOnly: Bool, say: @Sendable (String) -> Void) { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift index bdf2cb521b..4464993892 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift @@ -308,9 +308,12 @@ public enum ClusterPlacementFlow { + "(\(records.restrictedFamilies.sorted().map(\.description).joined(separator: ", ")) modes): \(records.failedShapesText). " + "Those exact shapes are not planned; every other placement is, on any Macs.") } - // Public traffic in one line (owner serving never waits for it): the coordinator's parity qualification decides. + // Public traffic in one line (owner serving never waits for it): the coordinator's parity qualification decides, + // and a setup that decodes with Qwen's speculative assistant is never offered to it. + let assistant = (batchScope?.tensorParallelQuote ?? tensorAssistantQuote)?.assistant let publicLine = ClusterPairServingGrants.publicTrafficLine(runtimeModelID: capability.runtimeModelID, - artifactSHA256: capability.artifactSHA256, mode: result.chosen?.mode) + artifactSHA256: capability.artifactSHA256, mode: result.chosen?.mode, + tensorAssistant: assistant != nil && result.chosen?.mode == .tensorParallel) lines.append("Public traffic") lines.append(" " + publicLine.prefix(1).uppercased() + publicLine.dropFirst() + ".") var setup: ClusterPlacementSetup? @@ -327,8 +330,7 @@ public enum ClusterPlacementFlow { lines.append(" Request deadline " + deadline.basis + ".") } let value = try ClusterPlacementSetup.synthesize(description: described, capability: capability, - chosen: chosen, batchLanes: batchScope?.lanes, - tensorAssistant: (batchScope?.tensorParallelQuote ?? tensorAssistantQuote)?.assistant?.policy) + chosen: chosen, batchLanes: batchScope?.lanes, tensorAssistant: assistant?.policy) lines.append("What happens next") lines += value.narration(localMemberID: localMemberID).map { " " + $0 } setup = value diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift index e2a95123e5..1b2ad56cee 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementTensorAssistantSelection.swift @@ -37,6 +37,16 @@ enum ClusterPlacementTensorAssistantSelection { /// stays bound by one weight pass. static let automaticDepth = 3 + /// The `backend.mtp_mode` discovery runs under for a plan whose setup serves through the coordinator + /// (`coordinator`) or on a local cluster. The assistant's speculative decoding has no parity qualification, so a + /// setup saved for coordinator pairing carries none (`ClusterConfiguration.tensorAssistantServesLocally`): under + /// `auto` such a plan quotes the ordinary target only. `on` is the operator's explicit choice and is kept; the + /// plan then says it is not offered for public traffic, and the leader refuses the coordinator's approval before + /// any part stops. + static func discoveryMode(_ configured: MTPMode, coordinator: Bool) -> MTPMode { + coordinator && configured == .auto ? .off : configured + } + static func automaticCandidate(mode: MTPMode, runtimeModelID: String, modelDirectory: URL, publicModelID: String, artifactSHA256: String, manifestSHA256: String, diff --git a/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift b/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift index 85d29eb3a6..1223b2126c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Memory/EngineV2Reslice.swift @@ -25,10 +25,12 @@ // boxes. Invariant: Σ(grants) ≤ fleetBudget at all times. // // Serviceability floor: a load whose re-slice would leave ANY slot below -// the minimum serveable KV (`UnifiedMemoryCap.minimumLoadKVBytes`, the same -// 1 GiB figure the post-load headroom guard enforces) is REFUSED — fail -// loud (503, coordinator reroutes) rather than thrashing every co-resident -// model below serviceability. +// its floor (the 1 GiB `UnifiedMemoryCap.minimumLoadKVBytes` plus that +// slot's fixed request workspace and admission watermark) is REFUSED — +// fail loud (503, coordinator reroutes) rather than thrashing every +// co-resident model below serviceability. Given the floors, a split that +// would leave a slot below its floor is replaced by floors first and the +// remainder by weight, so only a budget smaller than Σ(floors) refuses. import Foundation @@ -68,12 +70,19 @@ extension EngineV2KVSizing { /// * Σ(shares) ≤ budget always (floor division; the ≤ slot-count /// remainder bytes are deliberately left unassigned). /// + /// `minimumGrantBytes` (the floors `resliceMeetsServiceabilityFloor` + /// checks) keeps the proportional result whenever it clears every + /// floor. Otherwise, if Σ(floors) fits the budget, each slot gets its + /// floor and the rest of the budget is split by the same weights; if it + /// does not, the proportional result stands and the floor check refuses. + /// /// Returns modelId → grant bytes. The caller enforces the /// serviceability floor (`resliceMeetsServiceabilityFloor`) on LOAD. static func resliceGrants( existing: [ResliceSlot], newcomer: ResliceSlot?, - fleetKVBudgetBytes: UInt64 + fleetKVBudgetBytes: UInt64, + minimumGrantBytes: [String: Int]? = nil ) -> [String: Int] { var all = existing if let newcomer { all.append(newcomer) } @@ -86,6 +95,31 @@ extension EngineV2KVSizing { return [all[0].modelId: Int(budget)] } + let proportional = proportionalGrants(all, budget: budget) + guard let minimumGrantBytes, + !resliceMeetsServiceabilityFloor(proportional, minimumGrantBytes: minimumGrantBytes) + else { return proportional } + + var floors: [Int] = [] + var floorTotal: UInt64 = 0 + for slot in all { + let floor = serviceabilityFloor(slot.modelId, minimumGrantBytes: minimumGrantBytes) + let (total, overflow) = floorTotal.addingReportingOverflow(UInt64(floor)) + guard floor < Int.max, !overflow, total <= budget else { return proportional } + floors.append(floor) + floorTotal = total + } + let remainder = proportionalGrants(all, budget: budget - floorTotal) + var grants: [String: Int] = [:] + for (slot, floor) in zip(all, floors) { + grants[slot.modelId] = floor + (remainder[slot.modelId] ?? 0) + } + return grants + } + + /// `budget` split across ≥ 2 slots by their weights (equal split when + /// any rate is unknown), Σ ≤ budget. + private static func proportionalGrants(_ all: [ResliceSlot], budget: UInt64) -> [String: Int] { // Per-model weights. Any unknown rate degrades the WHOLE slice to // an equal split — mixing real weights with a guessed one would // silently starve whichever side the guess was wrong about. @@ -161,8 +195,14 @@ extension EngineV2KVSizing { minimumGrantBytes: [String: Int] = [:] ) -> Bool { grants.allSatisfy { modelId, grant in - let floor = max(Int(minimumServiceableGrantBytes), minimumGrantBytes[modelId] ?? 0) + let floor = serviceabilityFloor(modelId, minimumGrantBytes: minimumGrantBytes) return floor < Int.max && grant >= floor } } + + /// One slot's floor: its total from `minimumGrantBytes`, never below + /// the base `minimumServiceableGrantBytes`. + private static func serviceabilityFloor(_ modelId: String, minimumGrantBytes: [String: Int]) -> Int { + max(Int(minimumServiceableGrantBytes), minimumGrantBytes[modelId] ?? 0) + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift index 8a600a5a9a..a98ae7f27a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ChatRequest.swift @@ -38,9 +38,12 @@ public struct ChatCompletionRequest: Codable, Sendable { /// OpenAI `top_logprobs` (0–20, meaningful when `logprobs == true`). /// v2 engine path only; ignored by legacy. public let top_logprobs: Int? - /// OpenAI-compatible `min_p`. Applied on a cluster pair only (its decoding - /// rank samples with the product's min-p); the single-Mac serving - /// translator does not expose it (`EngineV2Translation.samplingParams`). + /// OpenAI-compatible `min_p`. Applied on every slot: a single Mac's v2 + /// engine gets it from `EngineV2Bridge` after translation + /// (`EngineV2Translation.samplingParams` leaves it 0), and a cluster pair's + /// decoding rank samples with it. The samplers count a value above 1 as 1 + /// and ignore 0, negative and NaN values; MiMo native media and Nemotron + /// Super refuse a non-zero value instead. public let min_p: Float? public init( diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift index ef96bfcd0a..beed4d1a47 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+EngineV2.swift @@ -246,15 +246,21 @@ extension ProviderLoop { ) async -> Bool { let survivors = await existingSlotGrants(excludingModelId: "", excludingModelIDs: excludingModelIDs) guard !survivors.isEmpty else { return true } + let minimumGrants = Self.minimumGrantBytes(survivors) let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, fleetKVBudgetBytes: fleetKVBudgetBytes( extraWeightBytes: 0, activationReserveBytes: reserveBytes, - excludingModelIDs: excludingModelIDs)) - return EngineV2KVSizing.resliceMeetsServiceabilityFloor( - targets, minimumGrantBytes: Dictionary(uniqueKeysWithValues: - survivors.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + excludingModelIDs: excludingModelIDs), + minimumGrantBytes: minimumGrants) + return EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: minimumGrants) + } + + /// Every slot's serviceability floor by model, for `resliceGrants` and + /// `resliceMeetsServiceabilityFloor`. + private static func minimumGrantBytes(_ slots: [ExistingSlotGrant]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: slots.map { ($0.slot.modelId, $0.minimumGrantBytes) }) } /// Existing v2 slots eligible for re-slicing: live (not mid-unload) @@ -414,13 +420,13 @@ extension ProviderLoop { modelId: modelId, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength) + let minimumGrants = Self.minimumGrantBytes(existing) var fleetBudget = fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes) var targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) - let minimumGrants = Dictionary(uniqueKeysWithValues: - existing.map { ($0.slot.modelId, $0.minimumGrantBytes) }) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) // Serviceability floor (fail loud): a slice that would leave ANY // slot below the minimum serveable grant is refused outright — @@ -445,7 +451,8 @@ extension ProviderLoop { targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) } guard EngineV2KVSizing.resliceMeetsServiceabilityFloor( targets, minimumGrantBytes: minimumGrants) @@ -544,14 +551,15 @@ extension ProviderLoop { modelId: String, weightBytes: Int, fp16KVBytesPerToken: Int, maxContextLength: Int ) async throws -> NewcomerReslice { let existing = await existingSlotGrants(excludingModelId: modelId) + let minimumGrants = Self.minimumGrantBytes(existing) let fleetBudget = fleetKVBudgetBytes(extraWeightBytes: weightBytes) let targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: .init(modelId: modelId, fp16KVBytesPerToken: fp16KVBytesPerToken, maxContextLength: maxContextLength), - fleetKVBudgetBytes: fleetBudget) - guard EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: - Dictionary(uniqueKeysWithValues: existing.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) + guard EngineV2KVSizing.resliceMeetsServiceabilityFloor(targets, minimumGrantBytes: minimumGrants) else { EngineV2Factory.emitRefusalTelemetry(modelId: modelId, reason: .resliceFloor, error: nil, emitTelemetry: engineV2SlotHooks?.emitTelemetry) @@ -646,7 +654,9 @@ extension ProviderLoop { /// Regrow body — caller holds the re-slice gate. Shrink targets, if /// the budget somehow contracted, are applied first so the Σ ≤ budget /// invariant holds throughout. Used directly by `ensureModelLoaded`'s - /// post-bridge-guard failure path, which already holds the gate. + /// post-bridge-guard failure path, which already holds the gate. The + /// floors keep a slot a load funded to its floor from being shrunk + /// back below it. internal func resliceGrowSurvivorsLocked() async { guard nativeMiMoAllowsReclamation() else { return } let survivors = await existingSlotGrants(excludingModelId: "") @@ -656,7 +666,8 @@ extension ProviderLoop { let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: Self.minimumGrantBytes(survivors)) for entry in survivors { if let target = targets[entry.slot.modelId], target < entry.previousGrant { await entry.bridge.updateKVBytesCapacity(target) diff --git a/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift b/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift index b2db116688..c201bb7463 100644 --- a/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift +++ b/provider-swift/Sources/ProviderCore/Server/MiMo/StandaloneServer+NativeMiMo.swift @@ -372,7 +372,8 @@ extension StandaloneServer { let targets = EngineV2KVSizing.resliceGrants(existing: existing.map(\.slot), newcomer: .init(modelId: modelID, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength), - fleetKVBudgetBytes: fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes)) + fleetKVBudgetBytes: fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes), + minimumGrantBytes: Self.minimumGrantBytes(existing)) guard Self.resliceKeepsSlotsServiceable(targets, existing: existing) else { EngineV2Factory.emitRefusalTelemetry(modelId: modelID, reason: .resliceFloor, error: nil, emitTelemetry: v2TestHooks?.emitTelemetry) diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift index 40966cc3c6..f3eb5d087a 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift @@ -1040,7 +1040,8 @@ public actor StandaloneServer { existing: survivors.map(\.slot), newcomer: nil, fleetKVBudgetBytes: fleetKVBudgetBytes( - extraWeightBytes: 0, activationReserveBytes: reserveBytes)) + extraWeightBytes: 0, activationReserveBytes: reserveBytes), + minimumGrantBytes: Self.minimumGrantBytes(survivors)) return Self.resliceKeepsSlotsServiceable(targets, existing: survivors) } @@ -1071,8 +1072,13 @@ public actor StandaloneServer { _ targets: [String: Int], existing: [ExistingSlotGrant] ) -> Bool { EngineV2KVSizing.resliceMeetsServiceabilityFloor( - targets, minimumGrantBytes: Dictionary(uniqueKeysWithValues: - existing.map { ($0.slot.modelId, $0.minimumGrantBytes) })) + targets, minimumGrantBytes: minimumGrantBytes(existing)) + } + + /// Every slot's serviceability floor by model, for `resliceGrants` and + /// `resliceKeepsSlotsServiceable`. + nonisolated static func minimumGrantBytes(_ existing: [ExistingSlotGrant]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: existing.map { ($0.slot.modelId, $0.minimumGrantBytes) }) } private struct SlotBuild { @@ -1201,11 +1207,13 @@ public actor StandaloneServer { modelId: modelId, fp16KVBytesPerToken: sizing.fp16KVBytesPerToken, maxContextLength: sizing.maxContextLength) + let minimumGrants = Self.minimumGrantBytes(existing) var fleetBudget = fleetKVBudgetBytes(extraWeightBytes: sizing.weightsBytes) var targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) // Serviceability floor (fail loud): refuse a load that would leave // any slot below the minimum serveable live-KV grant. @@ -1225,7 +1233,8 @@ public actor StandaloneServer { targets = EngineV2KVSizing.resliceGrants( existing: existing.map(\.slot), newcomer: newcomer, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: minimumGrants) } guard Self.resliceKeepsSlotsServiceable(targets, existing: existing) else { @@ -1369,7 +1378,8 @@ public actor StandaloneServer { /// Grow the surviving slots back to their re-sliced shares after an /// eviction (a lone survivor gets the FULL fleet budget back). Called - /// from the eviction path, i.e. inside `isLoadingAny`. + /// from the eviction path, i.e. inside `isLoadingAny`. The floors keep + /// a slot a load funded to its floor from being shrunk back below it. func resliceGrowSurvivors() async { guard nativeMiMoReclaimAllowed else { return } let survivors = await existingSlotGrants(excludingModelId: "") @@ -1379,7 +1389,8 @@ public actor StandaloneServer { let targets = EngineV2KVSizing.resliceGrants( existing: survivors.map(\.slot), newcomer: nil, - fleetKVBudgetBytes: fleetBudget) + fleetKVBudgetBytes: fleetBudget, + minimumGrantBytes: Self.minimumGrantBytes(survivors)) for entry in survivors { guard nativeMiMoReclaimAllowed else { return } if let target = targets[entry.slot.modelId], target < entry.previousGrant { diff --git a/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift b/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift index f6e470b9a2..5b5cfb39dd 100644 --- a/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift +++ b/provider-swift/Sources/ProviderCore/Service/ClusterServiceAgent.swift @@ -70,6 +70,12 @@ public enum ClusterServiceAgent { serviceDirectory.appendingPathComponent("service-health.json") } + /// The heartbeat of the service's coordinator-paired part: a file of its own, never the service's + /// (`ClusterService.partEnvironment`). + public static func partHealthPath(serviceDirectory: URL) -> URL { + serviceDirectory.appendingPathComponent("part-health.json") + } + // MARK: - Install public enum Outcome: String, Sendable, Equatable { diff --git a/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift b/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift index 8ebeab2888..88d2da7770 100644 --- a/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterRuntimeFactsCommand.swift @@ -4,30 +4,75 @@ import ProviderCore extension Cluster { /// The cluster runtime facts of an app bundle (`ClusterRuntimeApprovalFacts`), - /// printed in their canonical form: the digests the guided setup registers - /// with the coordinator for a model. It reads metadata only: no model - /// weights, no GPU, no configuration, no network and no secret. + /// printed in their canonical form: the digests a cluster approval of that + /// build pins, each model's pair-serving grant, and the parity + /// qualifications of the models this build declares public + /// (`ClusterPublicModels`). What it leaves out is named on standard error: a + /// declared family without a qualification and, with release candidates, + /// another registered model's catalog ID. The release lane runs the final + /// signed app's own CLI, so the declaration and the records are that + /// build's. It reads metadata only: no model weights, no GPU, no + /// configuration, no network and no secret. struct RuntimeFacts: ParsableCommand { static let configuration = CommandConfiguration(commandName: "runtime-facts", abstract: "Print the cluster runtime facts of an app bundle's cluster helpers and models.", shouldDisplay: false) @Option(help: "The app bundle whose Contents/Helpers are described.") - var app: String + var app: String? @Option(name: .customLong("model"), help: "ID=DIRECTORY or ID=CONFIG,MANIFEST of one model (repeatable).") var models: [String] = [] + @Option(name: .customLong("release-candidates"), + help: "A folder of candidate model folders: describe every model this build qualifies on a cluster.") + var releaseCandidates: String? + @Flag(name: .customLong("list-release-models"), help: "Print the models this build qualifies on a cluster as JSON.") + var listReleaseModels = false func validate() throws { - guard !models.isEmpty else { throw ValidationError("Give at least one --model") } + if listReleaseModels { + guard app == nil, models.isEmpty, releaseCandidates == nil else { + throw ValidationError("--list-release-models takes no other option") + } + return + } + guard app != nil, models.isEmpty != (releaseCandidates == nil) else { + throw ValidationError("Give --app and either --model or --release-candidates") + } } func run() throws { + if listReleaseModels { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + FileHandle.standardOutput.write(try encoder.encode(ClusterRuntimeApprovalFacts.releaseModels)) + return + } + guard let app else { throw ValidationError("Give --app") } let installation = ClusterRuntimeApprovalFacts.Installation(app: URL(fileURLWithPath: app, isDirectory: true)) + if let releaseCandidates { + let facts = try ClusterRuntimeApprovalFacts.release(installation: installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: URL(fileURLWithPath: releaseCandidates, isDirectory: true)), + note: Self.note) + // The release registers these bytes: they must read back under the strict decoder, and every ID a + // coordinator derives for this build's version must fit. + let bytes = try facts.canonicalBytes() + _ = try ClusterRuntimeApprovalFacts(canonical: bytes) + Self.note(facts) + FileHandle.standardOutput.write(bytes) + return + } let given = try models.map(ClusterRuntimeApprovalFacts.modelArgument) let facts = try ClusterRuntimeApprovalFacts.compute(installation: installation, models: given.map { $0.files }) let named = Set(facts.models.map(\.model)), expected = Set(given.map { $0.model }) guard named == expected, given.count == facts.models.count else { throw ValidationError("The manifests name \(named.sorted().joined(separator: ", ")), not \(given.map { $0.model }.joined(separator: ", "))") } + Self.note(facts) FileHandle.standardOutput.write(try facts.canonicalBytes()) } + + static func note(_ facts: ClusterRuntimeApprovalFacts) { + for line in facts.unqualifiedDeclaredFamilies() { note(line) } + } + + static func note(_ line: String) { FileHandle.standardError.write(Data("note: \(line)\n".utf8)) } } } diff --git a/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift b/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift index b033f1ed97..a7a24525b3 100644 --- a/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift +++ b/provider-swift/Sources/darkbloom/ClusterSetupWizardCommand.swift @@ -103,6 +103,7 @@ extension Cluster.Setup { var service = try Self.serviceSettings(config: config, modelDir: modelDir, worker: worker) service.wizard.privateMiMoImageQualification = request.privateMiMoImageQualification service.wizard.privateGLMImageQualification = request.privateGLMImageQualification + service.wizard.servingScope = request.scope let arguments = ["cluster", "service"] + (config.map { ["--config", $0] } ?? []) + (worker.map { ["--worker", $0] } ?? []) return .init(service: service, serviceArguments: arguments) diff --git a/provider-swift/Tests/ClusterMemberFixtureChild/MemberFixtureServicePart.swift b/provider-swift/Tests/ClusterMemberFixtureChild/MemberFixtureServicePart.swift index d5737bb0bb..d906e3bc96 100644 --- a/provider-swift/Tests/ClusterMemberFixtureChild/MemberFixtureServicePart.swift +++ b/provider-swift/Tests/ClusterMemberFixtureChild/MemberFixtureServicePart.swift @@ -25,6 +25,10 @@ func memberFixtureServicePart(arguments: [String]) throws { termination.resume() defer { termination.cancel() } guard registered.wait(timeout: .now() + 2) == .success else { throw MemberFixtureError.invalid } + // The heartbeat file the service told this part to beat into (written before `ready`, so a test sees both). + if let health = ProcessInfo.processInfo.environment["DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE"] { + try Data(health.utf8).write(to: directory.appendingPathComponent("\(role)-\(pid).health"), options: .withoutOverwriting) + } try Data(String(pid).utf8).write(to: ready, options: .withoutOverwriting) while true { diff --git a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift index ba5180860f..726fd78eb4 100644 --- a/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift +++ b/provider-swift/Tests/ClusterPlacementChecks/PlacementSetupCheck.swift @@ -1257,9 +1257,11 @@ import Foundation require("a hand-off record qualifies the hand-off family for public traffic, and the owner is served in every mode", publicFamilies(handoffModel) == [.handOff] && allows([m3Ultra, m5Ultra], handoffModel, cuts: [8], .phaseSplitMTP) && allows([m3Ultra, m5Ultra], handoffModel, cuts: [8], .pipeline) && allows([m3Ultra, m5Ultra], handoffModel, cuts: [8], .pipelineCompactDecode)) - require("public traffic for a family no record passed is not yet qualified", - ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoffModel, mode: .pipeline, decisions: decisions) == ClusterPairOwnerServing.notYetQualified - && ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoffModel, mode: .phaseSplit, decisions: decisions).hasPrefix("qualified for public traffic")) + require("public traffic for a family no record passed is not yet qualified (records only, no public declaration)", + ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoffModel, mode: .pipeline, decisions: decisions, publicModels: []) + == ClusterPairOwnerServing.notYetQualified + && ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoffModel, mode: .phaseSplit, decisions: decisions, publicModels: []) + .hasPrefix("qualified for public traffic")) require("a placement checked without its mode is refused", reason([m3Ultra, m5Ultra], handoffModel, cuts: [8], nil).contains("without its generation mode")) let handoff = try? ClusterPairServingGrants.grant(runtimeModelID: handoffModel, publicModelID: "p", decisions: decisions) require("a grant lists its families and no chip", handoff?.families == [.handOff] && handoff?.qualifiedChipClasses == [m3Ultra!, m5Ultra!] diff --git a/provider-swift/Tests/ClusterPlacementChecks/run.sh b/provider-swift/Tests/ClusterPlacementChecks/run.sh index df1c71901a..4ac7ce3d18 100755 --- a/provider-swift/Tests/ClusterPlacementChecks/run.sh +++ b/provider-swift/Tests/ClusterPlacementChecks/run.sh @@ -38,6 +38,7 @@ xcrun swiftc -j 4 "${task_flags[@]}" -D DARKBLOOM_CLUSTER_FIXTURE_ARTIFACTS -par "$task_provider/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift" "$task_provider/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift" \ "$task_provider/Tests/ClusterInstalledSessionChecks/AttestationSignerStandIn.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairServingGrant.swift" \ + "$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/ClusterPublicModels.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledPairQualificationRecords.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementSetup.swift" \ "$task_provider/Sources/ProviderCore/Inference/Distributed/Placement/ClusterPlacementFlow.swift" \ diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift new file mode 100644 index 0000000000..5dbeb80d8d --- /dev/null +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterOnboardingScopeSettingsTests.swift @@ -0,0 +1,22 @@ +import Testing +import ProviderCore +@testable import darkbloom + +/// UNRUN: CLI parsing/settings binding only; no live onboarding or child starts. How `darkbloom cluster` was asked to +/// serve reaches the settings the guided setup plans with (`ClusterSetupOperations.LiveSettings.servingScope`): +/// `darkbloom cluster local` plans a local cluster, which keeps Qwen's speculative assistant, and plain +/// `darkbloom cluster` plans for the scope the setup record saved. +struct ClusterOnboardingScopeSettingsTests { + @Test func theScopeAskedForReachesTheSettingsThePlanReads() throws { + let local = try #require(try Darkbloom.parseAsRoot(["cluster", "local", "--bind", "127.0.0.1"]) as? Cluster.Local) + let localLive = try Cluster.Setup.onboardingSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil, + request: local.onboardingRequest) + #expect(localLive.service.wizard.servingScope == .localOnly(bind: "127.0.0.1")) + let plain = try Cluster.Setup.onboardingSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil, + request: .init()) + #expect(plain.service.wizard.servingScope == nil) + // The cluster service plans from the record (its re-plans after an update or a memory refusal), never from a run. + let service = try Cluster.Setup.serviceSettings(config: "/fixture/provider.toml", modelDir: nil, worker: nil) + #expect(service.wizard.servingScope == nil) + } +} diff --git a/provider-swift/Tests/DarkbloomCLITests/ClusterRuntimeFactsCommandTests.swift b/provider-swift/Tests/DarkbloomCLITests/ClusterRuntimeFactsCommandTests.swift index 6500fc23dc..e547b5138c 100644 --- a/provider-swift/Tests/DarkbloomCLITests/ClusterRuntimeFactsCommandTests.swift +++ b/provider-swift/Tests/DarkbloomCLITests/ClusterRuntimeFactsCommandTests.swift @@ -4,18 +4,26 @@ import Testing @Suite("Cluster runtime-facts CLI") struct ClusterRuntimeFactsCommandTests { - @Test("the app and one or more models parse, and the command stays hidden") + @Test("each mode parses: the model list, given models, release candidates; the command stays hidden") func accepted() throws { + #expect(try Cluster.RuntimeFacts.parse(["--list-release-models"]).listReleaseModels) let given = try Cluster.RuntimeFacts.parse(["--app", "/A/Darkbloom.app", "--model", "Qwen3.5-9B=/m/q", "--model", "glm-5.3-flash=/m/g/config.json,/m/g/manifest.json"]) #expect(given.models.count == 2 && given.app == "/A/Darkbloom.app") + let release = try Cluster.RuntimeFacts.parse(["--app", "/A/Darkbloom.app", "--release-candidates", "/c"]) + #expect(release.releaseCandidates == "/c" && release.models.isEmpty) + #expect(try Darkbloom.parseAsRoot(["cluster", "runtime-facts", "--list-release-models"]) is Cluster.RuntimeFacts) #expect(try Darkbloom.parseAsRoot(["cluster", "runtime-facts", "--app", "/A", "--model", "a=/m"]) is Cluster.RuntimeFacts) #expect(Cluster.RuntimeFacts.configuration.shouldDisplay == false) } - @Test("a missing app or no model refuses") + @Test("mixed, incomplete or contradictory modes refuse") func rejected() { - for values in [[], ["--app", "/A"], ["--model", "a=/m"]] { + for values in [["--list-release-models", "--app", "/A"], ["--list-release-models", "--model", "a=/m"], + ["--list-release-models", "--release-candidates", "/c"], + [], ["--app", "/A"], ["--model", "a=/m"], ["--release-candidates", "/c"], + ["--app", "/A", "--model", "a=/m", "--release-candidates", "/c"], + ["--app", "/A", "--require-model", "a", "--release-candidates", "/c"]] { #expect(throws: (any Error).self, "\(values)") { _ = try Cluster.RuntimeFacts.parse(values) } } } diff --git a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift index cc47255b81..af09d07f5e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift @@ -1,16 +1,21 @@ +import CryptoKit import Foundation import Testing import DarkbloomClusterProtocol import DarkbloomClusterRuntime @testable import ProviderCore -/// The cluster runtime facts the guided setup registers. The capability bytes are +/// The cluster runtime facts a release registers and the guided setup matches. The capability bytes are /// the runtime catalog's real description of the pinned Qwen3.5-9B and MiMo /// metadata fixtures; a shell child stands in for the worker process at the /// process seam and prints them. No model, GPU or network. @Suite("Cluster runtime approval facts") struct ClusterRuntimeApprovalFactsTests { static let qwenArtifact = "127de76b4ef82b7aaa0acaac0ee31c784cff066eda64291f521f051469b7c24b" + /// One Gemma 4 26B artifact: `gemma-4-26b` and `gemma-4-26b-8bit` name it. + static let gemmaArtifact = "a4722b6020adb1894c700b45ddcd58bc0e0f033abe7139f86cbbbfe60cba4eb6" + /// The release version the decoder rows name (`init(canonical:releaseVersion:)`). + static let releaseVersion = "1.2.3" @Test func everyDigestIsTheOneTheMembersChecksCompare() throws { let f = try Fixture() @@ -53,27 +58,200 @@ struct ClusterRuntimeApprovalFactsTests { #expect(try f.calls() == ["--describe-runtime --config \(configuration) --manifest \(manifest) --expected-executable-sha256 \(facts.nativeRuntimeSHA256)"]) } - @Test func canonicalBytesAreSortedWithoutWhitespace() throws { + @Test func canonicalBytesRoundTripAndAreSortedWithoutWhitespace() throws { let facts = try Self.facts() let bytes = try facts.canonicalBytes() - let text = String(decoding: bytes, as: UTF8.self) - #expect(text.hasPrefix(#"{"metallib_sha256":""#)) - #expect(text.contains(#""models":[{"artifact_sha256":""#)) - #expect(text.contains(#""model":"EigenLabs/Qwen3.8-27B-4bit-mtp""#)) - #expect(text.hasSuffix(#""schema":"darkbloom_cluster_runtime_v1"}"#)) - #expect(!text.contains(" ") && !text.contains("\n") && !text.contains(#"\/"#)) + func h(_ seed: Character) -> String { String(repeating: seed, count: 64) } + func model(_ name: String, _ seed: Character, grant: String, qualifications: String) -> String { + #"{"artifact_sha256":"\#(h(seed))","capability_sha256":"\#(h("c"))","model":"\#(name)","pair_serving_grant":\#(grant),"# + + #""parity_qualifications":\#(qualifications),"profile_sha256":"\#(h("d"))","resource_policy_sha256":"\#(h("e"))"}"# + } + func grant(_ seed: Character, _ families: [String]) -> String { + #"{"evidence_sha256":"\#(h(seed))","mode_families":[\#(families.map { "\"\($0)\"" }.joined(separator: ","))]}"# + } + func qualification(_ schedule: Int, _ mode: String, cuts: String, media: Bool) -> String { + #"{"cuts":[\#(cuts)],"diverged":false,"evidence_sha256":"\#(h("f"))","mode":"\#(mode)","# + + #""numerics_classes":["g17d-nax1-mlx-22222222-macos27.0","g17d-nax1-mlx-22222222-macos27.0"],"promotable":true,"# + + #""qualified_at":"2026-10-31T00:00:00Z","request_envelope":{"max_output_tokens":1048576,"max_prompt_tokens":1048576,"# + + #""sampling":true,"tools":true,"video":\#(media),"vision":\#(media)},"schedule":\#(schedule),"tensor_parallel_shares":null}"# + } + // Keys in byte order at every level, a model without a grant and equal shares written as null, no whitespace, no + // escaped slash and no trailing newline. Qualifications: the pipeline's (text only), then tensor parallel's, + // schedules ascending. + let qualifications = [qualification(1, "pipeline_v1", cuts: "32", media: false), qualification(2, "pipeline_v1", cuts: "32", media: false), + qualification(1, "tensor_parallel_v1", cuts: "", media: true), + qualification(2, "tensor_parallel_v1", cuts: "", media: true)] + let golden = #"{"metallib_sha256":"\#(h("2"))","models":["# + + [model("EigenLabs/Qwen3.8-27B-4bit-mtp", "5", grant: grant("f", ["pipeline", "tensor_parallel"]), + qualifications: "[" + qualifications.joined(separator: ",") + "]"), + model("Qwen3.5-9B", "6", grant: grant("a", ["hand_off", "pipeline", "pipeline_speculative", "tensor_parallel"]), + qualifications: "[]"), + model("glm-5.3-flash", "7", grant: "null", qualifications: "[]")].joined(separator: ",") + + #"],"native_runtime_sha256":"\#(h("1"))","placement_policy_sha256":"\#(h("4"))","# + + #""resource_library_sha256":"\#(h("3"))","schema":"darkbloom_cluster_runtime_v2"}"# + #expect(String(decoding: bytes, as: UTF8.self) == golden) + let decoded = try ClusterRuntimeApprovalFacts(canonical: bytes, releaseVersion: Self.releaseVersion) + #expect(decoded == facts) + #expect(try decoded.canonicalBytes() == bytes) } - @Test func rulesRefuseDigestsCountsOrderAndModelIDs() throws { + /// The block the release lane computes for GLM-5.3-Flash on DevNet: the installed 0.10.5-dev.branch.17 app's own + /// worker described DevNet's catalog metadata (`--release-candidates`: catalog entry text, image and video; a + /// config.json of 45 layers). Its v1 digests are the app's own v1 output; the grant and the qualifications are this + /// build's declaration for that metallib. + @Test func theGLMBlockOfTheBranch17AppIsPinned() throws { + let data = try Data(contentsOf: Fixture.providerTests.appendingPathComponent("Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json")) + let facts = try ClusterRuntimeApprovalFacts(canonical: data, releaseVersion: "0.10.5-dev.branch.18") + #expect(try facts.canonicalBytes() == data) + #expect(facts.nativeRuntimeSHA256 == "c465b19a0e8965d19717bd91dd7a29d0113f38c476cfaf06ed8fe3cdc5c82550") + #expect(facts.metallibSHA256 == "98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be") + let glm = try #require(facts.models.first) + #expect(facts.models.map(\.model) == ["glm-5.3-flash"]) + #expect(glm.capabilitySHA256 == "2069ee1bf4e5f829203a252dfddf7ea365d322b76c33a662e384aaf7600fb462") + #expect(glm.pairServingGrant == .init(evidenceSHA256: ClusterPublicModels.evidenceSHA256, modeFamilies: ["pipeline", "tensor_parallel"])) + let declared = try #require(ClusterPublicModels.declared.first { $0.catalogModelID == "glm-5.3-flash" }) + #expect(glm.parityQualifications == ClusterRuntimeApprovalFacts.parityQualifications(declared, metallibSHA256: facts.metallibSHA256, + inputModalities: ["text", "image", "video"], layers: 45, servesMedia: { $0 == .tensorParallel })) + // Per schedule, q1 the pipeline (cut at 45 / 2 = 22) and q2 tensor parallel. + #expect(glm.parityQualifications.map(\.mode) == [.pipeline, .pipeline, .tensorParallel, .tensorParallel]) + #expect(glm.parityQualifications.map(\.schedule) == [1, 2, 1, 2]) + #expect(glm.parityQualifications.map(\.cuts) == [[22], [22], [], []]) + // What both live M5 Ultras register (ClusterMemberDeviceProfile.numericsClass). + #expect(glm.parityQualifications.allSatisfy { $0.numericsClasses == ["g17d-nax1-mlx-98bab9d7-macos27.0", "g17d-nax1-mlx-98bab9d7-macos27.0"] }) + // Tensor parallel takes the catalog's images and video; the pipeline is text only. + #expect(glm.parityQualifications.map { $0.requestEnvelope.vision && $0.requestEnvelope.video } == [false, false, true, true]) + #expect(glm.parityQualifications.allSatisfy { !$0.requestEnvelope.vision || $0.mode == .tensorParallel }) + #expect(facts.unqualifiedDeclaredFamilies().isEmpty) + } + + @Test func decoderRefusesUnknownMissingOrMistypedFields() throws { + let object = try JSONSerialization.jsonObject(with: Self.facts().canonicalBytes()) as! [String: Any] + var rows: [String: Any] = [:] + func edited(_ change: (inout [String: Any]) -> Void) -> [String: Any] { var copy = object; change(©); return copy } + func editedModel(_ change: (inout [String: Any]) -> Void) -> [String: Any] { + edited { block in var models = block["models"] as! [[String: Any]]; change(&models[0]); block["models"] = models } + } + func editedGrant(_ change: (inout [String: Any]) -> Void) -> [String: Any] { + editedModel { model in var grant = model["pair_serving_grant"] as! [String: Any]; change(&grant); model["pair_serving_grant"] = grant } + } + func editedQualification(_ change: (inout [String: Any]) -> Void) -> [String: Any] { + editedModel { model in + var qualifications = model["parity_qualifications"] as! [[String: Any]] + change(&qualifications[0]); model["parity_qualifications"] = qualifications + } + } + func editedEnvelope(_ change: (inout [String: Any]) -> Void) -> [String: Any] { + editedQualification { q in var envelope = q["request_envelope"] as! [String: Any]; change(&envelope); q["request_envelope"] = envelope } + } + rows["unknown field"] = edited { $0["extra"] = 1 } + rows["missing field"] = edited { $0.removeValue(forKey: "placement_policy_sha256") } + rows["schema v1"] = edited { $0["schema"] = "darkbloom_cluster_runtime_v1" } + rows["unknown model field"] = editedModel { $0["extra"] = 1 } + rows["missing model field"] = editedModel { $0.removeValue(forKey: "profile_sha256") } + rows["no pair_serving_grant"] = editedModel { $0.removeValue(forKey: "pair_serving_grant") } + rows["grant a string"] = editedModel { $0["pair_serving_grant"] = "pipeline" } + rows["grant a list"] = editedModel { $0["pair_serving_grant"] = ["pipeline"] } + rows["grant empty"] = editedModel { $0["pair_serving_grant"] = [String: Any]() } + rows["unknown grant field"] = editedGrant { $0["granted_at"] = "2026-10-31T00:00:00Z" } + rows["missing grant field"] = editedGrant { $0.removeValue(forKey: "mode_families") } + rows["families not a list"] = editedGrant { $0["mode_families"] = "pipeline" } + rows["family not a string"] = editedGrant { $0["mode_families"] = [1] } + rows["no parity_qualifications"] = editedModel { $0.removeValue(forKey: "parity_qualifications") } + rows["qualifications null"] = editedModel { $0["parity_qualifications"] = NSNull() } + rows["qualification a string"] = editedModel { $0["parity_qualifications"] = ["tensor_parallel"] } + rows["unknown qualification field"] = editedQualification { $0["id"] = "q1" } + rows["missing qualification field"] = editedQualification { $0.removeValue(forKey: "qualified_at") } + rows["shares absent"] = editedQualification { $0.removeValue(forKey: "tensor_parallel_shares") } + rows["shares not null"] = editedQualification { $0["tensor_parallel_shares"] = ["version": 1, "per_mille": [500, 500]] } + rows["unknown mode"] = editedQualification { $0["mode"] = "tensor_parallel_v9" } + rows["schedule a string"] = editedQualification { $0["schedule"] = "1" } + rows["promotable a number"] = editedQualification { $0["promotable"] = 1 } + rows["unknown envelope field"] = editedEnvelope { $0["logprobs"] = true } + rows["missing envelope field"] = editedEnvelope { $0.removeValue(forKey: "video") } + rows["mistyped digest"] = edited { $0["metallib_sha256"] = 7 } + rows["models not a list"] = edited { $0["models"] = [:] as [String: Any] } + for (label, value) in rows { + let data = try JSONSerialization.data(withJSONObject: value) + #expect(throws: ClusterConfigurationError.self, "\(label)") { try ClusterRuntimeApprovalFacts(canonical: data, releaseVersion: Self.releaseVersion) } + } + // A repeated key, also one spelled with an escape, at the top, in a model, a grant, a qualification or its envelope. + let text = String(decoding: try Self.facts().canonicalBytes(), as: UTF8.self) + for (label, repeated) in [ + ("top", text.replacingOccurrences(of: #"{"metallib_sha256":"#, + with: #"{"schema":"darkbloom_cluster_runtime_v2","metallib_sha256":"#)), + ("escaped", text.replacingOccurrences(of: #"{"metallib_sha256":"#, + with: #"{"sch\u0065ma":"darkbloom_cluster_runtime_v2","metallib_sha256":"#)), + ("model", text.replacingOccurrences(of: #"[{"artifact_sha256":"#, with: #"[{"model":"Z","artifact_sha256":"#)), + ("grant", text.replacingOccurrences(of: #""pair_serving_grant":{"evidence_sha256":"#, + with: #""pair_serving_grant":{"mode_families":["pipeline"],"evidence_sha256":"#)), + ("qualification", text.replacingOccurrences(of: #"{"cuts":[],"#, with: #"{"schedule":2,"cuts":[],"#)), + ("envelope", text.replacingOccurrences(of: #"{"max_output_tokens":"#, with: #"{"video":false,"max_output_tokens":"#)), + ] { + #expect(repeated != text, "\(label)") + #expect(throws: ClusterConfigurationError.self, "\(label)") { try ClusterRuntimeApprovalFacts(canonical: Data(repeated.utf8), releaseVersion: Self.releaseVersion) } + } + for data in [Data("{".utf8), Data("[]".utf8), Data(repeating: 32, count: ClusterRuntimeApprovalFacts.maximumEncodedBytes + 1)] { + #expect(throws: ClusterConfigurationError.self) { try ClusterRuntimeApprovalFacts(canonical: data, releaseVersion: Self.releaseVersion) } + } + } + + @Test func decoderRefusesFactsWhoseDerivedIDsExceedTheirBound() throws { + // release/1.2.3//s2: 17 bytes plus the model ID; a grant's ID adds "/grant", a qualification's "/q1" or "/q2". + func block(_ model: String, granted: Bool, qualified: Bool) throws -> Data { + var object = try JSONSerialization.jsonObject(with: Self.facts().canonicalBytes()) as! [String: Any] + var models = object["models"] as! [[String: Any]] + models = [models[0]]; models[0]["model"] = model + if !granted { models[0]["pair_serving_grant"] = NSNull() } + if !qualified { models[0]["parity_qualifications"] = [Any]() } + object["models"] = models + return try JSONSerialization.data(withJSONObject: object) + } + func m(_ count: Int) -> String { String(repeating: "m", count: count) } + #expect("release/1.2.3/\(m(111))/s2".utf8.count == ClusterRuntimeApprovalFacts.maximumDerivedIDBytes) + // The longest model ID that fits release 1.2.3; the bound follows the version the caller names, and a dev + // release version is 13 bytes longer. + for (granted, qualified, fits) in [(false, false, 111), (false, true, 108), (true, false, 105), (true, true, 105)] { + for (version, longest) in [("1.2.3", fits), ("1.2.3-dev.branch.7", fits - 13)] { + let label = "granted \(granted), qualified \(qualified), \(version)" + #expect(try ClusterRuntimeApprovalFacts(canonical: block(m(longest), granted: granted, qualified: qualified), + releaseVersion: version).models.map(\.model) == [m(longest)], "\(label)") + #expect(throws: ClusterConfigurationError.self, "\(label)") { + try ClusterRuntimeApprovalFacts(canonical: block(m(longest + 1), granted: granted, qualified: qualified), releaseVersion: version) + } + } + } + // One grant per approval; n counts each schedule's qualifications in block order: q1 the pipeline, q2 tensor parallel. + let facts = try Self.facts() + #expect(ClusterRuntimeApprovalFacts.derivedIDs(facts.models[0], releaseVersion: "V") + == ["s1", "s2", "s1/grant", "s2/grant", "s1/q1", "s2/q1", "s1/q2", "s2/q2"].map { "release/V/EigenLabs/Qwen3.8-27B-4bit-mtp/" + $0 }) + #expect(ClusterRuntimeApprovalFacts.derivedIDs(facts.models[2], releaseVersion: "V") == ["release/V/glm-5.3-flash/s1", "release/V/glm-5.3-flash/s2"]) + } + + @Test func rulesRefuseDigestsCountsOrderModelIDsGrantsAndQualifications() throws { let facts = try Self.facts(), good = facts.models func make(models: [ClusterRuntimeApprovalFacts.Model] = good, native: String? = nil) throws -> ClusterRuntimeApprovalFacts { try .init(nativeRuntimeSHA256: native ?? facts.nativeRuntimeSHA256, metallibSHA256: facts.metallibSHA256, resourceLibrarySHA256: facts.resourceLibrarySHA256, placementPolicySHA256: facts.placementPolicySHA256, models: models) } - func named(_ name: String, _ base: ClusterRuntimeApprovalFacts.Model = good[0]) -> ClusterRuntimeApprovalFacts.Model { - .init(model: name, artifactSHA256: base.artifactSHA256, capabilitySHA256: base.capabilitySHA256, - profileSHA256: base.profileSHA256, resourcePolicySHA256: base.resourcePolicySHA256) + func named(_ name: String, _ base: ClusterRuntimeApprovalFacts.Model = good[1], grant: ClusterRuntimeApprovalFacts.PairServingGrant? = nil, + qualifications: [ClusterRuntimeApprovalFacts.ParityQualification] = []) -> ClusterRuntimeApprovalFacts.Model { + .init(model: name, artifactSHA256: base.artifactSHA256, capabilitySHA256: base.capabilitySHA256, profileSHA256: base.profileSHA256, + resourcePolicySHA256: base.resourcePolicySHA256, pairServingGrant: grant, parityQualifications: qualifications) + } + func granted(_ families: [String], evidence: String = String(repeating: "f", count: 64)) -> ClusterRuntimeApprovalFacts.Model { + named("a", grant: .init(evidenceSHA256: evidence, modeFamilies: families)) + } + let q = good[0].parityQualifications[0] + func qualified(schedule: UInt8 = 1, classes: [String]? = nil, cuts: [Int] = [], mode: ClusterGenerationMode = .tensorParallel, + promotable: Bool = true, diverged: Bool = false, evidence: String? = nil, at: String = "2026-10-31T00:00:00Z", + envelope: ClusterRequestEnvelope? = nil) -> ClusterRuntimeApprovalFacts.Model { + named("a", qualifications: [.init(schedule: schedule, numericsClasses: classes ?? q.numericsClasses, cuts: cuts, mode: mode, + promotable: promotable, diverged: diverged, evidenceSHA256: evidence ?? q.evidenceSHA256, qualifiedAt: at, + requestEnvelope: envelope ?? q.requestEnvelope)]) + } + func envelope(vision: Bool = true, video: Bool = true, prompt: Int = 1_048_576, output: Int = 1_048_576) -> ClusterRequestEnvelope { + .init(sampling: true, tools: true, vision: vision, video: video, maxPromptTokens: prompt, maxOutputTokens: output) } let zero = String(repeating: "0", count: 64) let rows: [(String, () throws -> ClusterRuntimeApprovalFacts)] = [ @@ -83,21 +261,53 @@ struct ClusterRuntimeApprovalFactsTests { ("zero model digest", { try make(models: [.init(model: "a", artifactSHA256: zero, capabilitySHA256: good[0].capabilitySHA256, profileSHA256: good[0].profileSHA256, resourcePolicySHA256: good[0].resourcePolicySHA256)]) }), ("no models", { try make(models: []) }), - ("too many models", { try make(models: (0..<33).map { named(String(format: "m%02d", $0)) }) }), + ("too many models", { try make(models: (0..<65).map { named(String(format: "m%02d", $0)) }) }), ("unsorted", { try make(models: Array(good.reversed())) }), ("repeated", { try make(models: [good[0], good[0]]) }), ("empty ID", { try make(models: [named("")]) }), ("long ID", { try make(models: [named(String(repeating: "a", count: 129))]) }), ("non-ASCII ID", { try make(models: [named("Qwen\u{e9}")]) }), ("control byte ID", { try make(models: [named("a\n")]) }), + ("no mode family", { try make(models: [granted([])]) }), + ("unknown mode family", { try make(models: [granted(["pipeline_mtp"])]) }), + ("mode families unsorted", { try make(models: [granted(["tensor_parallel", "pipeline"])]) }), + ("mode family repeated", { try make(models: [granted(["pipeline", "pipeline"])]) }), + ("zero grant evidence", { try make(models: [granted(["pipeline"], evidence: zero)]) }), + ("uppercase grant evidence", { try make(models: [granted(["pipeline"], evidence: String(repeating: "F", count: 64))]) }), + ("schedule 3", { try make(models: [qualified(schedule: 3)]) }), + ("one numerics class", { try make(models: [qualified(classes: ["g17d"])]) }), + ("three numerics classes", { try make(models: [qualified(classes: ["a", "b", "c"])]) }), + ("empty numerics class", { try make(models: [qualified(classes: ["", "b"])]) }), + ("space in a numerics class", { try make(models: [qualified(classes: ["a b", "b"])]) }), + ("tensor parallel with a cut", { try make(models: [qualified(cuts: [8])]) }), + ("pipeline without a cut", { try make(models: [qualified(mode: .pipeline)]) }), + ("zero cut", { try make(models: [qualified(cuts: [0], mode: .pipeline)]) }), + ("diverged and promotable", { try make(models: [qualified(diverged: true)]) }), + ("zero evidence", { try make(models: [qualified(evidence: zero)]) }), + ("not an instant", { try make(models: [qualified(at: "2026-10-31")]) }), + ("video without vision", { try make(models: [qualified(envelope: envelope(vision: false, video: true))]) }), + ("no prompt tokens", { try make(models: [qualified(envelope: envelope(prompt: 0))]) }), + ("too many output tokens", { try make(models: [qualified(envelope: envelope(output: 1_048_577))]) }), + ("a placement twice", { try make(models: [named("a", qualifications: [q, q])]) }), + ("nine qualifications", { try make(models: [named("a", qualifications: (0..<9).map { index in + .init(schedule: 1, numericsClasses: ["c\(index)", "c\(index)"], cuts: [], mode: .tensorParallel, promotable: true, + diverged: false, evidenceSHA256: q.evidenceSHA256, qualifiedAt: q.qualifiedAt, requestEnvelope: q.requestEnvelope) + })]) }), ] for (label, row) in rows { #expect(throws: ClusterConfigurationError.self, "\(label)") { _ = try row() } } // The bounds themselves are accepted, in byte order (uppercase first). - _ = try make(models: (0..<32).map { named(String(format: "m%02d", $0)) }) + _ = try make(models: (0..<64).map { named(String(format: "m%02d", $0)) }) _ = try make(models: [named(" " + String(repeating: "~", count: 127))]) _ = try make(models: [named("Z"), named("a")]) + _ = try make(models: [granted(["hand_off", "pipeline", "pipeline_speculative", "tensor_parallel"])]) + _ = try make(models: [qualified(cuts: [8], mode: .pipeline, promotable: false, diverged: true, + at: "2026-10-31T00:00:00.5+02:00", envelope: envelope(vision: false, video: false, prompt: 1, output: 1))]) + _ = try make(models: [named("a", qualifications: [q, qualified(schedule: 2).parityQualifications[0]])]) + // A grant from families is sorted by byte and unique. + #expect(ClusterRuntimeApprovalFacts.PairServingGrant(evidenceSHA256: q.evidenceSHA256, families: [.tensorParallel, .pipeline, .pipeline]) + .modeFamilies == ["pipeline", "tensor_parallel"]) } @Test func describingRefusesMissingUnsafeOrForeignInputs() throws { @@ -170,17 +380,412 @@ struct ClusterRuntimeApprovalFactsTests { for text in ["no-equals", "=/m", "id=", "id=/a,", "id=,/b", "id=/a,/b,/c"] { #expect(throws: ClusterConfigurationError.self, "\(text)") { _ = try ClusterRuntimeApprovalFacts.modelArgument(text) } } + + let f = try Fixture() + let folder = f.root.appendingPathComponent("listing", isDirectory: true) + for name in ["b", "a", ".hidden"] { + try FileManager.default.createDirectory(at: folder.appendingPathComponent(name), withIntermediateDirectories: true) + } + #expect(try ClusterRuntimeApprovalFacts.candidates(in: folder).map { $0.manifest.deletingLastPathComponent().lastPathComponent } == ["a", "b"]) + #expect(throws: ClusterConfigurationError.self) { _ = try ClusterRuntimeApprovalFacts.candidates(in: f.root.appendingPathComponent("none")) } + } + + @Test func theDeclarationIsTheOwnersTwoModelsWithItsEvidenceDocument() throws { + let declared = ClusterPublicModels.declared + #expect(declared.map(\.runtimeModelID) == ["registered_glm53_flash", "registered_qwen38_27b"]) + #expect(declared.map(\.catalogModelID) == ["glm-5.3-flash", "EigenLabs/Qwen3.8-27B-4bit-mtp"]) + let ranks = ClusterPublicModel.Ranks(count: 2, gpuArchitecture: "applegpu_g17d", macOSMajor: 27, macOSMinor: 0) + for model in declared { + // Owner ruling, 2026-10-31: pipeline and tensor parallel, for both models. + #expect(model.families == [.pipeline, .tensorParallel] && model.schedules == [1, 2] && model.ranks == ranks) + // The artifact the runtime registers for the model, which its bundled records ran: a release lists it. + #expect(ClusterPairServingGrants.decisions.artifacts(runtimeModelID: model.runtimeModelID) == [model.artifactSHA256]) + #expect(ClusterRuntimeApprovalFacts.releaseModels.contains(.init(runtimeModelID: model.runtimeModelID, + artifactSHA256: model.artifactSHA256))) + // Every declared family has a placement on the declared ranks. + for family in model.families { + #expect(ClusterPublicModels.placement(of: family, layers: 64, ranks: model.ranks.count) != nil, "\(family.rawValue)") + } + } + #expect(declared[0].artifactSHA256 == ClusterGLMImageCandidate.artifactSHA256) + #expect(ClusterPublicModels.qualifiedAt == "2026-10-31T00:00:00Z") + // The released CLI names the evidence document by its SHA-256: the checked-in report's. + let report = try Data(contentsOf: Fixture.repository.appendingPathComponent(ClusterPublicModels.evidenceDocument)) + #expect(ClusterPublicModels.evidenceSHA256 == Self.sha256(report)) + // What both live M5 Ultras register with the Metal library of 0.10.5-dev.branch.15 to .17. + #expect(ClusterRuntimeApprovalFacts.numericsClasses(ranks, metallibSHA256: "98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be") + == ["g17d-nax1-mlx-98bab9d7-macos27.0", "g17d-nax1-mlx-98bab9d7-macos27.0"]) + } + + @Test func aPipelineIsCutAtHalfItsLayersAndTensorParallelIsNotCut() { + func placement(_ family: ClusterPairServingModeFamily, _ layers: Int?) -> String? { + ClusterPublicModels.placement(of: family, layers: layers, ranks: 2).map { "\($0.mode.rawValue) \($0.cuts)" } + } + #expect(placement(.pipeline, 45) == "pipeline_v1 [22]") + #expect(placement(.pipeline, 64) == "pipeline_v1 [32]") + #expect(placement(.pipeline, 2) == "pipeline_v1 [1]") + #expect(placement(.pipeline, 1) == nil) + #expect(placement(.pipeline, nil) == nil) + #expect(placement(.tensorParallel, nil) == "tensor_parallel_v1 []") + #expect(placement(.handOff, 64) == nil && placement(.pipelineSpeculative, 64) == nil) + } + + @Test func theRequestEnvelopeAdmitsTheMediaTheCatalogEntryListsWhereThePlacementServesMedia() { + func envelope(_ modalities: [String], servesMedia: Bool = true) -> (vision: Bool, video: Bool) { + let e = ClusterPublicModels.requestEnvelope(inputModalities: modalities, servesMedia: servesMedia) + #expect(e.sampling && e.tools && e.maxPromptTokens == 1_048_576 && e.maxOutputTokens == 1_048_576) + return (e.vision, e.video) + } + #expect(envelope([]) == (false, false)) + #expect(envelope(["text"]) == (false, false)) + #expect(envelope(["text", "image"]) == (true, false)) + #expect(envelope(["text", "video"]) == (false, false)) + #expect(envelope(["text", "image", "video"]) == (true, true)) + #expect(envelope(["text", "image", "video"], servesMedia: false) == (false, false)) + } + + @Test func parityQualificationsComeFromTheDeclarationOfTheModelCatalogIDAndArtifact() throws { + let f = try Fixture() + let metallibClass = ClusterMemberDeviceProfile.numericsClass(architecture: "applegpu_g17d", + metallibSHA256: f.digest(f.installation.metallib), os: OperatingSystemVersion(majorVersion: 27, minorVersion: 0, patchVersion: 0)) + func qualifications(_ folder: URL, publicModels: [ClusterPublicModel] = ClusterPublicModels.declared, + catalog: Bool = false) throws -> [ClusterRuntimeApprovalFacts.ParityQualification] { + let files = catalog ? try ClusterRuntimeApprovalFacts.candidates(in: folder.deletingLastPathComponent()) + .first { $0.manifest.deletingLastPathComponent().lastPathComponent == folder.lastPathComponent }! + : ClusterRuntimeApprovalFacts.ModelFiles(directory: folder) + return try #require(ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [files], + publicModels: publicModels).models.first).parityQualifications + } + // The declared 27B (64 layers) given by hand: the pipeline then tensor parallel, each on both schedules, this + // build's class on both ranks, text only. + let q27 = try f.model("q27", fixture: "registered-qwen38-27b") + let byHand = try qualifications(q27) + #expect(byHand.map(\.mode) == [.pipeline, .pipeline, .tensorParallel, .tensorParallel]) + #expect(byHand.map(\.schedule) == [1, 2, 1, 2]) + #expect(byHand.map(\.cuts) == [[32], [32], [], []]) + for q in byHand { + #expect(q.numericsClasses == [metallibClass, metallibClass]) + #expect(q.promotable && !q.diverged && q.evidenceSHA256 == ClusterPublicModels.evidenceSHA256 && q.qualifiedAt == "2026-10-31T00:00:00Z") + #expect(q.requestEnvelope == ClusterPublicModels.requestEnvelope(inputModalities: [], servesMedia: true)) + } + // As a release candidate, the catalog entry's media where the placement serves media (tensor parallel, + // `ClusterModelFeaturePolicy.mediaContract`); the pipeline is text only. + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + func media(_ qualifications: [ClusterRuntimeApprovalFacts.ParityQualification]) -> [String] { + qualifications.map { "\($0.mode.rawValue) vision \($0.requestEnvelope.vision) video \($0.requestEnvelope.video)" } + } + let all = try f.model("27b-media", parent: candidates, fixture: "registered-qwen38-27b", modalities: ["text", "image", "video"]) + #expect(media(try qualifications(all, catalog: true)) == ["pipeline_v1 vision false video false", "pipeline_v1 vision false video false", + "tensor_parallel_v1 vision true video true", "tensor_parallel_v1 vision true video true"]) + let images = try f.model("27b-images", parent: candidates, fixture: "registered-qwen38-27b", modalities: ["text", "image"]) + #expect(media(try qualifications(images, catalog: true)) == ["pipeline_v1 vision false video false", "pipeline_v1 vision false video false", + "tensor_parallel_v1 vision true video false", "tensor_parallel_v1 vision true video false"]) + // Undeclared: another model, the declared model under another catalog ID, or no declaration at all. + #expect(try qualifications(try f.model("nine")).isEmpty) + #expect(try qualifications(try f.model("copy", fixture: "registered-qwen38-27b", modelID: "EigenLabs/Qwen3.8-27B-copy")).isEmpty) + #expect(try qualifications(q27, publicModels: []).isEmpty) + // Another declaration declares another model, with its own artifact only. + let nine = try f.model("nine-declared") + let declaration = ClusterPublicModel(runtimeModelID: "registered_qwen35_9b", catalogModelID: "Qwen3.5-9B", + artifactSHA256: Self.qwenArtifact, families: [.tensorParallel], schedules: [2], ranks: ClusterPublicModels.twoM5Ultras) + #expect(try qualifications(nine, publicModels: [declaration]).map(\.schedule) == [2]) + let otherArtifact = ClusterPublicModel(runtimeModelID: "registered_qwen35_9b", catalogModelID: "Qwen3.5-9B", + artifactSHA256: String(repeating: "e", count: 64), families: [.tensorParallel], schedules: [2], ranks: ClusterPublicModels.twoM5Ultras) + #expect(try qualifications(nine, publicModels: [otherArtifact]).isEmpty) + } + + /// The pipeline's cut comes from the layer count of the model's config.json (`num_hidden_layers`, at the top level or + /// in `text_config`); without a usable one the pipeline's qualifications are left out, the grant still names the + /// family, and the facts say so. + @Test func aDeclaredPipelineNeedsTheConfigLayerCountOrIsLeftOutAndSaid() throws { + let f = try Fixture() + func described(_ name: String, _ change: ((inout [String: Any]) -> Void)? = nil) throws -> ClusterRuntimeApprovalFacts { + let folder = try f.model(name, fixture: "registered-qwen38-27b") + if let change { + let url = folder.appendingPathComponent("config.json") + var object = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any] + change(&object) + try JSONSerialization.data(withJSONObject: object).write(to: url) + } + return try ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [.init(directory: folder)]) + } + func textLayers(_ value: Any?) -> (inout [String: Any]) -> Void { + { object in var text = object["text_config"] as! [String: Any]; text["num_hidden_layers"] = value; object["text_config"] = text } + } + func pipelineCuts(_ facts: ClusterRuntimeApprovalFacts) -> [[Int]] { + facts.models[0].parityQualifications.filter { $0.mode == .pipeline }.map(\.cuts) + } + let fixture = try described("as-is") + #expect(pipelineCuts(fixture) == [[32], [32]]) + #expect(fixture.unqualifiedDeclaredFamilies().isEmpty) + // A top-level count is read before text_config's. + #expect(pipelineCuts(try described("top") { $0["num_hidden_layers"] = 47 }) == [[23], [23]]) + for (label, value) in [("absent", nil), ("zero", 0), ("one layer", 1), ("negative", -4), ("a fraction", 64.5), + ("a string", "64"), ("a boolean", true)] as [(String, Any?)] { + let facts = try described(label, textLayers(value)) + #expect(facts.models[0].parityQualifications.map(\.mode) == [.tensorParallel, .tensorParallel], "\(label)") + #expect(facts.models[0].pairServingGrant?.modeFamilies == ["pipeline", "tensor_parallel"], "\(label)") + #expect(facts.unqualifiedDeclaredFamilies() == ["EigenLabs/Qwen3.8-27B-4bit-mtp carries no parity qualification for its " + + "declared pipeline family (a pipeline needs num_hidden_layers in config.json)"], "\(label)") + } + // An undeclared model has nothing to say. + #expect(try ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [.init(directory: f.model("nine"))]) + .unqualifiedDeclaredFamilies().isEmpty) + } + + @Test func grantIsTheDeclaredFamiliesOrThePublicGrantOfTheDescribedArtifactWithTheDigestOfItsRecords() throws { + let f = try Fixture() + let model = try f.model("qwen") + let qwen = ClusterPairServingGrants.records.filter { $0.runtimeModelID == "registered_qwen35_9b" && $0.outcome == .passed } + let pipeline = try #require(qwen.first { $0.mode == .pipeline }) + let tensor = try #require(qwen.first { $0.mode == .tensorParallel }) + // Another artifact of the same model, and a divergence of exactly the pipeline record's shape. + let otherArtifact = try Self.record(pipeline) { $0["artifactSHA256"] = String(repeating: "e", count: 64) } + let diverged = try Self.record(pipeline) { object in + var comparisons = object["comparisons"] as! [[String: Any]] + comparisons[0]["verdict"] = "diverged"; comparisons[0].removeValue(forKey: "gapInULPs") + object["comparisons"] = comparisons; object["passed"] = false + } + func grant(_ folder: URL, _ records: [ClusterPairQualificationRecord]) throws -> ClusterRuntimeApprovalFacts.PairServingGrant? { + try #require(ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [.init(directory: folder)], + decisions: ClusterPairServingDecisions(records: records)).models.first).pairServingGrant + } + // An undeclared model: the passing records of the described artifact, in the order given, canonical, joined by "\n". + let pipelineLine = try pipeline.encodedLine(), tensorLine = try tensor.encodedLine() + #expect(try grant(model, [tensor, otherArtifact, pipeline]) + == .init(evidenceSHA256: Self.sha256(Data((tensorLine + "\n" + pipelineLine).utf8)), modeFamilies: ["pipeline", "tensor_parallel"])) + #expect(try grant(model, [pipeline]) == .init(evidenceSHA256: Self.sha256(Data(pipelineLine.utf8)), modeFamilies: ["pipeline"])) + // No record of this artifact, or a pass that a divergence of the same shape contradicts: no grant. + #expect(try grant(model, []) == nil) + #expect(try grant(model, [otherArtifact]) == nil) + #expect(try grant(model, [pipeline, diverged]) == nil) + #expect(try grant(model, [pipeline, diverged, tensor]) + == .init(evidenceSHA256: Self.sha256(Data(tensorLine.utf8)), modeFamilies: ["tensor_parallel"])) + // A family still granted by another pass leaves the contradicted pass out of its evidence. + let otherCut = try #require(qwen.first { $0.mode == .pipeline && $0.cuts != pipeline.cuts }) + #expect(try grant(model, [pipeline, otherCut, diverged]) + == .init(evidenceSHA256: Self.sha256(Data(try otherCut.encodedLine().utf8)), modeFamilies: ["pipeline"])) + // By default the build's own bundled records: the grant a member of this build reports. + let bundled = try #require(ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [.init(directory: model)]).models.first) + let own = try ClusterRuntimeApprovalFacts.PairServingGrant(ClusterPairServingGrants.grant(runtimeModelID: "registered_qwen35_9b", + publicModelID: "Qwen3.5-9B", artifactSHA256: Self.qwenArtifact)) + #expect(bundled.pairServingGrant == own) + #expect(own.modeFamilies == ["hand_off", "pipeline", "pipeline_speculative", "tensor_parallel"]) + + // A declared model: its declared families with the evidence document's digest, whatever the records say. + let q27 = try f.model("q27", fixture: "registered-qwen38-27b") + let declaredGrant = ClusterRuntimeApprovalFacts.PairServingGrant(evidenceSHA256: ClusterPublicModels.evidenceSHA256, + modeFamilies: ["pipeline", "tensor_parallel"]) + #expect(try grant(q27, []) == declaredGrant) + #expect(try grant(q27, ClusterPairServingGrants.records) == declaredGrant) + // Undeclared, the same artifact's grant is its records'. + let undeclared = try #require(ClusterRuntimeApprovalFacts.compute(installation: f.installation, models: [.init(directory: q27)], + publicModels: []).models.first) + #expect(undeclared.pairServingGrant == (try ClusterRuntimeApprovalFacts.PairServingGrant(ClusterPairServingGrants.grant( + runtimeModelID: "registered_qwen38_27b", publicModelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", + artifactSHA256: ClusterPublicModels.declared[1].artifactSHA256)))) + #expect(undeclared.parityQualifications.isEmpty) + } + + @Test func bundledRecordLinesAreTheirCanonicalEncoding() throws { + // So a grant's evidence digest can be recomputed from the bundle's own lines. + let lines = ClusterPairQualificationRecordsBundled.jsonLines.split(separator: "\n").map(String.init).filter { !$0.isEmpty } + let records = try ClusterPairQualificationRecord.decodeLines(ClusterPairQualificationRecordsBundled.jsonLines) + #expect(!records.isEmpty && records.count == lines.count) + for (line, record) in zip(lines, records) { #expect(try record.encodedLine() == line) } + } + + @Test func aCandidateWhoseCatalogEntryIsNotItsOwnIsRefused() throws { + let f = try Fixture() + let listed = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact) + for (label, entry) in [("another model's", #"{"id":"glm-5.3-flash","input_modalities":["text"]}"#), + ("missing modalities", #"{"id":"Qwen3.5-9B"}"#), ("modalities mistyped", #"{"id":"Qwen3.5-9B","input_modalities":"text"}"#), + ("an extra field", #"{"id":"Qwen3.5-9B","input_modalities":[],"r2_prefix":"x"}"#), ("not JSON", "{"), ("absent", nil)] { + let candidates = f.root.appendingPathComponent("candidates-\(label)", isDirectory: true) + let folder = try f.model("only", parent: candidates) + let catalog = folder.appendingPathComponent("catalog.json") + if let entry { try Data(entry.utf8).write(to: catalog) } else { try FileManager.default.removeItem(at: catalog) } + #expect(throws: ClusterConfigurationError.self, "\(label)") { + _ = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [listed]) + } + } } - /// Facts with three models (byte order: uppercase before lowercase), for the codec rows. + @Test func releaseChoosesTheCandidateTheWorkerDescribesAsEachListedModel() throws { + let f = try Fixture() + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + _ = try f.model("0-refused", parent: candidates, refused: true) + _ = try f.model("1-accepted", parent: candidates) + _ = try f.model("2-later", parent: candidates) + let listed = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact) + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [listed]) + #expect(facts.models.map(\.model) == ["Qwen3.5-9B"]) + #expect(facts.models.first?.parityQualifications == []) + // The refused candidate was tried, the accepted one chosen, the rest not run. + #expect(try f.calls().count == 2) + #expect(try f.calls().last?.contains("1-accepted") == true) + } + + @Test func releaseDescribesEveryCatalogIDOfAListedArtifactAndNothingElse() throws { + let f = try Fixture() + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + _ = try f.model("0-qwen", parent: candidates) + _ = try f.model("1-copy", parent: candidates, modelID: "Qwen3.5-9B-copy") + _ = try f.model("2-unlisted", parent: candidates, fixture: "registered-qwen38-27b") + let qwen = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact) + // Listed, but the environment's catalog does not have it: no candidate, left out. + let absent = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_glm53_flash", + artifactSHA256: ClusterGLMImageCandidate.artifactSHA256) + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [qwen, absent]) + #expect(facts.models.map(\.model) == ["Qwen3.5-9B", "Qwen3.5-9B-copy"]) + // A candidate of an artifact the build does not list is never described. + #expect(try f.calls().count == 2) + #expect(try !f.calls().contains { $0.contains("2-unlisted") }) + } + + /// Production's catalog lists one artifact under two catalog IDs that the build registers as two + /// runtime models (`gemma-4-26b` and `gemma-4-26b-8bit`, one configuration), and only the 8-bit one + /// is a listed model. The ID the worker describes as the other model is that model's, not a failure. + @Test func releaseLeavesOutACatalogIDTheWorkerDescribesAsAnotherRegisteredModel() throws { + let f = try Fixture() + let candidates = try Self.gemmaCandidates(f) + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [Self.gemma8Bit]) + #expect(facts.models.map(\.model) == ["gemma-4-26b-8bit"]) + #expect(facts.models.allSatisfy { $0.artifactSHA256 == Self.gemmaArtifact }) + #expect(try f.calls().count == 2) + } + + @Test func releaseNamesTheCatalogIDOfAnotherRegisteredModelItLeavesOut() throws { + let f = try Fixture() + let candidates = try Self.gemmaCandidates(f) + var notes: [String] = [] + _ = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [Self.gemma8Bit], note: { notes.append($0) }) + #expect(notes.count == 1) + #expect(notes.first?.hasPrefix("left out, the catalog model ID of another registered model: gemma-4-26b (registered_gemma4_26b_8bit, \(Self.gemmaArtifact)): ") == true) + #expect(notes.first?.contains("0-gemma/manifest.json is registered_gemma4_26b") == true) + // Listed alone, the other model keeps its own ID and leaves out the 8-bit one. + let other = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_gemma4_26b", artifactSHA256: Self.gemmaArtifact) + notes = [] + let facts = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: [other], note: { notes.append($0) }) + #expect(facts.models.map(\.model) == ["gemma-4-26b"]) + #expect(notes.count == 1 && notes.first?.contains("gemma-4-26b-8bit (registered_gemma4_26b, ") == true) + } + + static let gemma8Bit = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_gemma4_26b_8bit", + artifactSHA256: gemmaArtifact) + + /// Two candidates of the one Gemma 4 26B artifact, as production's catalog lists it: `gemma-4-26b` + /// (registered_gemma4_26b) and `gemma-4-26b-8bit` (registered_gemma4_26b_8bit), one configuration. + private static func gemmaCandidates(_ f: Fixture) throws -> URL { + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + _ = try f.model("0-gemma", parent: candidates, fixture: "registered-gemma4-26b") + let eightBitManifest = try Data(contentsOf: Fixture.metadataFixtures + .appendingPathComponent("registered-gemma4-26b-8bit.manifest.json")) + let eightBit = try f.model("1-gemma-8bit", parent: candidates, fixture: "registered-gemma4-26b", manifest: eightBitManifest) + try ClusterRuntimeCapabilityCodec.encode(ClusterResidentModelCatalog.describe( + configuration: Data(contentsOf: eightBit.appendingPathComponent("config.json")), + manifest: eightBitManifest, runtimeBinarySHA256: f.workerSHA256)) + .write(to: eightBit.appendingPathComponent("capability.out")) + return candidates + } + + @Test func releaseNamesEveryCatalogModelItCannotDescribeAndRefusesAnEmptyResult() throws { + let f = try Fixture() + let candidates = f.root.appendingPathComponent("candidates", isDirectory: true) + _ = try f.model("refused", parent: candidates, refused: true) + let qwen = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact) + func message(_ models: [ClusterRuntimeApprovalFacts.ReleaseModel]) -> String { + do { + _ = try ClusterRuntimeApprovalFacts.release(installation: f.installation, + candidates: try ClusterRuntimeApprovalFacts.candidates(in: candidates), models: models) + return "" + } catch { return String(describing: error) } + } + let refused = message([qwen]) + #expect(refused.contains("Qwen3.5-9B (registered_qwen35_9b, \(Self.qwenArtifact))") && refused.contains("refused/manifest.json")) + + _ = try f.model("accepted", parent: candidates) + // Described only as another registered model: left out, so no model is left, and the refusal names it. + let another = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_other", artifactSHA256: Self.qwenArtifact) + let leftOut = message([another]) + #expect(leftOut.hasPrefix("No candidate folder holds a model this build qualifies on a cluster; left out, the catalog model ID " + + "of another registered model: Qwen3.5-9B (registered_other, \(Self.qwenArtifact)): ")) + #expect(leftOut.contains("is registered_qwen35_9b")) + let absent = ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_glm53_flash", + artifactSHA256: ClusterGLMImageCandidate.artifactSHA256) + #expect(message([absent]).contains("No candidate folder holds a model this build qualifies on a cluster")) + #expect(message([]).contains("No candidate folder holds a model this build qualifies on a cluster")) + } + + @Test func releaseModelsComeFromPassingRecordsOfModelsWithAStageAdapter() throws { + let bundled = ClusterRuntimeApprovalFacts.releaseModels + for required in [ClusterRuntimeApprovalFacts.ReleaseModel(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact), + .init(runtimeModelID: "registered_glm53_flash", artifactSHA256: ClusterGLMImageCandidate.artifactSHA256)] { + #expect(bundled.contains(required)) + } + #expect(bundled == bundled.sorted { ($0.runtimeModelID, $0.artifactSHA256) < ($1.runtimeModelID, $1.artifactSHA256) }) + #expect(Set(bundled).count == bundled.count) + + let passing = try #require(ClusterPairServingGrants.records.first { $0.runtimeModelID == "registered_qwen35_9b" && $0.passed }) + #expect(ClusterRuntimeApprovalFacts.qualifiedModels(records: [passing]) + == [.init(runtimeModelID: "registered_qwen35_9b", artifactSHA256: Self.qwenArtifact)]) + let excluded: [(String, ClusterPairQualificationRecord)] = [ + ("no stage adapter", try Self.record(passing) { $0["runtimeModelID"] = "registered_unknown_model" }), + ("diverged", try Self.record(passing) { object in + var comparisons = object["comparisons"] as! [[String: Any]] + comparisons[0]["verdict"] = "diverged"; comparisons[0].removeValue(forKey: "gapInULPs") + object["comparisons"] = comparisons; object["passed"] = false + }), + ("inconsistent", try Self.record(passing) { $0["schema"] = "another_schema" }), + ] + for (label, excludedRecord) in excluded { + #expect(ClusterRuntimeApprovalFacts.qualifiedModels(records: [excludedRecord]).isEmpty, "\(label)") + } + } + + /// Facts with three models (byte order: uppercase before lowercase) for the codec rows: the first declared (a grant + /// of two families, four parity qualifications), the second with a grant from records only, the third with neither. static func facts() throws -> ClusterRuntimeApprovalFacts { - func model(_ name: String, _ seed: Character) -> ClusterRuntimeApprovalFacts.Model { + func model(_ name: String, _ seed: Character, grant: ClusterRuntimeApprovalFacts.PairServingGrant? = nil, + qualifications: [ClusterRuntimeApprovalFacts.ParityQualification] = []) -> ClusterRuntimeApprovalFacts.Model { .init(model: name, artifactSHA256: String(repeating: seed, count: 64), capabilitySHA256: String(repeating: "c", count: 64), - profileSHA256: String(repeating: "d", count: 64), resourcePolicySHA256: String(repeating: "e", count: 64)) + profileSHA256: String(repeating: "d", count: 64), resourcePolicySHA256: String(repeating: "e", count: 64), + pairServingGrant: grant, parityQualifications: qualifications) + } + let classes = Array(repeating: "g17d-nax1-mlx-22222222-macos27.0", count: 2) + let qualifications = [(ClusterGenerationMode.pipeline, [32]), (.tensorParallel, [])].flatMap { mode, cuts in + [UInt8(1), 2].map { + ClusterRuntimeApprovalFacts.ParityQualification(schedule: $0, numericsClasses: classes, cuts: cuts, mode: mode, + promotable: true, diverged: false, evidenceSHA256: String(repeating: "f", count: 64), qualifiedAt: "2026-10-31T00:00:00Z", + requestEnvelope: ClusterPublicModels.requestEnvelope(inputModalities: ["text", "image", "video"], + servesMedia: mode == .tensorParallel)) + } } return try .init(nativeRuntimeSHA256: String(repeating: "1", count: 64), metallibSHA256: String(repeating: "2", count: 64), resourceLibrarySHA256: String(repeating: "3", count: 64), placementPolicySHA256: String(repeating: "4", count: 64), - models: [model("EigenLabs/Qwen3.8-27B-4bit-mtp", "5"), model("Qwen3.5-9B", "6"), model("glm-5.3-flash", "7")]) + models: [model("EigenLabs/Qwen3.8-27B-4bit-mtp", "5", grant: .init(evidenceSHA256: String(repeating: "f", count: 64), + modeFamilies: ["pipeline", "tensor_parallel"]), + qualifications: qualifications), + model("Qwen3.5-9B", "6", grant: .init(evidenceSHA256: String(repeating: "a", count: 64), + modeFamilies: ["hand_off", "pipeline", "pipeline_speculative", "tensor_parallel"])), + model("glm-5.3-flash", "7")]) + } + + /// A copy of `base` with fields of its JSON changed. + static func record(_ base: ClusterPairQualificationRecord, _ change: (inout [String: Any]) -> Void) throws -> ClusterPairQualificationRecord { + var object = try JSONSerialization.jsonObject(with: Data(base.encodedLine().utf8)) as! [String: Any] + change(&object) + return try JSONDecoder().decode(ClusterPairQualificationRecord.self, from: JSONSerialization.data(withJSONObject: object)) + } + + static func sha256(_ data: Data) -> String { + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } } @@ -229,17 +834,28 @@ private struct Fixture { try Data(workerSHA256.utf8).write(to: expected) } - static var metadataFixtures: URL { + /// The checkout's `provider-swift` folder. + static var providerSwift: URL { var root = URL(fileURLWithPath: #filePath).deletingLastPathComponent() while root.lastPathComponent != "provider-swift", root.path != "/" { root.deleteLastPathComponent() } - return root.deletingLastPathComponent().appendingPathComponent("libs/darkbloom-cluster-worker/Tests/CapabilityChecks/Fixtures") + return root + } + + static var repository: URL { providerSwift.deletingLastPathComponent() } + + static var providerTests: URL { providerSwift.appendingPathComponent("Tests/ProviderCoreTests") } + + static var metadataFixtures: URL { + repository.appendingPathComponent("libs/darkbloom-cluster-worker/Tests/CapabilityChecks/Fixtures") } /// One model folder: a pinned fixture's config.json and manifest.json (or /// replacements), and the capability the runtime catalog describes for them. - func model(_ name: String, fixture: String = "registered-qwen35-9b", capabilityFixture: String? = nil, - workerSHA256: String? = nil, imageCandidate: Bool = false, manifest: Data? = nil, modelID: String? = nil) throws -> URL { - let folder = root.appendingPathComponent("models", isDirectory: true).appendingPathComponent(name, isDirectory: true) + /// A release candidate (`parent`) also has its catalog entry (`catalog.json`). + func model(_ name: String, parent: URL? = nil, fixture: String = "registered-qwen35-9b", capabilityFixture: String? = nil, + workerSHA256: String? = nil, imageCandidate: Bool = false, manifest: Data? = nil, modelID: String? = nil, + refused: Bool = false, modalities: [String] = ["text"]) throws -> URL { + let folder = (parent ?? root.appendingPathComponent("models", isDirectory: true)).appendingPathComponent(name, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) func read(_ fixture: String, _ kind: String) throws -> Data { try Data(contentsOf: Self.metadataFixtures.appendingPathComponent("\(fixture).\(kind).json")) @@ -260,6 +876,11 @@ private struct Fixture { : ClusterResidentModelCatalog.describe(configuration: read(source, "configuration"), manifest: read(source, "manifest"), runtimeBinarySHA256: pin) try ClusterRuntimeCapabilityCodec.encode(capability).write(to: folder.appendingPathComponent("capability.out")) + if refused { try Data().write(to: folder.appendingPathComponent("refuse")) } + if parent != nil, let id = (try? JSONSerialization.jsonObject(with: manifestBytes) as? [String: Any])?["model_id"] as? String { + try JSONSerialization.data(withJSONObject: ["id": id, "input_modalities": modalities], options: [.sortedKeys]) + .write(to: folder.appendingPathComponent("catalog.json")) + } return folder } diff --git a/provider-swift/Tests/ProviderCoreTests/Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json b/provider-swift/Tests/ProviderCoreTests/Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json new file mode 100644 index 0000000000..6efc4b48de --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json @@ -0,0 +1 @@ +{"metallib_sha256":"98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be","models":[{"artifact_sha256":"3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac","capability_sha256":"2069ee1bf4e5f829203a252dfddf7ea365d322b76c33a662e384aaf7600fb462","model":"glm-5.3-flash","pair_serving_grant":{"evidence_sha256":"dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d","mode_families":["pipeline","tensor_parallel"]},"parity_qualifications":[{"cuts":[22],"diverged":false,"evidence_sha256":"dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d","mode":"pipeline_v1","numerics_classes":["g17d-nax1-mlx-98bab9d7-macos27.0","g17d-nax1-mlx-98bab9d7-macos27.0"],"promotable":true,"qualified_at":"2026-10-31T00:00:00Z","request_envelope":{"max_output_tokens":1048576,"max_prompt_tokens":1048576,"sampling":true,"tools":true,"video":false,"vision":false},"schedule":1,"tensor_parallel_shares":null},{"cuts":[22],"diverged":false,"evidence_sha256":"dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d","mode":"pipeline_v1","numerics_classes":["g17d-nax1-mlx-98bab9d7-macos27.0","g17d-nax1-mlx-98bab9d7-macos27.0"],"promotable":true,"qualified_at":"2026-10-31T00:00:00Z","request_envelope":{"max_output_tokens":1048576,"max_prompt_tokens":1048576,"sampling":true,"tools":true,"video":false,"vision":false},"schedule":2,"tensor_parallel_shares":null},{"cuts":[],"diverged":false,"evidence_sha256":"dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d","mode":"tensor_parallel_v1","numerics_classes":["g17d-nax1-mlx-98bab9d7-macos27.0","g17d-nax1-mlx-98bab9d7-macos27.0"],"promotable":true,"qualified_at":"2026-10-31T00:00:00Z","request_envelope":{"max_output_tokens":1048576,"max_prompt_tokens":1048576,"sampling":true,"tools":true,"video":true,"vision":true},"schedule":1,"tensor_parallel_shares":null},{"cuts":[],"diverged":false,"evidence_sha256":"dccbc68bd337f634be9295eed8f909702252eab707a4ac3fdb5290ce8b98a86d","mode":"tensor_parallel_v1","numerics_classes":["g17d-nax1-mlx-98bab9d7-macos27.0","g17d-nax1-mlx-98bab9d7-macos27.0"],"promotable":true,"qualified_at":"2026-10-31T00:00:00Z","request_envelope":{"max_output_tokens":1048576,"max_prompt_tokens":1048576,"sampling":true,"tools":true,"video":true,"vision":true},"schedule":2,"tensor_parallel_shares":null}],"profile_sha256":"432d5ddfcbcb7163f8fa99b95e5142581cd77ec9372109867a2748ff3cbff47a","resource_policy_sha256":"421e0bfec667f8e1aafdcdcd9955d2aec1342c2d999c73e33e39fd1415412598"}],"native_runtime_sha256":"c465b19a0e8965d19717bd91dd7a29d0113f38c476cfaf06ed8fe3cdc5c82550","placement_policy_sha256":"68eee21a3262465084dc197798c89e44c0c1aa4072e7aa84804a027d57025829","resource_library_sha256":"d99096e5c6fc2b0bb0be802a34986d90ff1287416cd57a360d0980ac2ce95a65","schema":"darkbloom_cluster_runtime_v2"} \ No newline at end of file diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift index fa28745c52..c8c7660c87 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift @@ -29,7 +29,15 @@ final class ClusterApprovalMacs: @unchecked Sendable { static let model = "fixture/qwen" static let chip = ClusterChipClass(chipName: "Apple M3 Ultra") + /// What both Macs' setups place: the Qwen3.5 9B pipeline, or Qwen3.8 27B in tensor parallel as the guided setup + /// saves it, with or without the model's embedded speculative assistant (`ClusterConfiguration.tensorAssistant`). + enum Shape { + case pipeline + case qwen27TensorParallel(assistant: ClusterQwenTensorAssistantPolicy?) + } + let root: URL + let shape: Shape /// The setups' capability: the installed build's (`readopt` saves the setups of a new build). private(set) var capability: ClusterRuntimeCapability private(set) var capabilitySHA256: String @@ -39,10 +47,11 @@ final class ClusterApprovalMacs: @unchecked Sendable { var follower: Mac { macs[1] } /// `coordinatorURL`: the coordinator both provider configurations name. - init(coordinatorURL: String) throws { + init(coordinatorURL: String, shape: Shape = .pipeline) throws { let base = try NativePairMemberFixture.privateRoot() root = base - let installed = try Self.capability(runtime: Self.hash("a")) + self.shape = shape + let installed = try Self.capability(runtime: Self.hash("a"), shape: shape) capability = installed capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(installed)) @@ -91,22 +100,35 @@ final class ClusterApprovalMacs: @unchecked Sendable { } /// The capability the worker of the build whose worker digest is `runtime` describes for the fixture model. - static func capability(runtime: String) throws -> ClusterRuntimeCapability { + static func capability(runtime: String, shape: Shape = .pipeline) throws -> ClusterRuntimeCapability { let h = Self.hash - let profile = ClusterWorkerProfile(id: "registered_qwen35_9b_greedy_generation_v1", vocabularySize: 248320, - maximumPromptTokens: 8192, maximumOutputTokens: 128, maximumChunkTokens: 512, maximumContextTokens: 8320) - return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, - runtimeModelID: "registered_qwen35_9b", artifactSHA256: h("b"), configurationSHA256: h("c"), manifestSHA256: h("d"), - profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ - .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 16, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), - .init(rank: 1, sourceLayerStart: 16, sourceLayerEnd: 32, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], - arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5")) + switch shape { + case .pipeline: + let profile = ClusterWorkerProfile(id: "registered_qwen35_9b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: 8192, maximumOutputTokens: 128, maximumChunkTokens: 512, maximumContextTokens: 8320) + return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, + runtimeModelID: "registered_qwen35_9b", artifactSHA256: h("b"), configurationSHA256: h("c"), manifestSHA256: h("d"), + profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 16, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), + .init(rank: 1, sourceLayerStart: 16, sourceLayerEnd: 32, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], + arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5")) + case .qwen27TensorParallel: + let profile = ClusterWorkerProfile(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, + maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536) + return try ClusterRuntimeCapability(runtimeBinarySHA256: runtime, adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, + runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, artifactSHA256: h("b"), configurationSHA256: h("c"), + manifestSHA256: h("d"), profile: profile, profileFingerprint: h("e"), partitions: [.init(planSHA256: h("f"), stages: [ + .init(rank: 0, sourceLayerStart: 0, sourceLayerEnd: 32, stagePlanSHA256: h("1"), constructionConfigurationSHA256: h("2")), + .init(rank: 1, sourceLayerStart: 32, sourceLayerEnd: 64, stagePlanSHA256: h("3"), constructionConfigurationSHA256: h("4"))])], + arithmeticPolicyID: "qwen_cbv2_query128_bf16_tf32_default_v1", arithmeticPolicySHA256: h("5"), + supportedGenerationModes: [.pipeline, .tensorParallel]) + } } /// What an update does to both Macs' setups (`ClusterService`, "set the cluster up again after the update"): the /// same model and placement re-adopted for the new build's worker `runtime`, with no cluster approval. func readopt(runtime: String) throws { - capability = try Self.capability(runtime: runtime) + capability = try Self.capability(runtime: runtime, shape: shape) capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)) try saveSetups() } @@ -122,7 +144,7 @@ final class ClusterApprovalMacs: @unchecked Sendable { "ownerExecutable": other.owner.path, "workerExecutable": other.worker.path, "modelDirectory": other.model.path, "runtimeBinarySHA256": capability.runtimeBinarySHA256, "jacclDevice": "rdma_en7"] } - let configuration: [String: Any] = ["schema": ClusterConfiguration.schemaName, "clusterID": record.clusterID, + var configuration: [String: Any] = ["schema": ClusterConfiguration.schemaName, "clusterID": record.clusterID, "memberID": mac.memberID, "role": mac.rank == 0 ? "leader" : "follower", "publicModelID": Self.model, "capabilitySHA256": capabilitySHA256, "selectedPlanSHA256": h("f"), "prefillSchedule": "serial_v1", "chunkTokens": 16, "requestTimeoutSeconds": 300, "peers": macs.map(peer), @@ -130,6 +152,10 @@ final class ClusterApprovalMacs: @unchecked Sendable { "linkControl": ["schema": ClusterLinkControlAttachment.schemaName, "port": 47999, "linkEpoch": record.link.linkEpoch, "edgeID": record.link.edgeID, "secretFile": secret.path], "tokenizerFiles": [["path": "tokenizer.json", "sha256": h("6"), "purpose": "tokenizer"]]] + if case .qwen27TensorParallel(let assistant) = shape { + configuration["generationMode"] = ClusterGenerationMode.tensorParallel.rawValue + if let assistant { configuration["tensorAssistant"] = assistant.object } + } let input = mac.scratch.appendingPathComponent("setup.json"), capabilityInput = mac.scratch.appendingPathComponent("capability.json") try JSONSerialization.data(withJSONObject: configuration, options: [.sortedKeys]).write(to: input) try capabilityData.write(to: capabilityInput) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalServiceStartTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalServiceStartTests.swift index ba010329e5..ed3c8218e1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalServiceStartTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalServiceStartTests.swift @@ -8,8 +8,11 @@ import Testing @Suite("Cluster approval at a service start", .serialized) struct ClusterApprovalServiceStartTests { /// The leader's setup saved with an approval ending `endsIn` seconds from now (in the past: ended): a cluster - /// approval as the guided setup saves it, or (`handSaved`) a pair approval an operator saved by hand. - private func setUp(endsIn: Double, handSaved: Bool = false) throws -> (ClusterApprovalMacs, ClusterService, URL) { + /// approval as the guided setup saves it, or (`handSaved`) a pair approval an operator saved by hand. `supervised`: + /// the service runs under its supervisor (its heartbeat file named in its environment) or not; nil: this process's + /// environment as it is. + private func setUp(endsIn: Double, handSaved: Bool = false, + supervised: Bool? = nil) throws -> (ClusterApprovalMacs, ClusterService, URL) { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") let leader = macs.leader, saved = try macs.saved(leader), facts = try macs.facts() let current = try ClusterApprovalAttachment.attachment(for: macs.approval(), saved: saved, paths: leader.paths, @@ -42,12 +45,20 @@ struct ClusterApprovalServiceStartTests { try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: helper.path) let parts = leader.home.appendingPathComponent("parts", isDirectory: true) try FileManager.default.createDirectory(at: parts, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + let environment = supervised.map { underSupervisor -> [String: String] in + let key = ClusterSupervisionFiles.healthPathEnvironmentKey + var environment = ProcessInfo.processInfo.environment + environment[key] = underSupervisor + ? ClusterServiceAgent.healthPath(serviceDirectory: ClusterSetupPaths(paths: leader.paths).directory).path : nil + return environment + } let wizard = ClusterSetupOperations.LiveSettings(providerConfiguration: leader.provider, darkbloomExecutable: helper, sessionArguments: [], pair: nil, dryRun: true, version: "fixture") let service = ClusterService(settings: .init(wizard: wizard, leaderArguments: ["--service-part-fixture", parts.path, "leader"], followerArguments: [], soloArguments: ["--service-part-fixture", parts.path, "replacement"], - memberArguments: ["--service-part-fixture", parts.path, "member"]), paths: leader.paths, recoveryGraceSeconds: 0.2) + memberArguments: ["--service-part-fixture", parts.path, "member"]), paths: leader.paths, recoveryGraceSeconds: 0.2, + environment: environment) var leadership = ClusterOnboardingLeadership(role: "leader", leaderPin: leader.pin, peerPin: macs.follower.pin, peerName: "fixture peer", since: "fixture") leadership.serving = true; leadership.modelName = ClusterApprovalMacs.model @@ -102,6 +113,46 @@ struct ClusterApprovalServiceStartTests { #expect(try macs.bytes(macs.leader) == before, "a current approval was rewritten") } + /// A supervised service beats into the file its supervisor names, and so does a coordinator-paired part (with its + /// own pid) when it inherits that name. The supervisor's liveness guard reads another pid's beat as no beat, so on + /// DevNet it restarted a healthy registered service every 15 minutes or so (the pair dropped each time). The part + /// beats into a file of its own, and still runs as a supervised member (the key stays set). + @Test func aSupervisedServicesMemberPartNeverBeatsIntoTheServicesHeartbeat() throws { + // The fixture removes both homes (and `parts`) when it ends: it is kept until the last check. + let (macs, service, parts) = try setUp(endsIn: 14 * 86_400, supervised: true) + withExtendedLifetime(macs) { + let (reached, lines) = run(service, parts: parts) { started(parts, "member") } + #expect(reached, "the member part did not start: \(lines)") + let directory = service.store.paths.directory + #expect(heartbeatFiles(parts, "member") == [ClusterServiceAgent.partHealthPath(serviceDirectory: directory).path], + "the part must beat into its own file, never \(ClusterServiceAgent.healthPath(serviceDirectory: directory).path)") + } + } + + @Test func anUnsupervisedServicesMemberPartIsToldOfNoHeartbeatFile() throws { + let (macs, service, parts) = try setUp(endsIn: 14 * 86_400, supervised: false) + withExtendedLifetime(macs) { + let (reached, lines) = run(service, parts: parts) { started(parts, "member") } + #expect(reached, "the member part did not start: \(lines)") + #expect(heartbeatFiles(parts, "member").isEmpty) + } + } + + /// An empty name is no supervisor to the service and to its part alike: it stays empty, never a part's file. + @Test func anEmptyHeartbeatNameIsPassedOnEmpty() { + let key = ClusterSupervisionFiles.healthPathEnvironmentKey + let environment = ClusterService.partEnvironment([key: "", "HOME": "/fixture"], + serviceDirectory: URL(fileURLWithPath: "/fixture/.darkbloom/cluster-setup")) + #expect(environment == [key: "", "HOME": "/fixture"]) + } + + /// The heartbeat files the parts of `role` were told of (the fixture records its environment's). + private func heartbeatFiles(_ parts: URL, _ role: String) -> [String] { + ((try? FileManager.default.contentsOfDirectory(atPath: parts.path)) ?? []) + .filter { $0.hasPrefix(role + "-") && $0.hasSuffix(".health") } + .compactMap { try? String(contentsOf: parts.appendingPathComponent($0), encoding: .utf8) } + } + @Test func aHandSavedPairApprovalThatEndedStaysSavedAndIsNeverOffered() throws { let (macs, service, parts) = try setUp(endsIn: -60, handSaved: true) let before = try macs.bytes(macs.leader) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift new file mode 100644 index 0000000000..5964fb7a8a --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalTensorAssistantTests.swift @@ -0,0 +1,74 @@ +import Foundation +import Testing +import DarkbloomClusterProtocol +@testable import ProviderCore + +/// A Qwen3.8 27B tensor-parallel pair and the coordinator's cluster approval, with each Mac's real configuration +/// store, pairing store and installed files (`ClusterApprovalMacs`). The model's embedded speculative assistant +/// (`ClusterConfiguration.tensorAssistant`) has no public qualification and serves local clusters only, so a setup +/// saved for coordinator pairing carries none: a pair planned without it is saved on both Macs, and a setup with it is +/// refused by the leader's own check, before any part stops and before anything reaches the other Mac. +@Suite("Cluster approval and the Qwen tensor assistant", .serialized) +struct ClusterApprovalTensorAssistantTests { + static func assistant() throws -> ClusterQwenTensorAssistantPolicy { + try ClusterQwenTensorAssistantPolicy(depth: 3, inventorySHA256: ClusterApprovalMacs.hash("8"), verification: .admittedCohort) + } + + static let refusedHere = "Not offered for pairing: this Mac's check refused it: " + + @Test func aQwenTensorParallelPairWithoutTheAssistantIsSavedOnBothMacs() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", shape: .qwen27TensorParallel(assistant: nil)) + let approval = macs.approval(), facts = try macs.facts() + let result = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts) + #expect(result == .init(changed: true, line: ClusterApprovalLifetime.offeredLine(approval), note: .some(nil))) + for mac in macs.macs { + let saved = try macs.saved(mac).configuration + #expect(saved.nativeMember?.clusterApproval == approval, "rank \(mac.rank) saved no approval") + #expect(saved.selectedGenerationMode == .tensorParallel && saved.tensorAssistant == nil, "rank \(mac.rank)") + } + } + + @Test func theLeaderRefusesATensorAssistantSetupBeforeAnyPartStops() throws { + let policy = try Self.assistant() + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", shape: .qwen27TensorParallel(assistant: policy)) + for mac in macs.macs { #expect(try macs.saved(mac).configuration.tensorAssistant == policy, "rank \(mac.rank)") } + let approval = macs.approval(), facts = try macs.facts(), before = try macs.macs.map(macs.bytes) + let sent = ClusterApprovalRecorder() + var stops = 0, serves = 0 + // The control leader's minute check (`ClusterService.checkApproval`): no part stops, nothing is sent to the + // other Mac, nothing starts again, and the reason is the status note. + let checked = ClusterApprovalSync.apply(.save(approval), grace: 600, paths: macs.leader.paths, + providerConfiguration: macs.leader.provider, pairingStore: macs.leader.pairing, scratch: macs.leader.scratch, + now: Date().timeIntervalSince1970, stop: { stops += 1; return nil }, serve: { serves += 1 }, + sendToPeer: macs.cable(facts: facts, sent: sent), chipClass: ClusterApprovalMacs.chip, facts: { _ in facts }) + #expect(stops == 0 && serves == 0 && sent.values.isEmpty, "stops \(stops), serves \(serves), sent \(sent.values.map(\.op))") + #expect(!checked.changed && checked.line?.hasPrefix(Self.refusedHere) == true, "\(checked.line ?? "")") + #expect(checked.line == Self.refusedHere + ClusterConfiguration.tensorAssistantServesLocally) + #expect(checked.note == .some(checked.line)) + #expect(try macs.macs.map(macs.bytes) == before) + // The registration after the guided setup's Test stage (`OnboardingLive.localRegister`, `run`): this Mac's own + // check refuses it too, so nothing reaches the other Mac. + let registered = macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts, sent: sent) + #expect(!registered.changed && sent.values.isEmpty, "sent \(sent.values.map(\.op))") + #expect(registered.line?.hasPrefix(Self.refusedHere) == true, "\(registered.line ?? "")") + #expect(try macs.macs.map(macs.bytes) == before) + } + + /// The other Mac checks the same rule itself before it saves anything, so a leader of an earlier build that sends + /// the approval anyway gets the reason in plain words, and the other Mac's setup stays as it was. + @Test func theOtherMacRefusesATensorAssistantSetupWithThePlainReason() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider", + shape: .qwen27TensorParallel(assistant: try Self.assistant())) + let before = try macs.bytes(macs.follower) + var command = ClusterServiceCommand(op: .approval) + command.approval = macs.approval() + command.approvalEdge = ClusterEdge(peerPin: macs.leader.pin, transport: "rdma", measuredMbps: 1, measuredRTTMicros: 1) + let refused = #expect(throws: (any Error).self) { try macs.cable(facts: try macs.facts())(command) } + let reason = refused.map(ClusterApprovalSync.refusal) ?? "" + #expect(reason.hasSuffix(ClusterApprovalSync.peerRefusalPrefix + ClusterConfiguration.tensorAssistantServesLocally), "\(reason)") + #expect(try macs.bytes(macs.follower) == before) + // The same setup without an approval (the leader serving locally) is saved as it is: nothing to refuse. + try macs.cable(facts: try macs.facts())(ClusterServiceCommand(op: .approval)) + #expect(try macs.bytes(macs.follower) == before) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift index 12befc1dd2..d2aa09f109 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift @@ -27,11 +27,12 @@ struct ClusterApprovalWatchTests { private func step(_ macs: ClusterApprovalMacs, _ fetched: ClusterApprovalFetch.Outcome, setAside: ClusterSetupRecord.ApprovalSetAside? = nil, quickEnds: Int = 0, peer: String?? = nil, - scope: ClusterServingScope = .publicServing, _ watched: Watched, clock: Double) throws -> ClusterApprovalCheck.Step { + scope: ClusterServingScope = .publicServing, _ watched: Watched, clock: Double, + now: Double = Date().timeIntervalSince1970) throws -> ClusterApprovalCheck.Step { let facts = try macs.facts() return ClusterApprovalCheck.step(saved: try macs.saved(macs.leader), fetched: fetched, setAside: setAside, scope: scope, memberQuickEnds: quickEnds, peerApprovalID: peer, watch: &watched.watch, clock: clock, - grace: grace, now: Date().timeIntervalSince1970, facts: { _ in facts }) + grace: grace, now: now, facts: { _ in facts }) } /// The other Mac's saved cluster approval ID, as its status reports it. @@ -158,7 +159,7 @@ struct ClusterApprovalWatchTests { #expect(try step(macs, noAnswer, quickEnds: limit, watch, clock: 0) == .serveLocally(approval, .failing)) _ = serveLocally(macs, approval, facts: facts, reason: .failing) - let failing = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing) + let failing = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing, setAt: Date().timeIntervalSince1970) #expect(try step(macs, .approvals([approval]), setAside: failing, watch, clock: 0) == .keep) let later = macs.approval(endsIn: 20 * 86_400, id: "later") #expect(try step(macs, .approvals([approval, later]), setAside: failing, watch, clock: 0) == .save(later)) @@ -173,8 +174,8 @@ struct ClusterApprovalWatchTests { } /// A model approval names no build and keeps its `id` across updates: its parts failing on one build set it aside - /// for that build only, so the build an update installs takes it again. A record from an older build, which names - /// no build, keeps it aside by its `id`. + /// for that build only, so the build an update installs takes it again. A record from an older build names neither + /// the build nor the time it was set aside: it is past the hour, so any build takes the approval again. @Test func aModelApprovalSetAsideAsFailingIsTakenAgainByTheNextBuild() throws { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") let model = macs.modelApproval(), facts = try macs.facts(), watch = Watched() @@ -183,21 +184,124 @@ struct ClusterApprovalWatchTests { #expect(try step(macs, .approvals([model]), quickEnds: limit, watch, clock: 0) == .serveLocally(model, .failing)) #expect(serveLocally(macs, model, facts: facts, reason: .failing).changed) let failing = ClusterSetupRecord.ApprovalSetAside(approval: model, reason: .failing, - runtimeBinarySHA256: try macs.saved(macs.leader).capability.runtimeBinarySHA256) + runtimeBinarySHA256: try macs.saved(macs.leader).capability.runtimeBinarySHA256, setAt: Date().timeIntervalSince1970) // The build its parts kept failing on does not take it again. #expect(try step(macs, .approvals([model]), setAside: failing, watch, clock: 0) == .keep) - // A record saved by an older build reads without the field. + // A record saved by an older build reads without the fields it did not write. var object = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(failing)) as? [String: Any]) let removed = object.removeValue(forKey: "runtimeBinarySHA256") as? String #expect(removed == failing.runtimeBinarySHA256) + let removedTime = object.removeValue(forKey: "setAt") as? Double + #expect(removedTime == failing.setAt) let older = try JSONDecoder().decode(ClusterSetupRecord.ApprovalSetAside.self, from: JSONSerialization.data(withJSONObject: object)) #expect(older == ClusterSetupRecord.ApprovalSetAside(approval: model, reason: .failing)) + #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .save(model)) // An update re-adopts both setups for a new worker: the new build takes the same model approval again. try macs.readopt(runtime: ClusterApprovalMacs.hash("9")) #expect(try step(macs, .approvals([model]), setAside: failing, watch, clock: 0) == .save(model)) - #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .keep) + #expect(try step(macs, .approvals([model]), setAside: older, watch, clock: 0) == .save(model)) + } + + /// Ends the coordinator decides are not the pair's failures: a registration it did not accept in its negotiation + /// window (during a deploy, right after a restart, or when it is slow; twice within three minutes during an e2e + /// model change) leaves the count of quick ends as it is. Read from the parts' own log lines, as the cluster service + /// reads them, any number of them never sets the approval aside. + @Test func coordinatorSideEndsDoNotReachTheFailingLimit() throws { + let (macs, approval, _) = try offered() + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("rank-log-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let log = folder.appendingPathComponent("rank.log") + #expect(FileManager.default.createFile(atPath: log.path, contents: nil)) + let notAccepted = ClusterMemberControlError.negotiationFailed.rawValue + var count = 0 + for ran in [13.0, 12, 40, 3, 90] { + // Each part writes after where the one before it stopped. + let handle = try FileHandle(forWritingTo: log) + let offset = try handle.seekToEnd() + try handle.write(contentsOf: Data("cluster-member pair serving: follower (dials the leader)\nError: \(notAccepted)\n".utf8)) + try handle.close() + count = ClusterApprovalCheck.memberQuickEnds(after: count, ranSeconds: ran, lastError: ClusterService.lastError(in: log, from: offset)) + } + #expect(count == 0) + #expect(try step(macs, .approvals([approval]), quickEnds: count, Watched(), clock: 0) == .keep) + // Between local quick ends it neither adds one nor starts the count again; a part that ran long before the + // coordinator ended it still starts it again, as any long run does. + #expect(ClusterApprovalCheck.memberQuickEnds(after: 2, ranSeconds: 12, lastError: notAccepted) == 2) + #expect(ClusterApprovalCheck.memberQuickEnds(after: 2, ranSeconds: ClusterControlSoloAdmission.quickEndSeconds, + lastError: notAccepted) == 0) + } + + /// Ends with a local cause still count, with ends the coordinator decided between them: a changed input (the DevNet + /// trigger), a crash that wrote no error line and a member that ended before it registered set the approval aside. + @Test func localQuickEndsStillSetTheApprovalAside() throws { + let (macs, approval, _) = try offered() + let notAccepted = ClusterMemberControlError.negotiationFailed.rawValue + let ends: [String?] = ["Installed input identity or SHA-256 differs", notAccepted, nil, notAccepted, + ClusterMemberControlError.connectionEnded.rawValue] + var count = 0, counts: [Int] = [] + for lastError in ends { + count = ClusterApprovalCheck.memberQuickEnds(after: count, ranSeconds: 8, lastError: lastError) + counts.append(count) + } + #expect(counts == [1, 1, 2, 2, ClusterControlSoloAdmission.maximumQuickEnds]) + #expect(try step(macs, .approvals([approval]), quickEnds: count, Watched(), clock: 0) == .serveLocally(approval, .failing)) + } + + /// An approval set aside as failing is offered again, by the same build, `ClusterApprovalFallback.failingSeconds` + /// after the cluster service set it aside (a later matching one at once, as before). Each Mac's part that served + /// locally meanwhile started its count of quick ends again, so the pair is offered with none. + @Test func aFailingApprovalIsOfferedAgainAnHourAfterItWasSetAside() throws { + let (macs, approval, facts) = try offered() + let watch = Watched(), limit = ClusterControlSoloAdmission.maximumQuickEnds, hour = ClusterApprovalFallback.failingSeconds + let fallback = ClusterApprovalCheck.Step.serveLocally(approval, .failing) + #expect(try step(macs, .approvals([approval]), quickEnds: limit, watch, clock: 0) == fallback) + #expect(serveLocally(macs, approval, facts: facts, reason: .failing).changed) + let worker = try macs.saved(macs.leader).capability.runtimeBinarySHA256, now = Date().timeIntervalSince1970 + func setAside(at time: Double) throws -> ClusterSetupRecord.ApprovalSetAside { + try #require(ClusterApprovalCheck.setAside(by: fallback, worker: worker, now: time)) + } + // What the cluster service keeps: the approval, why, the setup's worker digest and when. + #expect(try setAside(at: now) == .init(approval: approval, reason: .failing, runtimeBinarySHA256: worker, setAt: now)) + #expect(ClusterApprovalCheck.setAside(by: .save(approval), worker: worker, now: now) == nil) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now), watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now - hour + 60), watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now - hour), watch, clock: 0, now: now) == .save(approval)) + // A time ahead of a clock that was set back holds it aside no longer either. + #expect(try step(macs, .approvals([approval]), setAside: setAside(at: now + 600), watch, clock: 0, now: now) == .save(approval)) + #expect(ClusterApprovalFallback.failing.line(approval, grace: grace).hasSuffix( + "the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists")) + + // Saved on both Macs again, the pair is offered and stays offered while its parts' new count is under the limit. + #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed) + #expect(try step(macs, .approvals([approval]), quickEnds: 0, watch, clock: 0, now: now) == .keep) + #expect(try step(macs, .approvals([approval]), quickEnds: limit, watch, clock: 0, now: now) == fallback) + } + + /// The leader's record as the current build writes it (the set-aside names its approval, reason and worker digest, + /// no time) reads cleanly with every field kept, and is past the hour: the approval is offered again. A set-aside + /// this build writes keeps its time through the store. + @Test func aSetAsideInTheCurrentRecordFormatReadsCleanlyAndIsPastTheHour() throws { + let (macs, approval, facts) = try offered() + #expect(serveLocally(macs, approval, facts: facts, reason: .failing).changed) + let worker = try macs.saved(macs.leader).capability.runtimeBinarySHA256, now = Date().timeIntervalSince1970 + let store = ClusterSetupStore(paths: ClusterSetupPaths(paths: macs.leader.paths)) + let note = ClusterApprovalFallback.failing.line(approval, grace: grace) + let current = ClusterSetupRecord.ApprovalSetAside(approval: approval, reason: .failing, runtimeBinarySHA256: worker) + try store.updateRecord { $0.approvalNote = note; $0.approvalSetAside = current } + let written = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: store.paths.record)) as? [String: Any]) + let keys = try #require(written["approvalSetAside"] as? [String: Any]).keys.sorted() + #expect(keys == ["approval", "reason", "runtimeBinarySHA256"]) + let read = try store.readRecord() + #expect(read.approvalSetAside == current && read.approvalSetAside?.setAt == nil && read.approvalNote == note) + #expect(try step(macs, .approvals([approval]), setAside: read.approvalSetAside, Watched(), clock: 0, now: now) == .save(approval)) + + let dated = try #require(ClusterApprovalCheck.setAside(by: .serveLocally(approval, .failing), worker: worker, now: now)) + try store.updateRecord { $0.approvalSetAside = dated } + #expect(try store.readRecord().approvalSetAside?.setAt == now) + #expect(try step(macs, .approvals([approval]), setAside: store.readRecord().approvalSetAside, Watched(), clock: 0, now: now) == .keep) } @Test func aClusterThatServesLocallyOnlyNeverAsksTheCoordinatorAndChangesNothing() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift index 32d5d75070..0f2ff762e8 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterOwnerServingTests.swift @@ -65,16 +65,77 @@ import DarkbloomClusterProcess == "not yet qualified for public traffic") } + /// A model the owner declared public (`ClusterPublicModels`) is qualified for public traffic in its declared families, + /// pipeline and tensor parallel, with or without a record of them: GLM-5.3-Flash has only a pipeline record and + /// Qwen3.8-27B none here. Only the declared families and artifact: another mode family, another artifact or an + /// undeclared model is not. + @Test func aDeclaredModelIsQualifiedInItsDeclaredFamiliesWithoutARecordOfThem() throws { + let glm = "registered_glm53_flash", q27 = "registered_qwen38_27b" + let pipelineOnly = ClusterPairServingDecisions(records: [record(glm, ["Apple M3 Ultra", "Apple M5 Max"], cuts: [39])]) + let none = ClusterPairServingDecisions(records: []) + func qualified(_ families: String) -> String { + "qualified for public traffic in \(families) mode (the coordinator's parity qualification decides each placement)" + } + for (model, decisions) in [(glm, pipelineOnly), (q27, none)] { + let declared = ClusterPublicModels.declared.first { $0.runtimeModelID == model }! + for (mode, family) in [(ClusterGenerationMode.pipeline, "pipeline"), (.tensorParallel, "tensor parallel")] { + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, mode: mode, decisions: decisions) == qualified(family)) + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, artifactSHA256: declared.artifactSHA256, + mode: mode, decisions: decisions) == qualified(family)) + // Another artifact of the model is not what was declared, and no record ran it. + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, artifactSHA256: String(repeating: "e", count: 64), + mode: mode, decisions: decisions) == ClusterPairOwnerServing.notYetQualified) + } + // A family the owner did not declare and no record passed. + for mode in [ClusterGenerationMode.pipelineMTP, .phaseSplit] { + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, mode: mode, decisions: decisions) + == ClusterPairOwnerServing.notYetQualified, "\(model) \(mode.rawValue)") + } + // Without the declaration, the records alone decide: no tensor-parallel record here. + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, mode: .tensorParallel, decisions: decisions, + publicModels: []) == ClusterPairOwnerServing.notYetQualified) + let owner = try ClusterPairServingGrants.ownerServing(runtimeModelID: model, publicModelID: "p", decisions: decisions) + #expect(owner.declaredFamilies == [.pipeline, .tensorParallel]) + #expect(owner.publicTrafficLine == qualified("pipeline and tensor parallel")) + } + // GLM's pipeline record qualifies its pipeline without the declaration; the 27B has none. + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: glm, mode: .pipeline, decisions: pipelineOnly, publicModels: []) + == qualified("pipeline")) + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: q27, mode: .pipeline, decisions: none, publicModels: []) + == ClusterPairOwnerServing.notYetQualified) + // An undeclared model is unchanged. + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: "registered_qwen35_9b", mode: .tensorParallel, decisions: none) + == ClusterPairOwnerServing.notYetQualified) + } + + /// A placement that decodes with Qwen's speculative assistant is never said to be qualified for public traffic: + /// the assistant serves local clusters only, so its setup is never offered to the coordinator. Without it, the + /// same model and mode are qualified as before; a model or mode that is not qualified says so either way. + @Test func aPlacementThatDecodesWithTheAssistantIsNotOfferedForPublicTraffic() { + let q27 = ClusterPublicModels.declared.first { $0.runtimeModelID == "registered_qwen38_27b" }! + let none = ClusterPairServingDecisions(records: []) + func line(_ mode: ClusterGenerationMode, assistant: Bool, model: String = q27.runtimeModelID) -> String { + ClusterPairServingGrants.publicTrafficLine(runtimeModelID: model, artifactSHA256: model == q27.runtimeModelID ? q27.artifactSHA256 : nil, + mode: mode, tensorAssistant: assistant, decisions: none) + } + #expect(line(.tensorParallel, assistant: false).hasPrefix("qualified for public traffic in tensor parallel mode")) + #expect(line(.tensorParallel, assistant: true) == ClusterPairOwnerServing.tensorAssistantNotOffered) + #expect(ClusterPairOwnerServing.tensorAssistantNotOffered.hasPrefix("not offered for public traffic")) + #expect(line(.pipelineMTP, assistant: true) == ClusterPairOwnerServing.notYetQualified) + #expect(line(.tensorParallel, assistant: true, model: "registered_qwen35_9b") == ClusterPairOwnerServing.notYetQualified) + } + /// With a passing pipeline record the pipeline family is qualified for public traffic, tensor parallel is not; both - /// are served for the owner. + /// are served for the owner. (Records only: no model is declared public here.) @Test func publicTrafficFollowsThePassingRecordsOnly() throws { let decisions = ClusterPairServingDecisions(records: [record("registered_qwen38_27b", ["Apple M3 Ultra", "Apple M5 Ultra"], cuts: [8])]) - let owner = try ClusterPairServingGrants.ownerServing(runtimeModelID: "registered_qwen38_27b", publicModelID: "p", decisions: decisions) + let owner = try ClusterPairServingGrants.ownerServing(runtimeModelID: "registered_qwen38_27b", publicModelID: "p", decisions: decisions, + publicModels: []) #expect(owner.publicGrant?.families == [.pipeline]) - #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: "registered_qwen38_27b", mode: .pipeline, decisions: decisions) - .hasPrefix("qualified for public traffic")) - #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: "registered_qwen38_27b", mode: .tensorParallel, decisions: decisions) - == "not yet qualified for public traffic") + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: "registered_qwen38_27b", mode: .pipeline, decisions: decisions, + publicModels: []).hasPrefix("qualified for public traffic")) + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: "registered_qwen38_27b", mode: .tensorParallel, decisions: decisions, + publicModels: []) == "not yet qualified for public traffic") #expect(ownerServes([m4max, m4max], "registered_qwen38_27b", cuts: [], mode: .tensorParallel, decisions)) #expect(ownerServes([m4max, cls("Apple M5 Pro")], "registered_qwen38_27b", cuts: [40], decisions)) } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPairServingDecisionsTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPairServingDecisionsTests.swift index 2c800fc72a..59fdc3d4c3 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPairServingDecisionsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterPairServingDecisionsTests.swift @@ -154,7 +154,8 @@ import DarkbloomClusterProtocol // A phase-split pass qualifies no pipeline for public traffic; the owner is served as a pipeline all the same. #expect(publicFamilies(handoff, decisions) == [.handOff]) #expect(allows([m3, m5u], handoff, decisions, mode: .phaseSplitMTP) && allows([m3, m5u], handoff, decisions, mode: .pipeline)) - #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoff, mode: .pipeline, decisions: decisions) + // (Records only: the owner's declaration of the 27B is ClusterOwnerServingTests'.) + #expect(ClusterPairServingGrants.publicTrafficLine(runtimeModelID: handoff, mode: .pipeline, decisions: decisions, publicModels: []) == ClusterPairOwnerServing.notYetQualified) // Without the mode a placement is refused, whatever the records. do { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift index b69b82102d..f4f253479c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/DistributedAutomaticBatchPlannerTests.swift @@ -44,11 +44,14 @@ final class DistributedAutomaticBatchPlannerTests { return p } - private func fixture() throws -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementBatchScope) { - let model = "registered_qwen38_27b" + /// `artifact`: the artifact digest every record names (default a constructed one; the registered digest makes the + /// model one its owner declared public, `ClusterPublicModels`). + private func fixture(artifact: String? = nil) throws + -> (ClusterPairDescription, ClusterRuntimeCapability, ClusterModelLayout, ClusterPlacementBatchScope) { + let model = "registered_qwen38_27b", artifact = artifact ?? hash("b") let part = ClusterModelLayout.Part(storedBytes: 2 * gib, loadedBytes: 2 * gib, largestTensorBytes: gib / 4, tensorCount: 16) let end = ClusterModelLayout.Part(storedBytes: gib / 2, loadedBytes: gib / 2, largestTensorBytes: gib / 2, tensorCount: 1) - let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + let raw = ClusterModelLayout(runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), layers: (0..<2).map { .init(index: $0, kind: "fixture", weights: part, stateFixedBytes: 1024, stateBytesPerToken: 1024, cost: 1) }, ingress: end, egress: end, excluded: .init(), admittedCuts: [1], structuralCuts: [1], generationModes: [.pipeline, .tensorParallel], prefillSchedules: [.serial], @@ -62,7 +65,7 @@ final class DistributedAutomaticBatchPlannerTests { object["tensorParallel"] = try JSONSerialization.jsonObject(with: JSONEncoder().encode(tensor)) let layout = try ClusterModelLayout.decode(JSONSerialization.data(withJSONObject: object)) let cap = try ClusterRuntimeCapability(runtimeBinarySHA256: hash("a"), adapterID: "qwen35-dense-layer-stage", adapterVersion: 1, - runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), manifestSHA256: hash("d"), + runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), manifestSHA256: hash("d"), profile: .init(id: "registered_qwen38_27b_greedy_generation_v1", vocabularySize: 248320, maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumChunkTokens: 512, maximumContextTokens: 65536), profileFingerprint: hash("e"), partitions: [.init(planSHA256: hash("f"), stages: [ @@ -79,7 +82,7 @@ final class DistributedAutomaticBatchPlannerTests { linkSecretFile: "/fixture/\(id).secret") }, tokenizerFiles: [.init(path: "tokenizer.json", sha256: hash("6"), purpose: .tokenizer)], linkControl: .init(port: 5578, linkEpoch: UUID().uuidString.lowercased(), edgeID: UUID().uuidString.lowercased())) - let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: hash("b"), configurationSHA256: hash("c"), + let request = try ClusterPlacementRequestScope(runtimeModelID: model, artifactSHA256: artifact, configurationSHA256: hash("c"), promptTokens: 1024, outputTokens: 128, maximumPromptTokens: 32768, maximumOutputTokens: 32768, maximumContextTokens: 65536, requestChargeEveryRankBytes: gib) let quote = try ClusterPlacementTensorBatchQuote(request: request, lanes: 4, chunkTokens: 128, @@ -721,7 +724,8 @@ final class DistributedAutomaticBatchPlannerTests { try ClusterModelFeaturePolicy.requireReady(valid, identity: id, profile: profile) } - @Test func automaticAssistantUsesVerifiedInlineArtifactAndRespectsDisabledModes() throws { + /// A catalog folder whose artifact declares and ships an inline speculative head (one tensor), with its manifest. + private func inlineAssistantArtifact() throws -> (directory: URL, modelID: String, aggregate: String, manifest: Data) { let directory = try home(), modelID = "fixture-inline-qwen" let header = try JSONSerialization.data(withJSONObject: ["mtp.weight": ["dtype": "F32", "shape": [1], "data_offsets": [0, 4]]]) var length = UInt64(header.count).littleEndian @@ -738,6 +742,11 @@ final class DistributedAutomaticBatchPlannerTests { "aggregate_sha256": aggregate, "total_size_bytes": shard.count, "files": [["path": files[0].path, "size_bytes": files[0].sizeBytes, "sha256": files[0].sha256]]]) try manifest.write(to: directory.appendingPathComponent("manifest.json")) + return (directory, modelID, aggregate, manifest) + } + + @Test func automaticAssistantUsesVerifiedInlineArtifactAndRespectsDisabledModes() throws { + let (directory, modelID, aggregate, manifest) = try inlineAssistantArtifact() func candidate(_ mode: MTPMode, id: String? = nil, digest: String? = nil, environment: [String: String] = [:]) throws -> Bool { try ClusterPlacementTensorAssistantSelection.automaticCandidate(mode: mode, @@ -759,6 +768,26 @@ final class DistributedAutomaticBatchPlannerTests { #expect(!disabledMalformed) } + /// Which plans ask for Qwen's speculative assistant (`discoveryMode`): under the default `auto`, a cluster that + /// serves locally only, as before, and never one served through the coordinator, whose setup may not carry it; + /// an explicit `on` in either case; never `off`. + @Test func aClusterServedThroughTheCoordinatorAsksForTheAssistantOnlyUnderAnExplicitOn() throws { + let artifact = try inlineAssistantArtifact() + func asks(_ configured: MTPMode, coordinator: Bool) throws -> Bool { + try ClusterPlacementTensorAssistantSelection.automaticCandidate( + mode: ClusterPlacementTensorAssistantSelection.discoveryMode(configured, coordinator: coordinator), + runtimeModelID: ClusterQwenTensorAssistantPolicy.runtimeModelID, modelDirectory: artifact.directory, + publicModelID: artifact.modelID, artifactSHA256: artifact.aggregate, + manifestSHA256: ClusterConfigurationCodec.sha256(artifact.manifest), environment: [:]) + } + #expect(try asks(.auto, coordinator: false)) + #expect(try !asks(.auto, coordinator: true)) + #expect(try asks(.on, coordinator: false) && asks(.on, coordinator: true)) + #expect(try !asks(.off, coordinator: false) && !asks(.off, coordinator: true)) + #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: true) == .off) + #expect(ClusterPlacementTensorAssistantSelection.discoveryMode(.auto, coordinator: false) == .auto) + } + @Test func automaticQuotePinsNativeInventoryAndCompleteWidthOneScope() throws { let (_, cap, _, _) = try fixture() func quote(_ verification: ClusterQwenTensorAssistantPolicy.Verification = .admittedCohort, @@ -796,9 +825,11 @@ final class DistributedAutomaticBatchPlannerTests { #expect(!plainArgs.contains("--mtp-depth") && plainArgs.contains("--batch-lanes")) } + /// `assistant` false: the same request's ordinary target quote, as discovery reads it without the assistant. private func assistantQuote(_ lanes: Int, depth: Int = ClusterPlacementTensorAssistantSelection.automaticDepth, - verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton) throws -> ClusterPlacementTensorBatchQuote { - let (_, _, _, scope) = try fixture() + verification: ClusterQwenTensorAssistantPolicy.Verification = .singleton, + artifact: String? = nil, assistant: Bool = true) throws -> ClusterPlacementTensorBatchQuote { + let (_, _, _, scope) = try fixture(artifact: artifact) return try .init(request: scope.request, lanes: lanes, chunkTokens: 128, perLaneStateBytes: gib, sharedBytesExcludingCollectives: 2 * gib, allowance: .init(maximumContextTokens: 65536, maximumChunkTokens: 512, @@ -806,8 +837,8 @@ final class DistributedAutomaticBatchPlannerTests { maximumCollectivePayloadBytes: max(512 * 4096, lanes * 248320 * 4), maximumCollectiveFrameBytes: max(512 * 4096, lanes * 248320 * 4) + 1024, allocationBound: { (($0 + 16383) / 16384) * 16384 }), - assistant: .init(policy: .init(depth: depth, inventorySHA256: hash("8"), verification: verification), - residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib)) + assistant: assistant ? ClusterPlacementTensorAssistantQuote(policy: .init(depth: depth, inventorySHA256: hash("8"), + verification: verification), residentBytes: gib, loadBytes: 2 * gib, largestAllocationBytes: gib) : nil) } @Test func wideningQuoteSteersTheRetainedSplitTowardOneThatCanWiden() throws { @@ -897,6 +928,47 @@ final class DistributedAutomaticBatchPlannerTests { #expect(kept.quote == fits && kept.decision.result.chosen != nil) } + /// The onboarding's public-traffic line (`ClusterSetupPlanning.decide`, `publicTraffic`) for Qwen3.8 27B, whose + /// owner declared tensor parallel public (`ClusterPublicModels`): a plan without the speculative assistant is + /// qualified; a plan that decodes with it is not said to be, since a setup saved for coordinator pairing carries + /// no assistant (`ClusterConfiguration.validate`). + @Test func onlyAPlanWithoutTheAssistantSaysItIsQualifiedForPublicTraffic() throws { + let home = try home(); record(home) + let artifact = try #require(ClusterPublicModels.declared.first { + $0.runtimeModelID == ClusterQwenTensorAssistantPolicy.runtimeModelID }).artifactSHA256 + let (pair, cap, layout, _) = try fixture(artifact: artifact) + let data = try ClusterRuntimeCapabilityCodec.encode(cap), digest = ClusterConfigurationCodec.sha256(data) + let model = ClusterSetupLocalModel(folder: "Qwen3.8-27B-4bit-mtp-fixture", modelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", + version: "fixture", artifactSHA256: artifact, totalBytes: 16_320_415_757) + let link = try #require(ClusterLinkProbeHistory.costs(homeDirectory: home, members: ["a", "b"])) + let local = try profile(), peer = try profile() + func plan(_ quote: ClusterPlacementTensorBatchQuote) throws -> (line: String?, explanation: [String], setup: ClusterConfiguration) { + let reading = ClusterSetupPlanning.ModelReading(model: model, layout: .success(layout), + capability: .success((cap, data, digest)), tokenizerFiles: pair.tokenizerFiles, tensorAssistantQuote: .success(quote)) + let decided = try #require(onLargeStack { + ClusterSetupPlanning.decide(readings: [reading], description: pair, localMemberID: "a", + localProfile: local, peerProfile: peer, peerModels: [model], measurements: [], link: link) + }.first) + let summary = try #require(decided.option.plan, "not offered: \(decided.option.blocker ?? "")") + let bytes = try #require(decided.setup?.configurations["a"]) + return (summary.publicTraffic, summary.explanation, + try ClusterConfigurationCodec.decode(bytes, capability: cap, capabilitySHA256: digest)) + } + let target = try plan(try assistantQuote(1, artifact: artifact, assistant: false)) + #expect(target.setup.selectedGenerationMode == .tensorParallel && target.setup.tensorAssistant == nil) + #expect(target.line?.hasPrefix("qualified for public traffic in tensor parallel mode") == true, "\(target.line ?? "")") + let assisted = try plan(try assistantQuote(1, verification: .admittedCohort, artifact: artifact)) + #expect(assisted.setup.tensorAssistant != nil) + #expect(assisted.line?.hasPrefix("qualified for public traffic") == false, "\(assisted.line ?? "")") + #expect(assisted.line?.hasPrefix("not offered for public traffic") == true, "\(assisted.line ?? "")") + #expect(assisted.line == ClusterPairOwnerServing.tensorAssistantNotOffered) + // The plan's own explanation (`darkbloom cluster plan`, the six-step wizard) says the same under "Public traffic". + func publicSection(_ lines: [String]) -> String? { lines.firstIndex(of: "Public traffic").map { lines[$0 + 1] } } + #expect(publicSection(target.explanation)?.hasPrefix(" Qualified for public traffic in tensor parallel mode") == true) + #expect(publicSection(assisted.explanation)?.hasPrefix(" Not offered for public traffic: it decodes with Qwen's speculative assistant") == true, + "\(publicSection(assisted.explanation) ?? "")") + } + @Test func testAssistantSingletonAndWiderPlansPersistSamePolicyAndBilateralArguments() throws { for verification in [ClusterQwenTensorAssistantPolicy.Verification.singleton, .admittedCohort] { let home = try home(); record(home) @@ -1008,6 +1080,21 @@ final class DistributedAutomaticBatchPlannerTests { } +/// Runs `body` on a thread with a 16 MiB stack and returns its result: the guided setup's whole planning step +/// (`ClusterSetupPlanning.decide` over `ClusterPlacementFlow.decide`) outgrows a test task's thread stack in a debug +/// build. +private func onLargeStack(_ body: @escaping @Sendable () -> T) -> T { + let result = LargeStackResult(), done = DispatchSemaphore(value: 0) + let thread = Thread { result.value = body(); done.signal() } + thread.stackSize = 16 << 20 + thread.start() + done.wait() + return result.value! +} + +/// The value `onLargeStack`'s thread hands back; written once before the semaphore signals, read after it. +private final class LargeStackResult: @unchecked Sendable { var value: T? } + private final class FeatureReadyOwner: DistributedResidentExecutionOwner, @unchecked Sendable { let ready: DistributedResidentReadiness? init(_ ready: DistributedResidentReadiness?) { self.ready = ready } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift new file mode 100644 index 0000000000..d7f19723aa --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/EngineV2ResliceFloorWiringTests.swift @@ -0,0 +1,256 @@ +// Copyright © 2026 Eigen Labs. +// +// Re-slice orchestration against slots whose floors include real fixed +// request workspace (`ResliceFloorScenario`). Residents are real EngineV2 +// instances over a contiguous backend, so `minimumServiceableGrantBytes` +// and serving width come from production code; the newcomer is built by +// the scripted hook engine. No weights, requests or GPU work. + +import Foundation +import MLXLMCommon +import MLXNN +import Testing + +@testable import ProviderCore + +private final class FloorStubLanguageModel: Module, LanguageModel { + func prepare(_ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters) throws + -> PrepareResult { + .tokens(input.text) + } + func newCache(parameters: GenerateParameters?) -> [KVCache] { [] } +} + +private struct FloorStubProcessor: UserInputProcessor { + struct Unsupported: Error {} + func prepare(input: UserInput) async throws -> LMInput { throw Unsupported() } +} + +private func makeFloorContainer() -> ModelContainer { + ModelContainer(context: ModelContext( + configuration: ModelConfiguration(id: "test/reslice-floor"), + model: FloorStubLanguageModel(), processor: FloorStubProcessor(), + tokenizer: StubBridgeTokenizer())) +} + +/// The production default `memory_reserve_gb`; it does not bind on 150+ GB. +private let floorConfigReserveBytes: UInt64 = 4 << 30 + +private func makeFloorLoop(physicalBytes: UInt64) throws -> ProviderLoop { + let config = ProviderLoopConfig( + coordinatorURL: "ws://127.0.0.1:0/ignored", + hardware: HardwareInfo( + machineModel: "Mac14,14", chipName: "Apple M2 Ultra", chipFamily: .m2, chipTier: .ultra, + memoryGb: physicalBytes >> 30, memoryAvailableGb: (physicalBytes >> 30) - 8, + cpuCores: CpuCores(total: 24, performance: 16, efficiency: 8), + gpuCores: 76, memoryBandwidthGbs: 800), + models: [], + config: ProviderConfig( + provider: ProviderSettings(name: "reslice-floor-test", memoryReserveGB: 4), + backend: BackendSettings(idleTimeoutMins: 0, maxModelSlots: 8), + coordinator: CoordinatorSettings(heartbeatIntervalSecs: 60))) + return try ProviderLoop(config: config, attestationSigner: nil, + kvBudgetForTesting: ScriptedProviderMemory.budget( + physicalBytes: physicalBytes, configReserveBytes: floorConfigReserveBytes)) +} + +/// Fleet KV budget for `models` resident on the scenario machine. +private func floorBudget(_ models: [ResliceFloorScenario.Model], physicalBytes: UInt64) -> UInt64 { + UnifiedMemoryCap.kvBudgetBytes(physicalBytes: physicalBytes, + residentWeightBytes: UInt64(models.reduce(0) { $0 + $1.weightsBytes }), + configReserveBytes: floorConfigReserveBytes) +} + +/// Residents at the shares the six-slot re-slice gave them, installed on +/// `install`. Each bridge must report the scenario's floor. +private func installResidents( + physicalBytes: UInt64, + install: (ResliceFloorScenario.Model, EngineV2Bridge) async -> Void +) async throws -> [String: EngineV2Bridge] { + let residents = try ResliceFloorScenario.residents() + let shares = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: floorBudget(residents, physicalBytes: physicalBytes)) + var bridges: [String: EngineV2Bridge] = [:] + for resident in residents { + let bridge = ResliceFloorScenario.makeBridge(modelId: resident.id, + fixedRequestBytes: resident.fixedRequestBytes, grant: try #require(shares[resident.id]), + kvBytesPerToken: resident.fp16KVBytesPerToken) + #expect(await bridge.minimumServiceableGrantBytes() == resident.minimumGrantBytes, "\(resident.id)") + await install(resident, bridge) + bridges[resident.id] = bridge + } + return bridges +} + +/// Every resident keeps at least its floor and can still serve a request. +private func expectResidentsServiceable(_ bridges: [String: EngineV2Bridge]) async { + for (id, bridge) in bridges { + let grant = await bridge.engineKVBytesCapacity() + #expect(grant >= (await bridge.minimumServiceableGrantBytes()), "\(id) grant \(grant)") + #expect(await bridge.effectiveServingConcurrency(allowExpansion: true) >= 1, "\(id)") + } +} + +@Suite("KV re-slice keeps every slot's floor (orchestration)", .serialized) +struct EngineV2ResliceFloorWiringTests { + private static let physical = ResliceFloorScenario.physicalBytes + + @Test("ProviderLoop admits a seventh model when Σ floors fits the fleet budget", + arguments: [ResliceFloorScenario.gemmaQAT.id, ResliceFloorScenario.gptOSS.id]) + func providerLoopAdmitsSeventhModel(newcomerID: String) async throws { + let newcomer = newcomerID == ResliceFloorScenario.gptOSS.id + ? ResliceFloorScenario.gptOSS : ResliceFloorScenario.gemmaQAT + let loop = try makeFloorLoop(physicalBytes: Self.physical) + let runtime = EngineV2Runtime() + await loop.setEngineV2RuntimeForTesting(runtime) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + let all = try ResliceFloorScenario.residents() + [newcomer] + let budget = floorBudget(all, physicalBytes: Self.physical) + // The proportional share alone would leave Lightning below its floor. + let lightning = try #require(all.first { $0.id == ResliceFloorScenario.lightningID }) + let proportional = EngineV2KVSizing.resliceGrants(existing: all.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: budget) + let lightningShare = try #require(proportional[lightning.id]) + #expect(lightningShare < lightning.minimumGrantBytes) + #expect(UInt64(all.reduce(0) { $0 + $1.minimumGrantBytes }) <= budget) + + let bridge = try await loop.resliceAndBuildEngineV2SlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + + await expectResidentsServiceable(residents) + let newcomerGrant = await bridge.engineKVBytesCapacity() + #expect(newcomerGrant >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + var total = UInt64(newcomerGrant) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= budget) + await bridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("StandaloneServer admits a seventh model when Σ floors fits the fleet budget") + func standaloneAdmitsSeventhModel() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let server = StandaloneServer(models: []) + await server.setV2TestHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await server.installSlotForTesting(modelId: model.id, bridge: bridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: model.sizing, modelType: model.modelType) + } + + let bridge = try await server.buildSlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + + await expectResidentsServiceable(residents) + #expect(await bridge.engineKVBytesCapacity() >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + await bridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("a seventh model whose floors exceed the fleet budget is still refused") + func infeasibleSeventhModelIsRefused() async throws { + let physical: UInt64 = 150 << 30 + let newcomer = ResliceFloorScenario.gemmaQAT + let all = try ResliceFloorScenario.residents() + [newcomer] + #expect(UInt64(all.reduce(0) { $0 + $1.minimumGrantBytes }) > floorBudget(all, physicalBytes: physical)) + let loop = try makeFloorLoop(physicalBytes: physical) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + var before: [String: Int] = [:] + for (id, bridge) in residents { before[id] = await bridge.engineKVBytesCapacity() } + + do { + _ = try await loop.resliceAndBuildEngineV2SlotForTesting( + modelId: newcomer.id, modelType: newcomer.modelType, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), sizing: newcomer.sizing) + Issue.record("an infeasible re-slice was admitted") + } catch InferenceError.modelLoadFailed(let message) { + #expect(message.contains("would leave a model without its fixed request workspace")) + #expect(message.contains("across 7 slots")) + } + for (id, bridge) in residents { + #expect(await bridge.engineKVBytesCapacity() == before[id], "\(id)") + await bridge.shutdown() + } + } + + @Test("regrow and the reserve preflight keep a starved slot at its floor") + func regrowAndPreflightKeepFloors() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let loop = try makeFloorLoop(physicalBytes: Self.physical) + await loop.setEngineV2SlotHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await loop.installModelSlotForTesting(modelId: model.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: bridge, + sizing: model.sizing, modelType: model.modelType) + } + let newcomerBridge = EngineV2Bridge(engine: InertStubEngine(kvBytesCapacity: 4 << 30), + modelId: newcomer.id, tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: []) + await loop.installModelSlotForTesting(modelId: newcomer.id, container: makeFloorContainer(), + tokenizer: TokenizerHandle(StubBridgeTokenizer()), engineV2: newcomerBridge, + sizing: newcomer.sizing, modelType: newcomer.modelType) + + #expect(await loop.reserveRaiseKeepsSurvivorsServiceable( + reserveBytes: UnifiedMemoryCap.defaultActivationReserveBytes)) + await loop.resliceGrowSurvivorsForTesting() + + await expectResidentsServiceable(residents) + let all = try ResliceFloorScenario.residents() + [newcomer] + var total = UInt64(await newcomerBridge.engineKVBytesCapacity()) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= floorBudget(all, physicalBytes: Self.physical)) + await newcomerBridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } + + @Test("StandaloneServer regrow and the reserve check keep a starved slot at its floor") + func standaloneRegrowAndReserveKeepFloors() async throws { + let newcomer = ResliceFloorScenario.gemmaQAT + let server = StandaloneServer(models: []) + await server.setV2TestHooksForTesting(.init(physicalMemoryBytes: Self.physical, + makeEngine: { _, grant in InertStubEngine(kvBytesCapacity: grant) })) + let residents = try await installResidents(physicalBytes: Self.physical) { model, bridge in + await server.installSlotForTesting(modelId: model.id, bridge: bridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: model.sizing, modelType: model.modelType) + } + let newcomerBridge = EngineV2Bridge(engine: InertStubEngine(kvBytesCapacity: 4 << 30), + modelId: newcomer.id, tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: []) + await server.installSlotForTesting(modelId: newcomer.id, bridge: newcomerBridge, + container: makeFloorContainer(), tokenizer: TokenizerHandle(StubBridgeTokenizer()), + sizing: newcomer.sizing, modelType: newcomer.modelType) + // The server's own budget: its proportional share alone starves Lightning. + let budget = await server.fleetKVBudgetBytes(extraWeightBytes: 0) + let all = try ResliceFloorScenario.residents() + [newcomer] + let lightning = try #require(all.first { $0.id == ResliceFloorScenario.lightningID }) + let proportional = EngineV2KVSizing.resliceGrants(existing: all.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: budget) + #expect(try #require(proportional[lightning.id]) < lightning.minimumGrantBytes) + + #expect(await server.reserveKeepsSurvivorsServiceable( + reserveBytes: await server.resolvedActivationReserveBytes)) + await server.resliceGrowSurvivors() + + await expectResidentsServiceable(residents) + var total = UInt64(await newcomerBridge.engineKVBytesCapacity()) + for resident in residents.values { total += UInt64(await resident.engineKVBytesCapacity()) } + #expect(total <= budget) + await newcomerBridge.shutdown() + for resident in residents.values { await resident.shutdown() } + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift new file mode 100644 index 0000000000..12ff78b434 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Fixtures/ResliceFloorScenario.swift @@ -0,0 +1,139 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLX + +@testable import MLXLLM +@testable import MLXLMCommon +@testable import ProviderCore + +/// The 0.10.5 "would leave a model without its fixed request workspace" +/// refusal: six catalog models resident on a 192 GB Mac, then +/// gemma-4-26b-qat-4bit or gpt-oss-20b as the seventh slot. Configuration +/// only: no weights, forward pass or tensor evaluation. +/// +/// KV rates are the engine's marginal fp16 rate (full-attention rows only). +/// Weights are the production catalog's `total_size_bytes`. Fixed request +/// workspace is each engine's recurrent state per request, a lower bound: +/// it leaves out allocator rounding, convolution state for Nemotron, and +/// assistant history. A slot's floor is what `EngineV2Bridge +/// .minimumServiceableGrantBytes` reports for that workspace. +enum ResliceFloorScenario { + struct Model { + let id: String + let modelType: String + let fp16KVBytesPerToken: Int + let maxContextLength: Int + let weightsBytes: Int + let fixedRequestBytes: Int + + var resliceSlot: EngineV2KVSizing.ResliceSlot { + .init(modelId: id, fp16KVBytesPerToken: fp16KVBytesPerToken, maxContextLength: maxContextLength) + } + + var sizing: SlotSizingSnapshot { + .init(weightsBytes: weightsBytes, fp16KVBytesPerToken: fp16KVBytesPerToken, + maxContextLength: maxContextLength, defaultMaxTokens: 8192) + } + + var minimumGrantBytes: Int { ResliceFloorScenario.minimumGrantBytes(fixedRequestBytes: fixedRequestBytes) } + } + + static let physicalBytes: UInt64 = 192 << 30 + + /// The fleet budgets the reporting provider logged for the two refusals. + static let reportedGemmaBudget: UInt64 = 51_467_271_830 + static let reportedGPTOSSBudget: UInt64 = 54_999_766_706 + + static let gemmaQAT = Model(id: "gemma-4-26b-qat-4bit", modelType: "gemma4", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 15_641_239_295, fixedRequestBytes: 0) + static let gptOSS = Model(id: "gpt-oss-20b", modelType: "gpt_oss", + fp16KVBytesPerToken: 24_576, maxContextLength: 131_072, + weightsBytes: 12_104_215_835, fixedRequestBytes: 0) + + /// The resident set. Its Qwen recurrent rows come from decoding each + /// model's text configuration. With MTP on (`mtp_mode = auto`), Qwen + /// adds one compact-replay generation to the three base generations; + /// Nemotron Lightning's request-stateful assistant at the tested depth + /// adds depth − 1. + static func residents() throws -> [Model] { + let base = CBv2RecurrentStateSpec.maximumLiveGenerations + let depth = CBv2MTPConfig.testedMaxDraftTokens + let wide = try qwenGeneration(wide: true) + let narrow = try qwenGeneration(wide: false) + // 23 Mamba-2 layers, FP32 SSM state [64 heads, 64, 128] each. + let lightningGeneration = 23 * 64 * 64 * 128 * 4 + return [ + Model(id: "ternary-bonsai-2-27b", modelType: "prism_hadamard_qwen35", + fp16KVBytesPerToken: 65_536, maxContextLength: 262_144, + weightsBytes: 8_608_670_713, fixedRequestBytes: base * wide), + Model(id: "qwen3.6-35b-a3b-vl-mtp-mxfp8", modelType: "qwen3_5_moe", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 21_308_856_601, fixedRequestBytes: (base + 1) * narrow), + Model(id: "EigenLabs/Qwen3.8-27B-4bit-mtp", modelType: "qwen3_5", + fp16KVBytesPerToken: 65_536, maxContextLength: 262_144, + weightsBytes: 16_320_415_757, fixedRequestBytes: (base + 1) * wide), + Model(id: "gemma-4-26b", modelType: "gemma4", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 27_986_040_506, fixedRequestBytes: 0), + Model(id: "qwen3.5-35b-a3b", modelType: "qwen3_5_moe", + fp16KVBytesPerToken: 20_480, maxContextLength: 262_144, + weightsBytes: 20_893_747_852, fixedRequestBytes: (base + 1) * narrow), + Model(id: "nvidia-nemotron-3.5-lightning", modelType: "nemotron_h", + fp16KVBytesPerToken: 6_144, maxContextLength: 262_144, + weightsBytes: 19_059_595_830, fixedRequestBytes: (base + depth - 1) * lightningGeneration), + ] + } + + static let lightningID = "nvidia-nemotron-3.5-lightning" + + /// An ordinary engine's floor at the SDK's default admission watermark; + /// an engine with no fixed workspace reports the base minimum. + static func minimumGrantBytes(fixedRequestBytes: Int) -> Int { + guard fixedRequestBytes > 0 else { return Int(EngineV2KVSizing.minimumServiceableGrantBytes) } + let watermark = AdmissionV2.Config().watermarkFraction + let capacity = 16 << 30 + return EngineV2Bridge.minimumOrdinaryGrantBytes( + fixedRequestBytes: fixedRequestBytes, capacityBytes: capacity, + admissibleCapacityBytes: capacity - Int(Double(capacity) * watermark), + watermarkFraction: watermark) + } + + /// A real ordinary engine over a contiguous backend holding `grant`, with + /// `fixedRequestBytes` of workspace per request at the SDK's default + /// watermark: its bridge reports the production floor and serving width. + static func makeBridge(modelId: String, fixedRequestBytes: Int, grant: Int, + kvBytesPerToken: Int = 0) -> EngineV2Bridge { + let fixture = DeadlineAdmissionFixtureModel() + let admission = AdmissionV2.Config(elementBytes: 4, fixedBytesPerRequest: fixedRequestBytes) + let engine = EngineV2(model: fixture, layerKinds: fixture.kinds, + backend: CBv2ContiguousKVBackend(config: .init(bytesCapacity: grant)), + cacheProvider: CBv2LayerCacheBank(layerKinds: fixture.kinds), + schedulerConfig: .init(maxConcurrentRequests: 4, enablePrefixCache: false), + admissionConfig: admission) + return EngineV2Bridge(engine: engine, modelId: modelId, + tokenizer: TokenizerHandle(StubBridgeTokenizer()), eosTokenIds: [], + kvBytesPerToken: kvBytesPerToken, fixedRequestBytes: engine.resolvedFixedBytesPerRequest, + admissionWatermarkFraction: admission.watermarkFraction, kvBackendKind: .contiguous) + } + + /// One recurrent generation of the dense 27B (`wide`) or the 35B-A3B + /// Qwen text tower. + private static func qwenGeneration(wide: Bool) throws -> Int { + let fields: [String: Any] = [ + "hidden_size": wide ? 5120 : 2048, + "num_hidden_layers": wide ? 64 : 40, + "num_attention_heads": wide ? 24 : 16, + "num_key_value_heads": wide ? 4 : 2, + "head_dim": 256, "full_attention_interval": 4, + "linear_num_key_heads": 16, "linear_key_head_dim": 128, + "linear_num_value_heads": wide ? 48 : 32, + "linear_value_head_dim": 128, "linear_conv_kernel_dim": 4, + "max_position_embeddings": 262_144, + ] + let config = try JSONDecoder().decode(Qwen35TextConfiguration.self, + from: JSONSerialization.data(withJSONObject: fields)) + return try config.cbv2RecurrentStateSpec(activationDType: .bfloat16).fixedBytesPerRequest() + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift new file mode 100644 index 0000000000..f70216b22c --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Memory/EngineV2ResliceFloorTests.swift @@ -0,0 +1,150 @@ +// Copyright © 2026 Eigen Labs. +// +// `EngineV2KVSizing.resliceGrants` given each slot's serviceability floor: +// the reported 0.10.5 refusal (`ResliceFloorScenario`), the unchanged +// proportional result whenever it already clears every floor, refusal when +// Σ(floors) exceeds the budget, and Σ(grants) ≤ budget throughout. + +import Foundation +import Testing + +@testable import ProviderCore + +@Suite("EngineV2 KV re-slice with slot floors (pure)") +struct EngineV2ResliceFloorTests { + private static let gib = 1 << 30 + + private static func floors(_ models: [ResliceFloorScenario.Model]) -> [String: Int] { + Dictionary(uniqueKeysWithValues: models.map { ($0.id, $0.minimumGrantBytes) }) + } + + private static func sum(_ grants: [String: Int]) -> UInt64 { + grants.values.reduce(UInt64(0)) { $0 + UInt64($1) } + } + + @Test("the reported refusal: Lightning starves under the proportional split; floors first admits", + arguments: [ + (ResliceFloorScenario.gemmaQAT.id, ResliceFloorScenario.reportedGemmaBudget), + (ResliceFloorScenario.gptOSS.id, ResliceFloorScenario.reportedGPTOSSBudget), + ]) + func reportedRefusalIsAdmitted(newcomerID: String, budget: UInt64) throws { + let newcomer = newcomerID == ResliceFloorScenario.gptOSS.id + ? ResliceFloorScenario.gptOSS : ResliceFloorScenario.gemmaQAT + let residents = try ResliceFloorScenario.residents() + // The newcomer has only the base floor, as on the load path. + let minimums = Self.floors(residents) + let floorTotal = residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + } + #expect(UInt64(floorTotal) * 5 < budget) + + let proportional = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget) + #expect(!EngineV2KVSizing.resliceMeetsServiceabilityFloor(proportional, minimumGrantBytes: minimums)) + let lightningFloor = try #require(minimums[ResliceFloorScenario.lightningID]) + let lightningShare = try #require(proportional[ResliceFloorScenario.lightningID]) + #expect(lightningShare < lightningFloor) + + let grants = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget, minimumGrantBytes: minimums) + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: minimums)) + #expect(grants.count == 7 && Self.sum(grants) <= budget) + // Each slot holds its floor plus its weighted share of the rest. + let remainder = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget - UInt64(floorTotal)) + for slot in residents + [newcomer] { + let floor = minimums[slot.id] ?? Int(EngineV2KVSizing.minimumServiceableGrantBytes) + #expect(grants[slot.id] == floor + (remainder[slot.id] ?? 0), "\(slot.id)") + } + } + + @Test("a proportional split that clears every floor is returned unchanged") + func clearingSplitIsUnchanged() throws { + let residents = try ResliceFloorScenario.residents() + let sixSlotBudget: UInt64 = 65_459_679_896 + let six = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: sixSlotBudget) + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(six, minimumGrantBytes: Self.floors(residents))) + #expect(EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), newcomer: nil, + fleetKVBudgetBytes: sixSlotBudget, minimumGrantBytes: Self.floors(residents)) == six) + + let pair = [ResliceFloorScenario.gemmaQAT.resliceSlot] + let budget = UInt64(40 * Self.gib) + #expect(EngineV2KVSizing.resliceGrants(existing: pair, newcomer: ResliceFloorScenario.gptOSS.resliceSlot, + fleetKVBudgetBytes: budget, minimumGrantBytes: [:]) + == EngineV2KVSizing.resliceGrants(existing: pair, newcomer: ResliceFloorScenario.gptOSS.resliceSlot, + fleetKVBudgetBytes: budget)) + } + + @Test("Σ floors above the budget, or an unprovable floor, keeps the proportional split and refuses") + func infeasibleFloorsStillRefuse() throws { + let residents = try ResliceFloorScenario.residents() + let newcomer = ResliceFloorScenario.gemmaQAT + let minimums = Self.floors(residents) + let floorTotal = residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + } + var unprovable = minimums + unprovable["gemma-4-26b"] = Int.max + let cases: [(UInt64, [String: Int])] = [ + (UInt64(floorTotal - 1), minimums), + (ResliceFloorScenario.reportedGemmaBudget, unprovable), + ] + for (budget, floors) in cases { + let proportional = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget) + let grants = EngineV2KVSizing.resliceGrants(existing: residents.map(\.resliceSlot), + newcomer: newcomer.resliceSlot, fleetKVBudgetBytes: budget, minimumGrantBytes: floors) + #expect(grants == proportional) + #expect(!EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: floors)) + } + } + + @Test("Σ grants ≤ budget at every budget; every floor is met exactly when Σ floors fits") + func budgetInvariantAcrossBudgets() throws { + let residents = try ResliceFloorScenario.residents() + let slots = residents.map(\.resliceSlot) + let newcomer = ResliceFloorScenario.gptOSS.resliceSlot + let minimums = Self.floors(residents) + let floorTotal = UInt64(residents.reduce(Int(EngineV2KVSizing.minimumServiceableGrantBytes)) { + $0 + $1.minimumGrantBytes + }) + var budgets: [UInt64] = [0, floorTotal - 1, floorTotal, floorTotal + 1, UInt64(Int.max)] + var step = floorTotal / 2 + while step < 4 * ResliceFloorScenario.reportedGPTOSSBudget { + budgets.append(step) + step += 997_001_003 + } + for budget in budgets { + let grants = EngineV2KVSizing.resliceGrants(existing: slots, newcomer: newcomer, + fleetKVBudgetBytes: budget, minimumGrantBytes: minimums) + #expect(Self.sum(grants) <= min(budget, UInt64(Int.max)), "budget \(budget)") + #expect(EngineV2KVSizing.resliceMeetsServiceabilityFloor(grants, minimumGrantBytes: minimums) + == (floorTotal <= budget), "budget \(budget)") + } + // At the boundary every slot holds exactly its floor. + let tight = EngineV2KVSizing.resliceGrants(existing: slots, newcomer: newcomer, + fleetKVBudgetBytes: floorTotal, minimumGrantBytes: minimums) + for slot in slots + [newcomer] { + #expect(tight[slot.modelId] == minimums[slot.modelId] ?? Self.gib, "\(slot.modelId)") + } + } + + @Test("an unknown rate splits what remains after the floors equally") + func unknownRateSplitsRemainderEqually() { + let starved = EngineV2KVSizing.ResliceSlot(modelId: "a", fp16KVBytesPerToken: 0, maxContextLength: 0) + let other = EngineV2KVSizing.ResliceSlot(modelId: "b", fp16KVBytesPerToken: 20_480, maxContextLength: 131_072) + let budget = UInt64(6 * Self.gib) + let grants = EngineV2KVSizing.resliceGrants(existing: [starved], newcomer: other, + fleetKVBudgetBytes: budget, minimumGrantBytes: ["a": 4 * Self.gib]) + #expect(grants == ["a": 4 * Self.gib + Self.gib / 2, "b": Self.gib + Self.gib / 2]) + } + + @Test("a single slot keeps the whole budget whatever its floor") + func singleSlotKeepsWholeBudget() { + let budget = UInt64(3 * Self.gib) + let grants = EngineV2KVSizing.resliceGrants(existing: [], newcomer: ResliceFloorScenario.gemmaQAT.resliceSlot, + fleetKVBudgetBytes: budget, minimumGrantBytes: [ResliceFloorScenario.gemmaQAT.id: 8 * Self.gib]) + #expect(grants == [ResliceFloorScenario.gemmaQAT.id: Int(budget)]) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift index 1f52708d15..f1d5168c67 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedSlotTests+Capacity.swift @@ -55,14 +55,36 @@ extension NemotronSuperManagedSlotTests { #expect(await fixture.budget.outstandingReservedBytes() == 0) } - /// The build is checked against its grant with the planned lane and - /// round; publication re-slices it beside the resident models. Beside an - /// idle model with a far larger KV share (the fixture owner publishes its - /// 1,024-token context against that model's 8,192), Super's grant is a few - /// MiB and serves no request: the load fails, the slot is unpublished and - /// retired, and the co-resident model keeps its grant and is not evicted. + /// Beside an idle model with a far larger KV share (the fixture owner + /// publishes its 1,024-token context against that model's 8,192), Super's + /// proportional share is a few MiB. Both floors fit the budget, so Super + /// is funded to its floor and loads; the co-resident model keeps its own. @Test(.timeLimit(.minutes(2))) - func publishedGrantThatServesNoRequestFailsTheLoad() async throws { + func superBesideALargerKVShareLoadsAtItsFloor() async throws { + let fixture = try await Self.coResidentFixture(weightsGiB: 1, availableGiB: 110) + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let loop = fixture.loop + await loop.setEngineV2SlotHooksForTesting(ProviderLoop.EngineV2SlotHooks( + physicalMemoryBytes: 128 << 30, makeEngine: { _, _ in throw CancellationError() })) + try await loop.ensureModelLoaded(modelId: Self.modelID, allowEviction: false, + revisionDirectory: fixture.directory) + let owner = try #require(await loop.nemotronSuperOwnerForTesting(modelId: Self.modelID)) + let grant = await owner.bridge.resliceAdmissionBytesClaim() + #expect(grant >= (await owner.bridge.minimumServiceableGrantBytes())) + #expect(await owner.bridge.superGrantRefusal(grantBytes: grant, requests: 1) == nil) + let coResidentGrant = try #require(fixture.idle.capacityUpdates.last) + #expect(coResidentGrant >= Int(EngineV2KVSizing.minimumServiceableGrantBytes)) + #expect(await loop.modelLoadingResidentIDs() == [Self.coResidentID, Self.modelID].sorted()) + #expect(await loop.unloadModel(Self.modelID)) + } + + /// The newcomer check counts Super's planned lane and round beside its + /// grant. A co-resident model whose own floor leaves less than Super's + /// base floor of that budget refuses the load before anything is built: + /// nothing is published or retained, and the co-resident model keeps its + /// grant and is not evicted. + @Test(.timeLimit(.minutes(2))) + func floorsAboveTheBudgetRefuseTheLoadBeforeTheBuild() async throws { let fixture = try await Self.coResidentFixture(weightsGiB: 1, availableGiB: 110) defer { try? FileManager.default.removeItem(at: fixture.directory) } let loop = fixture.loop @@ -70,6 +92,11 @@ extension NemotronSuperManagedSlotTests { physicalMemoryBytes: 128 << 30, makeEngine: { _, _ in throw CancellationError() })) await loop.resliceGrowSurvivorsForTesting() let lone = try #require(fixture.idle.capacityUpdates.last) + // Its floor leaves 1.75 GiB of the lone budget, less than Super's + // planned reservations and base floor need. + let coResident = ResliceFloorScenario.makeBridge(modelId: Self.coResidentID, + fixedRequestBytes: Int(Double(lone - (7 << 28)) * 0.95) - (1 << 30), grant: lone) + await loop.modelLoadingInstallSlot(Self.coResidentID, bridge: coResident, weightsBytes: 1 << 30) var refusal: Error? do { try await loop.ensureModelLoaded(modelId: Self.modelID, allowEviction: false, @@ -77,15 +104,15 @@ extension NemotronSuperManagedSlotTests { } catch { refusal = error } let error = try #require(refusal) #expect(ProviderLoop.loadErrorStatusCode(for: error) == 503) - #expect("\(error)".contains("serves 1 concurrent request(s)"), "\(error)") - #expect(await loop.modelLoadingLastLoadError()?.message.contains("serves 1 concurrent request(s)") == true) + #expect("\(error)".contains("below its serviceable KV grant"), "\(error)") + #expect(await loop.modelLoadingLastLoadError()?.message.contains("below its serviceable KV grant") == true) #expect(await loop.nemotronSuperOwnerForTesting(modelId: Self.modelID) == nil) #expect(await loop.engineV2Runtime.bridge(forModel: Self.modelID) == nil) #expect(await loop.modelLoadingResidentIDs() == [Self.coResidentID]) - #expect(fixture.idle.shutdownCalls == 0) - #expect(fixture.idle.capacityUpdates.last == lone, "the co-resident model's grant is restored") + #expect(await coResident.engineKVBytesCapacity() == lone, "the co-resident model keeps its grant") #expect(await fixture.budget.outstandingReservedBytes() == 0) #expect(await loop.nemotronSuperRetainedWeightBytesForTesting() == 0) + await coResident.shutdown() } /// A load whose native work did not retire keeps the installation's size diff --git a/scripts/provider-cluster-runtime-facts.sh b/scripts/provider-cluster-runtime-facts.sh new file mode 100755 index 0000000000..0017300832 --- /dev/null +++ b/scripts/provider-cluster-runtime-facts.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# The cluster runtime facts (cluster_runtime) of an app bundle for one +# environment, computed by the app's own CLI and cluster worker +# (ClusterRuntimeApprovalFacts), so each model's pair-serving grant and the +# parity qualifications of the models it declares public are that build's +# (its qualification records and ClusterPublicModels). +# +# Usage: provider-cluster-runtime-facts.sh APP CLI_NAME ENVIRONMENT FOLDER +# +# The app lists the models it qualifies on a cluster; their manifest, +# config.json (never weights) and catalog entry (its input modalities) come from +# ENVIRONMENT's public catalog and model CDN (provider-cluster-runtime-models.py), +# which leaves out a listed model that catalog does not have and names it in +# FOLDER/skipped.md; the app's worker describes each one. FOLDER must not exist; the facts are +# FOLDER/cluster-runtime.json. The app's CLI runs with an empty environment. +set -euo pipefail + +if [ "$#" -ne 4 ]; then + echo "usage: $0 APP CLI_NAME ENVIRONMENT FOLDER" >&2 + exit 64 +fi +app=$1 +cli=$2 +environment=$3 +root=$4 +scripts=$(cd "$(dirname "$0")" && pwd) + +mkdir "$root" "$root/home" +runtime_facts() { + env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin HOME="$root/home" DARKBLOOM_NO_UPDATE_CHECK=1 \ + "$app/Contents/MacOS/$cli" cluster runtime-facts "$@" +} + +runtime_facts --list-release-models > "$root/release-models.json" +python3 "$scripts/provider-cluster-runtime-models.py" --environment "$environment" \ + --models "$root/release-models.json" --output "$root/candidates" --skipped "$root/skipped.md" +runtime_facts --app "$app" --release-candidates "$root/candidates" > "$root/cluster-runtime.json" diff --git a/scripts/provider-cluster-runtime-models.py b/scripts/provider-cluster-runtime-models.py new file mode 100644 index 0000000000..6e91e22686 --- /dev/null +++ b/scripts/provider-cluster-runtime-models.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Fetch the metadata of every model a release's cluster runtime facts describe. + +The input is the build's own model list (`darkbloom cluster runtime-facts +--list-release-models`) and the release's environment. The catalog and model +CDN read are the environment's own, the ones its app reads +(provider-swift/identity/provider-identity.json: `coordinatorHTTPURL`, +`modelCDNURL`). For each listed artifact, every entry of the public catalog +(`GET /v1/models/catalog`) with that aggregate gives candidates: the two +encodings of the entry's manifest the provider reads, in the order it asks for +them (ClusterModelProvisioningStore.catalogAnswer: +`//manifest.json`, then +`/v1/models/catalog/manifest/`), each with the entry's +config.json from the CDN. A manifest is kept when it names the entry and the +listed aggregate and lists config.json; config.json is kept when its size and +SHA-256 are the manifest's. Each kept manifest is one candidate folder, with the +entry's `id` and `input_modalities` (catalog.json: the media a declared public +model's request envelope admits); the build's own worker chooses among them. +Weights are never read. + +A listed artifact the catalog does not have is left out and named (standard +output and `--skipped`). Every other failure (an unreadable catalog, an entry +with no usable manifest) fails the command, which then writes nothing. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +ROOT = Path(__file__).resolve().parent.parent +IDENTITY_FILE = ROOT / 'provider-swift/identity/provider-identity.json' +ENVIRONMENTS = ('dev', 'staging', 'prod') +# ClusterCatalogArtifact.maximumManifestBytes; ClusterConfigurationFiles.maximumModelConfigurationBytes. +MAXIMUM_MANIFEST_BYTES = 1 << 20 +MAXIMUM_CONFIGURATION_BYTES = 32 << 20 +MAXIMUM_CATALOG_BYTES = 8 << 20 +ATTEMPTS = 3 +# The CDN refuses Python's default agent. +USER_AGENT = 'darkbloom-release-cluster-runtime/1' +DIGEST = re.compile(r'[0-9a-f]{64}') +MODALITY = re.compile(r'[\x21-\x7e]{1,32}') +MAXIMUM_MODALITIES = 16 + + +class FetchError(RuntimeError): + pass + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise FetchError(f'refusing a redirect from {req.full_url}') + + +def registry(environment, identity_file=IDENTITY_FILE): + """(coordinator URL, CDN URL) the app of `environment` reads.""" + if environment not in ENVIRONMENTS: + raise ValueError(f'Unknown environment: {environment}') + entry = json.loads(Path(identity_file).read_text())['environments'][environment] + return entry['coordinatorHTTPURL'].rstrip('/'), entry['modelCDNURL'].rstrip('/') + + +def get(url, maximum): + """The body of a 200 response of at most `maximum` bytes; transient failures are retried.""" + request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT}) + for attempt in range(1, ATTEMPTS + 1): + try: + with urllib.request.build_opener(NoRedirect()).open(request, timeout=60) as response: + data = response.read(maximum + 1) + if len(data) > maximum: + raise FetchError(f'{url}: more than {maximum} bytes') + return data + except urllib.error.HTTPError as error: + error.close() + if error.code < 500 or attempt == ATTEMPTS: + raise FetchError(f'{url}: HTTP {error.code}') from error + except (urllib.error.URLError, TimeoutError, ConnectionError) as error: + if attempt == ATTEMPTS: + raise FetchError(f'{url}: {error}') from error + time.sleep(2 * attempt) + raise AssertionError('unreachable') + + +def r2_path(path): + # ModelDownloader.escapeR2Path: each segment percent-encoded as a URL path. + return '/'.join(urllib.parse.quote(segment, safe="!$&'()*+,;=:@") for segment in path.split('/')) + + +def model_id_path(model_id): + # ModelCatalogClient.escapeModelIDForPath: one segment, so "/" is encoded. + return urllib.parse.quote(model_id, safe="!$&'()*+,;=:@") + + +def catalog(coordinator, fetch=get): + try: + models = json.loads(fetch(coordinator + '/v1/models/catalog', MAXIMUM_CATALOG_BYTES))['models'] + except (ValueError, KeyError, TypeError) as error: + raise FetchError(f'{coordinator}: unreadable model catalog') from error + if not isinstance(models, list): + raise FetchError(f'{coordinator}: unreadable model catalog') + return [entry for entry in models if isinstance(entry, dict)] + + +def configuration_entry(data, entry, artifact): + """The manifest's config.json entry, when the manifest names this catalog entry and artifact.""" + try: + manifest = json.loads(data) + except ValueError as error: + raise ValueError('not JSON') from error + if not isinstance(manifest, dict) or manifest.get('model_id') != entry['id'] \ + or manifest.get('aggregate_sha256') != artifact: + raise ValueError('names another model or aggregate') + files = [item for item in manifest.get('files') or [] if isinstance(item, dict) and item.get('path') == 'config.json'] + if len(files) != 1 or type(files[0].get('size_bytes')) is not int \ + or not DIGEST.fullmatch(str(files[0].get('sha256'))): + raise ValueError('lists no single config.json with its size and SHA-256') + return files[0] + + +def catalog_entry(entry): + """catalog.json of a candidate: the entry's ID and input modalities (none listed: text only).""" + modalities = entry.get('input_modalities', []) + if not isinstance(modalities, list) or len(modalities) > MAXIMUM_MODALITIES \ + or not all(isinstance(item, str) and MODALITY.fullmatch(item) for item in modalities): + raise ValueError('input_modalities is not a list of modality names') + return json.dumps({'id': entry['id'], 'input_modalities': modalities}, sort_keys=True, separators=(',', ':')).encode() + + +def candidates(listed, coordinator, cdn, fetch=get): + """({artifact: [(manifest, config, catalog.json bytes)]}, listed models the catalog lacks, failures).""" + entries = catalog(coordinator, fetch) + found, skipped, failures = {}, [], [] + for model in listed: + artifact, kept, notes = model['artifact_sha256'], [], [] + matching = [entry for entry in entries if entry.get('aggregate_sha256') == artifact + and isinstance(entry.get('id'), str) and isinstance(entry.get('r2_prefix'), str)] + if not matching: + skipped.append(model) + continue + for entry in matching: + base = cdn + '/' + r2_path(entry['r2_prefix']) + configuration, entry_kept = None, 0 + try: + entry_file = catalog_entry(entry) + except ValueError as error: + failures.append(f"{entry['id']} ({model['runtime_model_id']}, {artifact}): catalog entry: {error}") + continue + for url in (base + '/manifest.json', + coordinator + '/v1/models/catalog/manifest/' + model_id_path(entry['id'])): + try: + data = fetch(url, MAXIMUM_MANIFEST_BYTES) + item = configuration_entry(data, entry, artifact) + if any(data == manifest for manifest, _, _ in kept): + entry_kept += 1 + continue + if configuration is None: + configuration = fetch(base + '/config.json', MAXIMUM_CONFIGURATION_BYTES) + if len(configuration) != item['size_bytes'] \ + or hashlib.sha256(configuration).hexdigest() != item['sha256']: + raise ValueError("config.json differs from the manifest's size or SHA-256") + kept.append((data, configuration, entry_file)) + entry_kept += 1 + except (FetchError, ValueError) as error: + notes.append(f'{url}: {error}') + if not entry_kept: + failures.append(f"{entry['id']} ({model['runtime_model_id']}, {artifact}): " + '; '.join(notes)) + found[artifact] = kept + return found, skipped, failures + + +def write(found, output): + output.mkdir(parents=True, exist_ok=False) + index = 0 + for artifact in sorted(found): + for manifest, configuration, entry in found[artifact]: + folder = output / f'{index:03d}' + folder.mkdir() + (folder / 'manifest.json').write_bytes(manifest) + (folder / 'config.json').write_bytes(configuration) + (folder / 'catalog.json').write_bytes(entry) + index += 1 + + +def read_list(path): + listed = json.loads(Path(path).read_text()) + if not isinstance(listed, list) or not listed or not all( + isinstance(item, dict) and set(item) == {'runtime_model_id', 'artifact_sha256'} + and isinstance(item['runtime_model_id'], str) and DIGEST.fullmatch(str(item['artifact_sha256'])) + for item in listed): + raise ValueError('The release model list must be a non-empty list of runtime_model_id and artifact_sha256') + return listed + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + parser.add_argument('--environment', choices=ENVIRONMENTS, required=True, + help="The release's environment: its catalog and model CDN are read") + parser.add_argument('--models', type=Path, required=True, + help='Output of darkbloom cluster runtime-facts --list-release-models') + parser.add_argument('--output', type=Path, required=True, help='New folder for the candidate folders') + parser.add_argument('--skipped', type=Path, required=True, + help='New file: one Markdown line per listed model the catalog does not have') + arguments = parser.parse_args(argv) + coordinator, cdn = registry(arguments.environment) + found, skipped, failures = candidates(read_list(arguments.models), coordinator, cdn) + if failures: + for failure in failures: + print(f'::error::No usable catalog metadata for a qualified cluster model: {failure}', file=sys.stderr) + return 1 + lines = [f"- Not in the {arguments.environment} catalog, left out: {model['runtime_model_id']} " + f"(artifact {model['artifact_sha256']})" for model in skipped] + for line in lines: + print(line) + write(found, arguments.output) + with open(arguments.skipped, 'x', encoding='utf-8') as file: + file.write(''.join(line + '\n' for line in lines)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/provider-release-publication.py b/scripts/provider-release-publication.py index 4a43da04f0..d84e651583 100644 --- a/scripts/provider-release-publication.py +++ b/scripts/provider-release-publication.py @@ -23,6 +23,168 @@ class ReadinessPending(RuntimeError): pass +# The cluster runtime facts (darkbloom_cluster_runtime_v2) of the final signed +# app, written by its own `cluster runtime-facts` (ClusterRuntimeApprovalFacts). +# Any environment's payload may carry the block; the release lane adds it only +# when that environment's *_CLUSTER_RUNTIME_ENABLED variable is 'true'. This +# only checks the block; it computes no digest. +CLUSTER_RUNTIME_SCHEMA = 'darkbloom_cluster_runtime_v2' +CLUSTER_RUNTIME_DIGESTS = ('native_runtime_sha256', 'metallib_sha256', 'resource_library_sha256', + 'placement_policy_sha256') +CLUSTER_RUNTIME_MODEL_DIGESTS = ('artifact_sha256', 'capability_sha256', 'profile_sha256', 'resource_policy_sha256') +CLUSTER_MODE_FAMILIES = ('hand_off', 'pipeline', 'pipeline_speculative', 'tensor_parallel') +# ClusterGenerationMode: tensor parallel has no layer cut, every other mode one +# per member boundary (layerCutCount). +CLUSTER_GENERATION_MODES = ('pipeline_v1', 'pipeline_compact_decode_v1', 'phase_split_v1', 'phase_split_mtp_v1', + 'tensor_parallel_v1', 'pipeline_prefill_tensor_decode_v1', 'pipeline_mtp_v1') +CLUSTER_RUNTIME_MAXIMUM_MODELS = 64 +CLUSTER_RUNTIME_MAXIMUM_BYTES = 64 * 1024 +# A derived approval admits two members, so a qualification names two numerics classes. +CLUSTER_DERIVED_MEMBERS = 2 +# Four mode families times two schedules. +CLUSTER_MAXIMUM_QUALIFICATIONS = 8 +CLUSTER_QUALIFICATION_FIELDS = {'schedule', 'numerics_classes', 'cuts', 'mode', 'tensor_parallel_shares', 'promotable', + 'diverged', 'evidence_sha256', 'qualified_at', 'request_envelope'} +CLUSTER_ENVELOPE_FIELDS = {'sampling', 'tools', 'vision', 'video', 'max_prompt_tokens', 'max_output_tokens'} +CLUSTER_MAXIMUM_TOKENS = 1 << 20 +# The instants a coordinator accepts: seconds, an optional fraction, then Z or an offset. +CLUSTER_INSTANT = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,9})?(Z|[+-][0-9]{2}:[0-9]{2})') +# A coordinator derives approvals `release///s<1|2>`, for a +# model with a grant each approval's `/grant`, and for each parity +# qualification `/q`, and refuses at registration +# a block with any derived ID over this bound. +CLUSTER_DERIVED_ID_MAXIMUM_BYTES = 128 +# The coordinator reads a release registration (POST /v1/releases) under this +# limit (MaxReleaseRegisterBodyBytes, applied as http.MaxBytesReader applies +# it); a larger body would be refused only at publish, after staging. +COORDINATOR_REGISTRATION_MAXIMUM_BYTES = 64 * 1024 + + +def is_digest(value): + return isinstance(value, str) and re.fullmatch('[0-9a-f]{64}', value) is not None and value != '0' * 64 + + +def is_integer(value, low, high): + return type(value) is int and low <= value <= high + + +def check_pair_serving_grant(grant): + """A model's pair_serving_grant: null, or exactly its evidence digest and 1 to 4 known families in byte order.""" + if grant is None: + return + if not isinstance(grant, dict) or set(grant) != {'evidence_sha256', 'mode_families'}: + raise ValueError('Invalid cluster_runtime: a pair_serving_grant is not null or exactly ' + 'evidence_sha256 and mode_families') + families = grant['mode_families'] + if not isinstance(families, list) or not families \ + or any(not isinstance(family, str) or family not in CLUSTER_MODE_FAMILIES for family in families) \ + or any(first >= second for first, second in zip(families, families[1:])): + raise ValueError('Invalid cluster_runtime: mode_families must list 1 to 4 known mode families, ' + 'sorted by byte and unique') + + +def check_parity_qualifications(qualifications): + """A model's parity qualifications, as a coordinator validates them for its derived approvals.""" + if not isinstance(qualifications, list) or len(qualifications) > CLUSTER_MAXIMUM_QUALIFICATIONS: + raise ValueError(f'Invalid cluster_runtime: parity_qualifications must be a list of at most ' + f'{CLUSTER_MAXIMUM_QUALIFICATIONS}') + placements = [] + for q in qualifications: + if not isinstance(q, dict) or set(q) != CLUSTER_QUALIFICATION_FIELDS: + raise ValueError('Invalid cluster_runtime: unknown or missing parity qualification fields') + envelope, classes, cuts = q['request_envelope'], q['numerics_classes'], q['cuts'] + if not is_integer(q['schedule'], 1, 2) or q['mode'] not in CLUSTER_GENERATION_MODES \ + or q['tensor_parallel_shares'] is not None \ + or not isinstance(classes, list) or len(classes) != CLUSTER_DERIVED_MEMBERS \ + or not all(isinstance(c, str) and re.fullmatch(r'[\x21-\x7e]{1,64}', c) for c in classes) \ + or not isinstance(cuts, list) or not all(is_integer(cut, 1, 1 << 31) for cut in cuts) \ + or len(cuts) != (0 if q['mode'] == 'tensor_parallel_v1' else len(classes) - 1) \ + or any(first >= second for first, second in zip(cuts, cuts[1:])) \ + or type(q['promotable']) is not bool or type(q['diverged']) is not bool \ + or (q['promotable'] and q['diverged']) \ + or not isinstance(q['qualified_at'], str) or not CLUSTER_INSTANT.fullmatch(q['qualified_at']): + raise ValueError('Invalid cluster_runtime: a parity qualification names another schedule, mode, shares, ' + 'member count, cuts, flags or instant than a derived approval admits') + if not isinstance(envelope, dict) or set(envelope) != CLUSTER_ENVELOPE_FIELDS \ + or not all(type(envelope[key]) is bool for key in ('sampling', 'tools', 'vision', 'video')) \ + or not is_integer(envelope['max_prompt_tokens'], 1, CLUSTER_MAXIMUM_TOKENS) \ + or not is_integer(envelope['max_output_tokens'], 1, CLUSTER_MAXIMUM_TOKENS) \ + or (envelope['video'] and not envelope['vision']): + raise ValueError(f'Invalid cluster_runtime: a request_envelope needs its six fields, 1 to ' + f'{CLUSTER_MAXIMUM_TOKENS} tokens and vision for video') + placement = (q['schedule'], q['mode'], tuple(classes), tuple(cuts)) + if placement in placements: + raise ValueError('Invalid cluster_runtime: two parity qualifications of a model describe one placement') + placements.append(placement) + + +def check_cluster_runtime(block): + if not isinstance(block, dict) or set(block) != {'schema', 'models', *CLUSTER_RUNTIME_DIGESTS} \ + or block['schema'] != CLUSTER_RUNTIME_SCHEMA: + raise ValueError('Invalid cluster_runtime: unknown or missing fields or another schema') + models = block['models'] + if not isinstance(models, list) or not 1 <= len(models) <= CLUSTER_RUNTIME_MAXIMUM_MODELS: + raise ValueError(f'Invalid cluster_runtime: 1 to {CLUSTER_RUNTIME_MAXIMUM_MODELS} models are required') + digests, names = [block[key] for key in CLUSTER_RUNTIME_DIGESTS], [] + for model in models: + if not isinstance(model, dict) \ + or set(model) != {'model', 'pair_serving_grant', 'parity_qualifications', *CLUSTER_RUNTIME_MODEL_DIGESTS}: + raise ValueError('Invalid cluster_runtime: unknown or missing model fields') + if not isinstance(model['model'], str) or re.fullmatch(r'[\x20-\x7e]{1,128}', model['model']) is None: + raise ValueError('Invalid cluster_runtime: a model ID is not 1 to 128 printable ASCII bytes') + names.append(model['model'].encode()) + digests += [model[key] for key in CLUSTER_RUNTIME_MODEL_DIGESTS] + check_pair_serving_grant(model['pair_serving_grant']) + if model['pair_serving_grant'] is not None: + digests.append(model['pair_serving_grant']['evidence_sha256']) + check_parity_qualifications(model['parity_qualifications']) + digests += [q['evidence_sha256'] for q in model['parity_qualifications']] + if not all(is_digest(value) for value in digests): + raise ValueError('Invalid cluster_runtime: a digest is not 64 lowercase hex characters or is zero') + if any(first >= second for first, second in zip(names, names[1:])): + raise ValueError('Invalid cluster_runtime: models must be sorted by model ID and unique') + + +def derived_ids(model, version): + """The IDs a coordinator derives for a model of the block: its approvals, their grants, then one per qualification.""" + approval = f"release/{version}/{model['model']}/s" + ids = [approval + '1', approval + '2'] + if model['pair_serving_grant'] is not None: + ids += [approval + '1/grant', approval + '2/grant'] + counts = {} + for q in model['parity_qualifications']: + counts[q['schedule']] = counts.get(q['schedule'], 0) + 1 + ids.append(f"{approval}{q['schedule']}/q{counts[q['schedule']]}") + return ids + + +def check_cluster_derived_ids(block, version): + """Every ID a coordinator derives from the block fits its bound.""" + if any(len(identifier.encode()) > CLUSTER_DERIVED_ID_MAXIMUM_BYTES + for model in block['models'] for identifier in derived_ids(model, version)): + raise ValueError(f'Invalid cluster_runtime: a derived cluster approval, grant or parity qualification ID exceeds ' + f'{CLUSTER_DERIVED_ID_MAXIMUM_BYTES} bytes') + + +def load_cluster_runtime(path): + data = Path(path).read_bytes() + if len(data) > CLUSTER_RUNTIME_MAXIMUM_BYTES: + raise ValueError('Invalid cluster_runtime: the block exceeds its bound') + + def unique(pairs): + if len({key for key, _ in pairs}) != len(pairs): + raise ValueError('Invalid cluster_runtime: a field is repeated') + return dict(pairs) + try: + block = json.loads(data, object_pairs_hook=unique) + except json.JSONDecodeError as error: + raise ValueError('Invalid cluster_runtime: not JSON') from error + check_cluster_runtime(block) + if data != json.dumps(block, sort_keys=True, separators=(',', ':')).encode(): + raise ValueError('Invalid cluster_runtime: not canonical (keys sorted by byte, no whitespace, no trailing newline)') + return block + + def object_key(payload): return f"releases/v{payload['version']}/artifacts/{payload['bundle_hash']}/{BUNDLE}" @@ -50,6 +212,20 @@ def validate(payload, env): raise ValueError(f'Invalid signed digest: {key}') if payload['url'] != env['R2_PUBLIC_URL'].rstrip('/') + '/' + object_key(payload): raise ValueError('Publication origin or immutable object path changed') + if 'cluster_runtime' in payload: + check_cluster_runtime(payload['cluster_runtime']) + check_cluster_derived_ids(payload['cluster_runtime'], payload['version']) + size = len(registration_body(payload)) + if size > COORDINATOR_REGISTRATION_MAXIMUM_BYTES: + raise ValueError(f'The release registration body is {size} bytes, over the coordinator\'s limit of ' + f'{COORDINATOR_REGISTRATION_MAXIMUM_BYTES} bytes (POST /v1/releases); shorten the release ' + f'notes or the cluster_runtime block') + + +def registration_body(payload): + """The bytes the registration sends: a cluster_runtime block goes in its canonical form (no whitespace; its keys + keep the canonical file's byte order). Without one the body is unchanged.""" + return (json.dumps(payload, separators=(',', ':')) if 'cluster_runtime' in payload else json.dumps(payload)).encode() def release_changelog(env): @@ -68,7 +244,9 @@ def release_changelog(env): return f"Release v{env['VERSION']}" -def prepare(root, bundle, env): +def prepare(root, bundle, env, cluster_runtime=None): + # Read before anything is written: a refused block leaves no publication folder. + block = None if cluster_runtime is None else load_cluster_runtime(cluster_runtime) root.mkdir(parents=True, exist_ok=False) payload = { 'version': env['VERSION'], 'platform': 'macos-arm64', 'backend': 'mlx-swift', @@ -80,6 +258,8 @@ def prepare(root, bundle, env): 'changelog': release_changelog(env), } payload['url'] = env['R2_PUBLIC_URL'].rstrip('/') + '/' + object_key(payload) + if block is not None: + payload['cluster_runtime'] = block validate(payload, env) if sha256(bundle) != payload['bundle_hash']: raise ValueError('Signed bundle changed after final verification') @@ -125,7 +305,7 @@ def coordinator(env, path, payload=None): data = None if payload is not None: headers.update({'Content-Type': 'application/json', 'Authorization': 'Bearer ' + env['RELEASE_KEY']}) - data = json.dumps(payload).encode() + data = registration_body(payload) request = urllib.request.Request(env['COORDINATOR_URL'].rstrip('/') + path, data=data, headers=headers) try: with urllib.request.build_opener(NoRedirect()).open(request, timeout=150) as response: @@ -213,14 +393,18 @@ def main(): parser.add_argument('--artifact-id') parser.add_argument('--artifact-digest') parser.add_argument('--run-id') + parser.add_argument('--cluster-runtime', type=Path, + help='prepare: the cluster runtime facts of the final signed app, sent as cluster_runtime') args = parser.parse_args() + if args.cluster_runtime is not None and args.operation != 'prepare': + parser.error('--cluster-runtime is a prepare option') if args.operation == 'download': download(os.environ['GITHUB_REPOSITORY'], args.artifact_id, args.artifact_digest, args.run_id, args.directory) elif args.operation == 'prepare': if args.bundle is None: parser.error('prepare requires --bundle') - prepare(args.directory, args.bundle, os.environ) + prepare(args.directory, args.bundle, os.environ, args.cluster_runtime) else: globals()[args.operation](args.directory, os.environ) diff --git a/scripts/test-provider-cluster-runtime-models.py b/scripts/test-provider-cluster-runtime-models.py new file mode 100644 index 0000000000..58c4ecaef3 --- /dev/null +++ b/scripts/test-provider-cluster-runtime-models.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python3 +"""The release's model-metadata fetch against a local HTTP registry (no network, no weights).""" +import hashlib +import http.server +import importlib.util +import json +from pathlib import Path +import tempfile +import threading +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location('models', Path(__file__).with_name('provider-cluster-runtime-models.py')) +MODELS = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODELS) + +ARTIFACT = 'a' * 64 +OTHER = 'b' * 64 +CONFIG = b'{"model_type": "qwen3_5"}' + + +def manifest(model_id, aggregate=ARTIFACT, config=CONFIG, created='2026-09-03T00:00:00Z', files=None): + entries = files if files is not None else [ + {'path': 'config.json', 'size_bytes': len(config), 'sha256': hashlib.sha256(config).hexdigest()}, + {'path': 'model.safetensors', 'size_bytes': 10, 'sha256': 'c' * 64}] + return json.dumps({'model_id': model_id, 'aggregate_sha256': aggregate, 'created_at': created, + 'files': entries}).encode() + + +class Registry(http.server.BaseHTTPRequestHandler): + routes = {} + hits = [] + + def do_GET(self): + Registry.hits.append((self.path, self.headers.get('User-Agent'))) + responses = Registry.routes.get(self.path, [(404, b'missing', {})]) + status, body, headers = responses.pop(0) if len(responses) > 1 else responses[0] + self.send_response(status) + for key, value in headers.items(): + self.send_header(key, value) + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +class FetchTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Registry) + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + cls.base = f'http://127.0.0.1:{cls.server.server_address[1]}' + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + Registry.routes, Registry.hits = {}, [] + sleep = patch.object(MODELS.time, 'sleep') + self.sleeps = sleep.start() + self.addCleanup(sleep.stop) + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.coordinator, self.cdn = self.base + '/dev', self.base + '/cdn' + self.listed = [{'runtime_model_id': 'registered_qwen35_9b', 'artifact_sha256': ARTIFACT}] + + def route(self, path, body, status=200, headers=None): + Registry.routes[path] = [(status, body, headers or {})] + + def catalog(self, *entries): + self.route('/dev/v1/models/catalog', json.dumps({'models': list(entries)}).encode()) + + def entry(self, model_id, prefix, aggregate=ARTIFACT, cdn=None, coordinator=None, config=CONFIG, + modalities=('text', 'image')): + """A catalog entry with its CDN manifest, coordinator manifest and config.json.""" + self.route(f'/cdn/{prefix}/manifest.json', cdn if cdn is not None else manifest(model_id, aggregate)) + self.route('/dev/v1/models/catalog/manifest/' + MODELS.model_id_path(model_id), + coordinator if coordinator is not None else manifest(model_id, aggregate, created='other')) + self.route(f'/cdn/{prefix}/config.json', config) + return {'id': model_id, 'r2_prefix': prefix, 'aggregate_sha256': aggregate, 'input_modalities': list(modalities), + 'display_name': 'not copied'} + + def fetch(self, listed=None): + return MODELS.candidates(self.listed if listed is None else listed, self.coordinator, self.cdn) + + def test_both_encodings_of_every_matching_entry_become_candidates_cdn_first(self): + qwen = self.entry('Qwen3.5-9B', 'v2/Qwen3.5-9B--3e3c/2026-09-03-r1') + twin = self.entry('Qwen3.5-9B-copy', 'v2/copy/r1') + self.catalog(qwen, twin, self.entry('other', 'v2/other/r1', aggregate=OTHER)) + found, skipped, failures = self.fetch() + self.assertEqual((skipped, failures), ([], [])) + self.assertEqual([(json.loads(m)['model_id'], json.loads(m)['created_at']) for m, _, _ in found[ARTIFACT]], + [('Qwen3.5-9B', '2026-09-03T00:00:00Z'), ('Qwen3.5-9B', 'other'), + ('Qwen3.5-9B-copy', '2026-09-03T00:00:00Z'), ('Qwen3.5-9B-copy', 'other')]) + self.assertTrue(all(config == CONFIG for _, config, _ in found[ARTIFACT])) + # Each candidate carries its own entry's ID and input modalities, canonical, and nothing else of the entry. + self.assertEqual([entry for _, _, entry in found[ARTIFACT]], + [b'{"id":"Qwen3.5-9B","input_modalities":["text","image"]}'] * 2 + + [b'{"id":"Qwen3.5-9B-copy","input_modalities":["text","image"]}'] * 2) + self.assertFalse(any('/v2/other/' in path for path, _ in Registry.hits)) + self.assertTrue(all(agent == MODELS.USER_AGENT for _, agent in Registry.hits)) + # config.json is fetched once per entry, never a weight file. + self.assertEqual(sum(path.endswith('/config.json') for path, _ in Registry.hits), 2) + self.assertFalse(any('safetensors' in path for path, _ in Registry.hits)) + + def test_identical_encodings_are_kept_once(self): + same = manifest('Qwen3.5-9B') + self.catalog(self.entry('Qwen3.5-9B', 'v2/q/r1', coordinator=same)) + found, skipped, failures = self.fetch() + self.assertEqual((failures, skipped, [m for m, _, _ in found[ARTIFACT]]), ([], [], [same])) + + def test_a_listed_artifact_the_catalog_lacks_is_left_out_and_named(self): + glm = {'runtime_model_id': 'registered_glm53_flash', 'artifact_sha256': OTHER} + self.catalog(self.entry('Qwen3.5-9B', 'v2/q/r1'), {'id': 'no-prefix', 'aggregate_sha256': OTHER}, 'not an entry') + found, skipped, failures = self.fetch(self.listed + [glm]) + self.assertEqual((skipped, failures), ([glm], [])) + self.assertEqual(len(found[ARTIFACT]), 2) + self.assertNotIn(OTHER, found) + # Nothing of the absent model is asked for. + self.assertFalse(any('no-prefix' in path for path, _ in Registry.hits)) + + def test_the_entrys_input_modalities_go_with_its_candidates(self): + for label, modalities, expected in (('image and video', ['text', 'image', 'video'], ['text', 'image', 'video']), + ('text only', ['text'], ['text']), ('none listed', None, [])): + with self.subTest(row=label): + Registry.routes = {} + entry = self.entry('glm-5.3-flash', 'v2/glm/r1') + if modalities is None: + entry.pop('input_modalities') + else: + entry['input_modalities'] = modalities + self.catalog(entry) + found, _, failures = self.fetch() + self.assertEqual(failures, []) + self.assertTrue(all(json.loads(item) == {'id': 'glm-5.3-flash', 'input_modalities': expected} + for _, _, item in found[ARTIFACT])) + for label, modalities in (('not a list', 'text'), ('not strings', [1]), ('empty name', ['']), + ('a space', ['text image']), ('too many', ['m%d' % index for index in range(17)])): + with self.subTest(row=label): + Registry.routes = {} + entry = self.entry('glm-5.3-flash', 'v2/glm/r1') + entry['input_modalities'] = modalities + self.catalog(entry) + found, _, failures = self.fetch() + self.assertEqual(found[ARTIFACT], []) + self.assertEqual(len(failures), 1) + self.assertIn('input_modalities', failures[0]) + + def test_model_ids_and_prefixes_are_escaped_as_the_provider_escapes_them(self): + self.assertEqual(MODELS.model_id_path('EigenLabs/Qwen3.8 27B'), 'EigenLabs%2FQwen3.8%2027B') + self.assertEqual(MODELS.r2_path('v2/A b/r1'), 'v2/A%20b/r1') + self.catalog(self.entry('EigenLabs/Qwen3.8-27B', 'v2/Qwen3.8--x/r1')) + found, _, _ = self.fetch() + self.assertEqual(len(found[ARTIFACT]), 2) + self.assertIn(('/dev/v1/models/catalog/manifest/EigenLabs%2FQwen3.8-27B', MODELS.USER_AGENT), Registry.hits) + + def test_a_manifest_that_does_not_match_is_never_a_candidate(self): + config = CONFIG + rows = { + 'another model': manifest('Other'), + 'another aggregate': manifest('Qwen3.5-9B', aggregate=OTHER), + 'no config.json': manifest('Qwen3.5-9B', files=[{'path': 'a', 'size_bytes': 1, 'sha256': 'c' * 64}]), + 'config.json twice': manifest('Qwen3.5-9B', files=[ + {'path': 'config.json', 'size_bytes': len(config), 'sha256': hashlib.sha256(config).hexdigest()}] * 2), + 'config size not an integer': manifest('Qwen3.5-9B', files=[ + {'path': 'config.json', 'size_bytes': '25', 'sha256': hashlib.sha256(config).hexdigest()}]), + 'config size a boolean': manifest('Qwen3.5-9B', files=[ + {'path': 'config.json', 'size_bytes': True, 'sha256': hashlib.sha256(config).hexdigest()}]), + 'config digest malformed': manifest('Qwen3.5-9B', files=[ + {'path': 'config.json', 'size_bytes': len(config), 'sha256': 'X' * 64}]), + 'config size differs': manifest('Qwen3.5-9B', config=config + b' '), + 'config digest differs': manifest('Qwen3.5-9B', files=[ + {'path': 'config.json', 'size_bytes': len(config), 'sha256': 'd' * 64}]), + 'not JSON': b'{', + 'not an object': b'[]', + } + for label, body in rows.items(): + with self.subTest(row=label): + Registry.routes = {} + self.catalog(self.entry('Qwen3.5-9B', 'v2/q/r1', cdn=body, coordinator=body)) + found, skipped, failures = self.fetch() + self.assertEqual((found[ARTIFACT], skipped), ([], [])) + self.assertEqual(len(failures), 1) + self.assertTrue(failures[0].startswith(f'Qwen3.5-9B (registered_qwen35_9b, {ARTIFACT}): ')) + + def test_every_catalog_entry_of_a_listed_artifact_needs_a_usable_manifest(self): + # One entry of the artifact answers, the other does not: the second fails by name. + good = self.entry('Qwen3.5-9B', 'v2/q/r1') + self.catalog(good, {'id': 'Qwen3.5-9B-copy', 'r2_prefix': 'v2/copy/r1', 'aggregate_sha256': ARTIFACT}) + found, _, failures = self.fetch() + self.assertEqual(len(found[ARTIFACT]), 2) + self.assertEqual(len(failures), 1) + self.assertTrue(failures[0].startswith('Qwen3.5-9B-copy (registered_qwen35_9b, ')) + self.assertIn('HTTP 404', failures[0]) + + def test_server_errors_are_retried_and_client_errors_are_not(self): + url = self.base + '/flaky' + Registry.routes['/flaky'] = [(503, b'', {}), (200, b'ok', {})] + self.assertEqual(MODELS.get(url, 10), b'ok') + Registry.routes['/down'] = [(500, b'', {})] + with self.assertRaisesRegex(MODELS.FetchError, 'HTTP 500'): + MODELS.get(self.base + '/down', 10) + self.assertEqual(sum(path == '/down' for path, _ in Registry.hits), MODELS.ATTEMPTS) + with self.assertRaisesRegex(MODELS.FetchError, 'HTTP 404'): + MODELS.get(self.base + '/missing', 10) + self.assertEqual(sum(path == '/missing' for path, _ in Registry.hits), 1) + + def test_redirects_oversize_bodies_and_unreachable_hosts_are_refused(self): + self.route('/moved', b'', status=302, headers={'Location': self.base + '/elsewhere'}) + with self.assertRaisesRegex(MODELS.FetchError, 'redirect'): + MODELS.get(self.base + '/moved', 10) + self.route('/large', b'x' * 11) + with self.assertRaisesRegex(MODELS.FetchError, 'more than 10 bytes'): + MODELS.get(self.base + '/large', 10) + closed = http.server.HTTPServer(('127.0.0.1', 0), Registry) + port = closed.server_address[1] + closed.server_close() + with self.assertRaises(MODELS.FetchError): + MODELS.get(f'http://127.0.0.1:{port}/', 10) + self.assertEqual(self.sleeps.call_count, MODELS.ATTEMPTS - 1) + + def test_an_unreadable_or_unreachable_catalog_stops_the_fetch(self): + for body in (b'{', b'{"models": {}}', b'[]'): + with self.subTest(body=body): + self.route('/dev/v1/models/catalog', body) + with self.assertRaisesRegex(MODELS.FetchError, 'unreadable model catalog'): + self.fetch() + Registry.routes = {} + with self.assertRaisesRegex(MODELS.FetchError, 'HTTP 404'): + self.fetch() + + def test_the_model_list_is_checked(self): + for listed in ([], {}, [{'runtime_model_id': 'x'}], + [{'runtime_model_id': 'x', 'artifact_sha256': 'A' * 64}], + [{'runtime_model_id': 1, 'artifact_sha256': ARTIFACT}], + [{'runtime_model_id': 'x', 'artifact_sha256': ARTIFACT, 'extra': 1}]): + with self.subTest(listed=listed): + path = self.root / 'list.json' + path.write_text(json.dumps(listed)) + with self.assertRaisesRegex(ValueError, 'release model list'): + MODELS.read_list(path) + + def test_each_environment_reads_its_own_catalog_and_cdn(self): + self.assertEqual(MODELS.registry('dev'), ('https://api.dev.darkbloom.dev', 'https://models.darkbloom.ai')) + self.assertEqual(MODELS.registry('staging'), ('https://api.staging.darkbloom.dev', 'https://models.darkbloom.ai')) + self.assertEqual(MODELS.registry('prod'), ('https://api.darkbloom.dev', 'https://models.darkbloom.ai')) + identity = self.root / 'identity.json' + identity.write_text(json.dumps({'environments': {'dev': {'coordinatorHTTPURL': 'https://one/', + 'modelCDNURL': 'https://cdn/'}}})) + self.assertEqual(MODELS.registry('dev', identity), ('https://one', 'https://cdn')) + with self.assertRaisesRegex(ValueError, 'Unknown environment'): + MODELS.registry('local') + + def test_main_writes_candidates_and_the_left_out_models_or_fails_without_writing(self): + self.catalog(self.entry('Qwen3.5-9B', 'v2/q/r1')) + listed = self.root / 'list.json' + absent = {'runtime_model_id': 'registered_glm53_flash', 'artifact_sha256': OTHER} + listed.write_text(json.dumps(self.listed + [absent])) + output, skipped = self.root / 'candidates', self.root / 'skipped.md' + arguments = ['--environment', 'dev', '--models', str(listed), '--output', str(output), '--skipped', str(skipped)] + with patch.object(MODELS, 'registry', return_value=(self.coordinator, self.cdn)) as registry, \ + patch('sys.stdout') as stdout: + self.assertEqual(MODELS.main(arguments), 0) + registry.assert_called_once_with('dev') + self.assertEqual(sorted(p.name for p in output.iterdir()), ['000', '001']) + for folder in output.iterdir(): + self.assertEqual(sorted(path.name for path in folder.iterdir()), ['catalog.json', 'config.json', 'manifest.json']) + self.assertEqual((folder / 'config.json').read_bytes(), CONFIG) + self.assertEqual(json.loads((folder / 'manifest.json').read_bytes())['aggregate_sha256'], ARTIFACT) + self.assertEqual((folder / 'catalog.json').read_bytes(), b'{"id":"Qwen3.5-9B","input_modalities":["text","image"]}') + line = f'- Not in the dev catalog, left out: registered_glm53_flash (artifact {OTHER})\n' + self.assertEqual(skipped.read_text(), line) + self.assertIn(line.strip(), ''.join(call.args[0] for call in stdout.write.call_args_list)) + # A failure writes neither folder nor list. + Registry.routes = {} + self.catalog({'id': 'Qwen3.5-9B', 'r2_prefix': 'v2/q/r1', 'aggregate_sha256': ARTIFACT}) + refused = ['--environment', 'dev', '--models', str(listed), '--output', str(self.root / 'refused'), + '--skipped', str(self.root / 'refused.md')] + with patch.object(MODELS, 'registry', return_value=(self.coordinator, self.cdn)), patch('sys.stderr') as stderr: + self.assertEqual(MODELS.main(refused), 1) + self.assertFalse((self.root / 'refused').exists()) + self.assertFalse((self.root / 'refused.md').exists()) + self.assertIn('Qwen3.5-9B (registered_qwen35_9b', ''.join(call.args[0] for call in stderr.write.call_args_list)) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-provider-release-pipeline.py b/scripts/test-provider-release-pipeline.py index 8dd8b548d8..45a3998cfa 100644 --- a/scripts/test-provider-release-pipeline.py +++ b/scripts/test-provider-release-pipeline.py @@ -13,6 +13,15 @@ RELEASE = (ROOT / '.github/workflows/release-provider.yml').read_text() WARM = (ROOT / '.github/workflows/provider-release-cache.yml').read_text() ACTION = (ROOT / '.github/actions/provider-release-build/action.yml').read_text() +FACTS_SCRIPT = (ROOT / 'scripts/provider-cluster-runtime-facts.sh').read_text() +FACTS_STEP = '- name: Compute cluster runtime facts from the final signed app\n' +SHOW_STEP = '- name: Show the cluster runtime facts\n' +RETAIN_STEP = '- name: Retain the cluster runtime facts\n' + + +def step(content, name): + """The body of the step that starts with `name`, up to the next step.""" + return content.split(name, 1)[1].split('\n - name:', 1)[0].split('\n # ', 1)[0] def caller_lanes(): @@ -197,7 +206,13 @@ def test_signing_requires_both_sdk_lanes_without_environment_approval(self): self.assertIn('needs: [resolve-env, build-provider, qualify-sdk]', content) self.assertNotRegex(content, r'(?m)^ environment:') self.assertNotRegex(content, r'(?m)^ if:.*always') - self.assertNotIn('continue-on-error:', RELEASE) + # Every release step is required. The only exceptions are the cluster + # runtime facts steps: their failure fails the job only when the + # payload carries the block (CLUSTER_RUNTIME_SEND). + self.assertEqual(RELEASE.count('continue-on-error:'), 3) + self.assertIn("continue-on-error: ${{ env.CLUSTER_RUNTIME_SEND != 'true' }}\n", step(content, FACTS_STEP)) + for name in (SHOW_STEP, RETAIN_STEP): + self.assertIn('continue-on-error: true\n', step(content, name)) self.assertNotIn('continue-on-error:', ACTION) self.assertIn('needs: [resolve-env, build-and-release]', job(RELEASE, 'validate-older-macos')) @@ -443,6 +458,114 @@ def test_dev_and_staging_artifacts_avoid_collision_but_prod_stays_unqualified(se self.assertNotIn('provider-sdk-test-diagnostics--', ACTION) self.assertNotRegex(WARM, r'(?m)^\s+environment:') + def test_cluster_runtime_facts_come_from_the_final_signed_app_without_secrets(self): + sign = job(RELEASE, 'build-and-release') + facts = step(sign, FACTS_STEP) + # Every lane and every run: no condition of its own. + self.assertNotIn('\n if:', facts) + # After signing, notarization, the final tar and its hashes; before the + # payload is prepared and the keychain is cleaned up. + self.assertLess(sign.index('xcrun notarytool submit'), sign.index(FACTS_STEP)) + self.assertLess(sign.index('echo "BUNDLE_HASH=$BUNDLE_HASH"'), sign.index(FACTS_STEP)) + for later in ('- name: Record signed validation identity', '- name: Prepare exact signed release identity', + '- name: Cleanup keychain'): + self.assertLess(sign.index(FACTS_STEP), sign.index(later)) + # No secret: none referenced, the two secret-derived GITHUB_ENV values + # and the signing keychain removed before release code runs, which then + # runs with an empty environment. + self.assertNotIn('secrets.', facts) + self.assertNotIn('\n env:', facts) + first_run = facts.index('scripts/provider-cluster-runtime-facts.sh "$FACTS_ROOT/app/$APP_NAME" "$CLI_NAME" ' + '"$ENV_PREFIX" "$FACTS_ROOT/facts"') + for removal in ('unset r2_public_url coordinator_url', 'security delete-keychain "$KEYCHAIN_PATH"\n', + 'test ! -e "$KEYCHAIN_PATH"', 'IDENTITIES=$(security find-identity -p codesigning)', + 'if grep -F -q -- "$DEVELOPER_ID" <<< "$IDENTITIES"; then'): + self.assertLess(facts.index(removal), first_run) + # A keychain that cannot be deleted, or an identity still listed, fails the step. + self.assertNotIn('|| true', facts) + self.assertNotIn('2>/dev/null', facts) + # Every identity, not only valid ones: a revoked or expired key left behind is found too. + self.assertNotIn('find-identity -v', facts) + self.assertLess(facts.index('security delete-keychain'), facts.index('IDENTITIES=')) + # The final archived bytes, extracted afresh after their hash is checked. + self.assertLess(facts.index('= "$BUNDLE_HASH"'), facts.index('tar -xzf /tmp/darkbloom-bundle-macos-arm64.tar.gz')) + self.assertLess(facts.index('tar -xzf /tmp/darkbloom-bundle-macos-arm64.tar.gz'), first_run) + # A hang ends the step; with the block unsent its failure only warns. + self.assertIn('timeout-minutes: 20\n', facts) + # The shared script: the app's own CLI only ever runs with an empty + # environment, and the metadata comes from the release's environment. + self.assertTrue(FACTS_SCRIPT.startswith('#!/usr/bin/env bash\n') and 'set -euo pipefail\n' in FACTS_SCRIPT) + self.assertEqual(FACTS_SCRIPT.count('/Contents/MacOS/'), 1) + self.assertIn(' env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin HOME="$root/home" DARKBLOOM_NO_UPDATE_CHECK=1 \\\n' + ' "$app/Contents/MacOS/$cli" cluster runtime-facts "$@"\n', FACTS_SCRIPT) + fetch = 'python3 "$scripts/provider-cluster-runtime-models.py" --environment "$environment"' + self.assertLess(FACTS_SCRIPT.index('runtime_facts --list-release-models'), FACTS_SCRIPT.index(fetch)) + self.assertLess(FACTS_SCRIPT.index(fetch), + FACTS_SCRIPT.index('runtime_facts --app "$app" --release-candidates "$root/candidates"')) + # Any failure fails the script: no swallowed status, no required list. + for soft in ('|| status', '|| true', '--require-model', '2>'): + self.assertNotIn(soft, FACTS_SCRIPT) + + def test_cluster_runtime_is_sent_only_when_the_environment_variable_is_true(self): + sign = job(RELEASE, 'build-and-release') + switch = sign.split(' CLUSTER_RUNTIME_SEND: >-\n', 1)[1].split('\n\n', 1)[0] + self.assertEqual(' '.join(switch.split()), + "${{ needs.resolve-env.outputs.publish == 'true' && " + "((needs.resolve-env.outputs.environment == 'dev' && vars.DEV_CLUSTER_RUNTIME_ENABLED == 'true') || " + "(needs.resolve-env.outputs.environment == 'staging' && vars.STAGING_CLUSTER_RUNTIME_ENABLED == 'true') || " + "(needs.resolve-env.outputs.environment == 'prod' && vars.PROD_CLUSTER_RUNTIME_ENABLED == 'true')) }}") + for variable in ('DEV', 'STAGING', 'PROD'): + self.assertEqual(RELEASE.count(f'vars.{variable}_CLUSTER_RUNTIME_ENABLED'), 1) + self.assertEqual(RELEASE.count('CLUSTER_RUNTIME_SEND: >-'), 1) + # The facts step names the file for prepare only when the block is sent. + self.assertEqual(RELEASE.count('CLUSTER_RUNTIME_FILE='), 1) + self.assertIn(' if [ "$CLUSTER_RUNTIME_SEND" = true ]; then\n' + ' echo "CLUSTER_RUNTIME_FILE=$FACTS_ROOT/facts/cluster-runtime.json" >> "$GITHUB_ENV"\n' + ' fi\n', step(sign, FACTS_STEP)) + # Prepare: with the switch off, today's command byte for byte; with it + # on, the facts are required and passed. + prepare = step(sign, '- name: Prepare exact signed release identity\n') + today = ('python3 scripts/provider-release-publication.py prepare \\\n' + ' --directory "$RUNNER_TEMP/provider-publication" --bundle /tmp/darkbloom-bundle-macos-arm64.tar.gz\n') + on, off = prepare.split(' if [ "$CLUSTER_RUNTIME_SEND" = true ]; then\n', 1)[1].split(' else\n', 1) + off = off.split(' fi\n', 1)[0] + self.assertEqual(off, ' ' + today) + self.assertIn('test -s "${CLUSTER_RUNTIME_FILE:-}"\n', on) + self.assertLess(on.index('test -s'), on.index('prepare')) + self.assertIn('--cluster-runtime "$CLUSTER_RUNTIME_FILE"\n', on) + self.assertEqual(RELEASE.count('--cluster-runtime'), 1) + + def test_cluster_runtime_facts_are_always_shown_and_retained(self): + sign = job(RELEASE, 'build-and-release') + for name in (SHOW_STEP, RETAIN_STEP): + with self.subTest(step=name): + content = step(sign, name) + # They also run when the facts step failed, and never fail the job. + self.assertIn("if: ${{ !cancelled() && (steps.cluster_runtime.outcome == 'success' || " + "steps.cluster_runtime.outcome == 'failure') }}\n", content) + self.assertNotIn('secrets.', content) + self.assertLess(sign.index(FACTS_STEP), sign.index(name)) + self.assertLess(sign.index(name), sign.index('- name: Prepare exact signed release identity')) + self.assertIn(' id: cluster_runtime\n', step(sign, FACTS_STEP)) + show = step(sign, SHOW_STEP) + self.assertIn('>> "$GITHUB_STEP_SUMMARY"', show) + self.assertIn('python3 -m json.tool --sort-keys "$FACTS/cluster-runtime.json"', show) + self.assertIn('cat "$FACTS/skipped.md"', show) + retain = step(sign, RETAIN_STEP) + self.assertIn('uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a', retain) + # Lanes of one run never collide. + self.assertIn('name: cluster-runtime-${{ needs.resolve-env.outputs.environment }}-' + '${{ needs.resolve-env.outputs.source_sha }}-${{ github.run_attempt }}\n', retain) + self.assertIn('${{ runner.temp }}/cluster-runtime/facts/cluster-runtime.json\n', retain) + self.assertIn('if-no-files-found: warn\n', retain) + + def test_the_cluster_runtime_scripts_start_the_release_lanes(self): + # The facts script runs the fetch script; a change to either starts + # both push lanes, like every other script a release runs. + for caller in (CALLER, (ROOT / '.github/workflows/release-dev-branch.yml').read_text()): + for script in ('scripts/provider-cluster-runtime-models.py', 'scripts/provider-cluster-runtime-facts.sh'): + self.assertIn(f" - '{script}'\n", caller) + if __name__ == '__main__': unittest.main() diff --git a/scripts/test-provider-release-publication.py b/scripts/test-provider-release-publication.py index a77b1e4bfe..9049591828 100644 --- a/scripts/test-provider-release-publication.py +++ b/scripts/test-provider-release-publication.py @@ -305,6 +305,358 @@ def test_tag_annotation_is_retained_as_data_not_executable_code(self): self.assertEqual(PUB.release_changelog(dict(env, GITHUB_REF_TYPE='branch')), 'Release v0.9.8') +GLM_BLOCK = (Path(__file__).resolve().parent.parent + / 'provider-swift/Tests/ProviderCoreTests/Fixtures/ClusterRuntime/glm-5.3-flash-dev-branch17.json') +ALL_FAMILIES = ['hand_off', 'pipeline', 'pipeline_speculative', 'tensor_parallel'] + + +def qualification(schedule, mode='tensor_parallel_v1', cuts=(), media=True): + return {'schedule': schedule, 'numerics_classes': ['g17d-nax1-mlx-22222222-macos27.0'] * 2, 'cuts': list(cuts), + 'mode': mode, 'tensor_parallel_shares': None, 'promotable': True, 'diverged': False, + 'evidence_sha256': 'f' * 64, 'qualified_at': '2026-10-31T00:00:00Z', + 'request_envelope': {'sampling': True, 'tools': True, 'vision': media, 'video': media, + 'max_prompt_tokens': 1048576, 'max_output_tokens': 1048576}} + + +def cluster_runtime_block(): + """The 27B declared (a grant of its two families; the pipeline's qualifications, text only, then tensor + parallel's), the 9B with a grant from records only, GLM with neither.""" + def model(name, seed, grant=None, qualifications=()): + return {'model': name, 'artifact_sha256': seed * 64, 'capability_sha256': 'c' * 64, 'pair_serving_grant': grant, + 'parity_qualifications': list(qualifications), 'profile_sha256': 'd' * 64, 'resource_policy_sha256': 'e' * 64} + declared = [qualification(1, 'pipeline_v1', [32], media=False), qualification(2, 'pipeline_v1', [32], media=False), + qualification(1), qualification(2)] + return {'schema': 'darkbloom_cluster_runtime_v2', 'native_runtime_sha256': '1' * 64, + 'metallib_sha256': '2' * 64, 'resource_library_sha256': '3' * 64, + 'placement_policy_sha256': '4' * 64, + 'models': [model('EigenLabs/Qwen3.8-27B-4bit-mtp', '5', + {'evidence_sha256': 'f' * 64, 'mode_families': ['pipeline', 'tensor_parallel']}, declared), + model('Qwen3.5-9B', '6', {'evidence_sha256': 'a' * 64, 'mode_families': list(ALL_FAMILIES)}), + model('glm-5.3-flash', '7')]} + + +class ClusterRuntimeTests(PublicationFixture): + # The payloads of PublicationFixture (prod) and of its dev twin, byte for + # byte as the release lane wrote them before cluster_runtime existed: a + # release without the block is unchanged in every environment. + PROD_PAYLOAD_SHA256 = 'f864c569d555a574a8499160cb2a815d5d54ce2ac73294e690e16a44cf999758' + DEV_PAYLOAD_SHA256 = 'f8d464b44d74957419bb800386735647891775bb1cfc5bc70db794033bd07e50' + + def dev_env(self): + return dict(self.env, ENV_PREFIX='dev', VERSION='0.9.8-dev.branch.7') + + def write_block(self, block, name='cluster-runtime.json'): + path = self.base / name + path.write_text(block if isinstance(block, str) else json.dumps(block, sort_keys=True, separators=(',', ':'))) + return path + + def test_payload_bytes_are_unchanged_without_the_block(self): + self.assertNotIn('cluster_runtime', self.payload) + self.assertEqual(PUB.sha256(self.root / 'release-payload.json'), self.PROD_PAYLOAD_SHA256) + root = self.base / 'dev' + payload = PUB.prepare(root, self.root / PUB.BUNDLE, self.dev_env()) + self.assertNotIn('cluster_runtime', payload) + self.assertEqual(PUB.sha256(root / 'release-payload.json'), self.DEV_PAYLOAD_SHA256) + + def test_every_environment_carries_a_valid_block_through_stage(self): + # Staging is refused before and after this block ("Unknown publication environment"). + for env in (self.dev_env(), dict(self.env, VERSION='0.9.9')): + with self.subTest(environment=env['ENV_PREFIX']): + block, root = cluster_runtime_block(), self.base / env['ENV_PREFIX'] + payload = PUB.prepare(root, self.root / PUB.BUNDLE, env, self.write_block(block)) + self.assertEqual(payload['cluster_runtime'], block) + self.assertEqual(list(payload)[-1], 'cluster_runtime') + written = json.loads((root / 'release-payload.json').read_text()) + self.assertEqual(written['cluster_runtime'], block) + # Every other field is the payload without the block. + without = PUB.prepare(self.base / (env['ENV_PREFIX'] + '-without'), self.root / PUB.BUNDLE, env) + self.assertEqual({key: value for key, value in written.items() if key != 'cluster_runtime'}, without) + env.update(RELEASE_PAYLOAD_SHA256=PUB.sha256(root / 'release-payload.json'), + RELEASE_PROVENANCE_SHA256=PUB.sha256(root / 'release-provenance.json')) + with patch.object(PUB, 'upload') as upload: + PUB.stage(root, env) + upload.assert_called_once() + with self.assertRaisesRegex(ValueError, 'Unknown publication environment'): + PUB.prepare(self.base / 'staging', self.root / PUB.BUNDLE, dict(self.env, ENV_PREFIX='staging'), + self.write_block(cluster_runtime_block())) + + def test_registration_sends_the_block_in_its_canonical_form(self): + def sent(env, payload): + with patch.object(PUB.urllib.request, 'build_opener') as opener: + opener.return_value.open.return_value.__enter__.return_value.read.return_value = b'{}' + PUB.coordinator(env, '/v1/releases', payload) + return opener.return_value.open.call_args.args[0].data + # Read back from the retained payload, as publish does. + root = self.base / 'dev' + PUB.prepare(root, self.root / PUB.BUNDLE, self.dev_env(), self.write_block(cluster_runtime_block())) + env = dict(self.dev_env(), RELEASE_PAYLOAD_SHA256=PUB.sha256(root / 'release-payload.json'), + RELEASE_PROVENANCE_SHA256=PUB.sha256(root / 'release-provenance.json')) + body = sent(env, PUB.checked_payload(root, env)) + self.assertEqual(json.loads(body)['cluster_runtime'], cluster_runtime_block()) + canonical = json.dumps(cluster_runtime_block(), sort_keys=True, separators=(',', ':')).encode() + self.assertIn(b'"cluster_runtime":' + canonical + b'}', body) + # Without the block, the body is the one sent before cluster_runtime existed. + self.assertEqual(sent(self.env, self.payload), json.dumps(self.payload).encode()) + + def test_a_block_that_is_not_canonical_is_refused(self): + block = cluster_runtime_block() + for label, text in {'whitespace': json.dumps(block, sort_keys=True), + 'trailing newline': json.dumps(block, sort_keys=True, separators=(',', ':')) + '\n', + 'unsorted keys': json.dumps(dict(reversed(list(block.items()))), separators=(',', ':'))}.items(): + with self.subTest(row=label), self.assertRaisesRegex(ValueError, 'not canonical'): + PUB.prepare(self.base / label, self.root / PUB.BUNDLE, self.dev_env(), self.write_block(text)) + self.assertFalse((self.base / label).exists()) + + def test_malformed_block_is_refused(self): + def edited(change): + block = cluster_runtime_block() + change(block) + return block + many = [dict(cluster_runtime_block()['models'][1], model=f'model-{index:02d}') for index in range(65)] + def edited_q(change, index=0): + return edited(lambda b: change(b['models'][0]['parity_qualifications'][index])) + + def edited_envelope(change): + return edited_q(lambda q: change(q['request_envelope'])) + + def edited_grant(change): + return edited(lambda b: change(b['models'][0]['pair_serving_grant'])) + rows = { + 'unknown field': edited(lambda b: b.update(extra='x')), + 'missing field': edited(lambda b: b.pop('metallib_sha256')), + 'schema v1': edited(lambda b: b.update(schema='darkbloom_cluster_runtime_v1')), + 'unknown model field': edited(lambda b: b['models'][0].update(extra='x')), + 'missing model field': edited(lambda b: b['models'][0].pop('profile_sha256')), + 'no pair_serving_grant': edited(lambda b: b['models'][2].pop('pair_serving_grant')), + 'grant a string': edited(lambda b: b['models'][2].update(pair_serving_grant='pipeline')), + 'grant a list': edited(lambda b: b['models'][2].update(pair_serving_grant=['pipeline'])), + 'grant empty': edited(lambda b: b['models'][2].update(pair_serving_grant={})), + 'unknown grant field': edited_grant(lambda g: g.update(granted_at='2026-10-31T00:00:00Z')), + 'missing grant field': edited_grant(lambda g: g.pop('mode_families')), + 'families not a list': edited_grant(lambda g: g.update(mode_families='pipeline')), + 'no mode family': edited_grant(lambda g: g.update(mode_families=[])), + 'unknown mode family': edited_grant(lambda g: g.update(mode_families=['pipeline_mtp'])), + 'mode families unsorted': edited_grant(lambda g: g.update(mode_families=['tensor_parallel', 'pipeline'])), + 'mode family repeated': edited_grant(lambda g: g.update(mode_families=['pipeline', 'pipeline'])), + 'family not a string': edited_grant(lambda g: g.update(mode_families=[1])), + 'zero grant evidence': edited_grant(lambda g: g.update(evidence_sha256='0' * 64)), + 'uppercase grant evidence': edited_grant(lambda g: g.update(evidence_sha256='F' * 64)), + 'grant evidence not a string': edited_grant(lambda g: g.update(evidence_sha256=7)), + 'no parity_qualifications': edited(lambda b: b['models'][1].pop('parity_qualifications')), + 'qualifications null': edited(lambda b: b['models'][1].update(parity_qualifications=None)), + 'qualification a string': edited(lambda b: b['models'][1].update(parity_qualifications=['tensor_parallel'])), + 'nine qualifications': edited(lambda b: b['models'][1].update(parity_qualifications=[ + dict(qualification(1), numerics_classes=[f'c{index}'] * 2) for index in range(9)])), + 'unknown qualification field': edited_q(lambda q: q.update(id='q1')), + 'missing qualification field': edited_q(lambda q: q.pop('qualified_at')), + 'shares absent': edited_q(lambda q: q.pop('tensor_parallel_shares')), + 'shares not null': edited_q(lambda q: q.update(tensor_parallel_shares={'version': 1, 'per_mille': [500, 500]})), + 'schedule 3': edited_q(lambda q: q.update(schedule=3)), + 'schedule true': edited_q(lambda q: q.update(schedule=True)), + 'schedule a string': edited_q(lambda q: q.update(schedule='1')), + 'unknown mode': edited_q(lambda q: q.update(mode='tensor_parallel_v9')), + 'one numerics class': edited_q(lambda q: q.update(numerics_classes=['g17d'])), + 'three numerics classes': edited_q(lambda q: q.update(numerics_classes=['a', 'b', 'c'])), + 'empty numerics class': edited_q(lambda q: q.update(numerics_classes=['', 'b'])), + 'numerics class not a string': edited_q(lambda q: q.update(numerics_classes=[1, 2])), + 'tensor parallel with a cut': edited_q(lambda q: q.update(mode='tensor_parallel_v1', cuts=[8])), + 'pipeline without a cut': edited_q(lambda q: q.update(mode='pipeline_v1', cuts=[])), + 'zero cut': edited_q(lambda q: q.update(mode='pipeline_v1', cuts=[0])), + 'cut not an integer': edited_q(lambda q: q.update(mode='pipeline_v1', cuts=[8.0])), + 'promotable a number': edited_q(lambda q: q.update(promotable=1)), + 'diverged and promotable': edited_q(lambda q: q.update(diverged=True)), + 'zero evidence': edited_q(lambda q: q.update(evidence_sha256='0' * 64)), + 'uppercase evidence': edited_q(lambda q: q.update(evidence_sha256='F' * 64)), + 'not an instant': edited_q(lambda q: q.update(qualified_at='2026-10-31')), + 'unknown envelope field': edited_envelope(lambda e: e.update(logprobs=True)), + 'missing envelope field': edited_envelope(lambda e: e.pop('video')), + 'video without vision': edited_envelope(lambda e: e.update(vision=False, video=True)), + 'no prompt tokens': edited_envelope(lambda e: e.update(max_prompt_tokens=0)), + 'too many output tokens': edited_envelope(lambda e: e.update(max_output_tokens=1048577)), + 'sampling a number': edited_envelope(lambda e: e.update(sampling=1)), + 'a placement twice': edited(lambda b: b['models'][0]['parity_qualifications'].append(qualification(1))), + 'uppercase digest': edited(lambda b: b.update(native_runtime_sha256='A' * 64)), + 'short digest': edited(lambda b: b['models'][1].update(capability_sha256='c' * 63)), + 'zero digest': edited(lambda b: b['models'][1].update(resource_policy_sha256='0' * 64)), + 'digest not a string': edited(lambda b: b.update(placement_policy_sha256=1)), + 'no models': edited(lambda b: b.update(models=[])), + 'models not a list': edited(lambda b: b.update(models={})), + 'model not an object': edited(lambda b: b['models'].append('glm')), + 'too many models': edited(lambda b: b.update(models=many)), + 'unsorted models': edited(lambda b: b['models'].reverse()), + 'repeated model': edited(lambda b: b['models'].append(dict(b['models'][-1]))), + 'empty model ID': edited(lambda b: b['models'][0].update(model='')), + 'long model ID': edited(lambda b: b['models'][0].update(model='A' * 129)), + 'non-ASCII model ID': edited(lambda b: b['models'][0].update(model='Qwené')), + 'control byte in model ID': edited(lambda b: b['models'][0].update(model='A\n')), + 'model ID not a string': edited(lambda b: b['models'][0].update(model=7)), + 'block not an object': [], + } + for label, block in rows.items(): + with self.subTest(row=label): + for env in (self.dev_env(), self.env): + with self.assertRaisesRegex(ValueError, 'Invalid cluster_runtime'): + PUB.prepare(self.base / (label + env['ENV_PREFIX']), self.root / PUB.BUNDLE, env, + self.write_block(block)) + self.assertFalse((self.base / (label + env['ENV_PREFIX'])).exists()) + with self.assertRaisesRegex(ValueError, 'Invalid cluster_runtime'): + PUB.check_cluster_runtime(block) + with self.assertRaisesRegex(ValueError, 'Invalid cluster_runtime'): + PUB.validate(dict(self.payload, cluster_runtime=block), self.env) + text = json.dumps(cluster_runtime_block()) + for label, data in {'repeated field': text[:-1] + ', "schema": "darkbloom_cluster_runtime_v2"}', + 'repeated grant field': text.replace('"evidence_sha256"', '"mode_families": [], "evidence_sha256"', 1), + 'repeated qualification field': text.replace('"cuts"', '"schedule": 1, "cuts"', 1), + 'over its bound': text + ' ' * (64 * 1024), 'not JSON': text[:-1]}.items(): + with self.subTest(row=label), self.assertRaisesRegex(ValueError, 'Invalid cluster_runtime'): + PUB.prepare(self.base / label, self.root / PUB.BUNDLE, self.dev_env(), self.write_block(data)) + + def test_a_block_whose_derived_ids_exceed_128_bytes_is_refused_before_staging(self): + # release///s2 with version 0.9.8-dev.branch.7: 30 bytes plus the model ID; a grant's ID + # adds 6 more (/grant), a parity qualification's 3 (/q1, /q2). + env = self.dev_env() + self.assertEqual(len(f"release/{env['VERSION']}/{'m' * 98}/s2".encode()), 128) + template = cluster_runtime_block()['models'] + refused = 'derived cluster approval, grant or parity qualification ID exceeds 128 bytes' + for label, base, fits in (('neither', template[2], 98), ('qualifications', dict(template[0], pair_serving_grant=None), 95), + ('a grant', template[1], 92), ('a grant and qualifications', template[0], 92)): + with self.subTest(row=label): + block, over = cluster_runtime_block(), cluster_runtime_block() + block['models'] = [dict(base, model='m' * fits)] + over['models'] = [dict(base, model='m' * (fits + 1))] + payload = PUB.prepare(self.base / ('fits ' + label), self.root / PUB.BUNDLE, env, + self.write_block(block, 'fits.json')) + self.assertEqual(payload['cluster_runtime'], block) + with self.assertRaisesRegex(ValueError, refused), patch.object(PUB, 'upload') as upload: + PUB.prepare(self.base / ('over ' + label), self.root / PUB.BUNDLE, env, self.write_block(over, 'over.json')) + upload.assert_not_called() + self.assertFalse((self.base / ('over ' + label) / 'release-payload.json').exists()) + with self.assertRaisesRegex(ValueError, refused): + PUB.validate(dict(payload, cluster_runtime=over), env) + # One grant per approval; n counts each schedule's qualifications from 1 in block order: q1 the pipeline, + # q2 tensor parallel. + self.assertEqual(PUB.derived_ids(template[0], 'V'), [ + 'release/V/EigenLabs/Qwen3.8-27B-4bit-mtp/' + suffix + for suffix in ('s1', 's2', 's1/grant', 's2/grant', 's1/q1', 's2/q1', 's1/q2', 's2/q2')]) + self.assertEqual(PUB.derived_ids(template[2], 'V'), ['release/V/glm-5.3-flash/s1', 'release/V/glm-5.3-flash/s2']) + + def test_a_registration_body_over_the_coordinators_limit_is_refused_before_staging(self): + # The coordinator reads POST /v1/releases under 64 KiB, the block's own bound: a block within its bound can + # still take the body over the limit. Grow a valid block by whole qualifications, then lengthen numerics + # classes byte by byte to a body of exactly the limit, and one byte over it. + env, limit = self.dev_env(), PUB.COORDINATOR_REGISTRATION_MAXIMUM_BYTES + self.assertEqual(limit, 65536) + sized = PUB.prepare(self.base / 'sized', self.root / PUB.BUNDLE, env) + template = cluster_runtime_block()['models'][0] + + def block(models): + return dict(cluster_runtime_block(), models=models) + + def body(models): + return PUB.registration_body(dict(sized, cluster_runtime=block(models))) + + def grown(models): + count = len(models[-1]['parity_qualifications']) if models else 8 + index = len(models) - (count < 8) + return models[:index] + [dict(template, model=f'm{index:02d}', parity_qualifications=[ + dict(qualification(1 + n % 2), numerics_classes=[f'c{n}'] * 2) for n in range(count % 8 + 1)])] + + def padded(models, extra): + out = [] + for model in models: + qualifications = [] + for q in model['parity_qualifications']: + classes = [] + for name in q['numerics_classes']: + add = min(extra, 64 - len(name)) + classes.append(name + 'x' * add) + extra -= add + qualifications.append(dict(q, numerics_classes=classes)) + out.append(dict(model, parity_qualifications=qualifications)) + self.assertEqual(extra, 0) + return out + models = grown([]) + while len(body(grown(models))) <= limit: + models = grown(models) + gap = limit - len(body(models)) + exact, over = padded(models, gap), padded(models, gap + 1) + self.assertEqual((len(body(exact)), len(body(over))), (limit, limit + 1)) + self.assertLess(len(json.dumps(block(over), sort_keys=True, separators=(',', ':'))), PUB.CLUSTER_RUNTIME_MAXIMUM_BYTES) + + payload = PUB.prepare(self.base / 'exact', self.root / PUB.BUNDLE, env, self.write_block(block(exact), 'exact.json')) + self.assertEqual(len(PUB.registration_body(payload)), limit) + refused = f"registration body is {limit + 1} bytes, over the coordinator's limit of {limit} bytes" + with self.assertRaisesRegex(ValueError, refused), patch.object(PUB, 'upload') as upload: + PUB.prepare(self.base / 'over', self.root / PUB.BUNDLE, env, self.write_block(block(over), 'over.json')) + upload.assert_not_called() + self.assertFalse((self.base / 'over' / 'release-payload.json').exists()) + with self.assertRaisesRegex(ValueError, refused): + PUB.validate(dict(payload, cluster_runtime=block(over)), env) + # The same limit without a block: release notes the coordinator would refuse. + with self.assertRaisesRegex(ValueError, "over the coordinator's limit"): + PUB.validate(dict(self.payload, changelog='x' * limit), self.env) + # Registration sends exactly the bytes that were sized. + with patch.object(PUB.urllib.request, 'build_opener') as opener: + opener.return_value.open.return_value.__enter__.return_value.read.return_value = b'{}' + PUB.coordinator(dict(env, RELEASE_KEY='k'), '/v1/releases', payload) + self.assertEqual(opener.return_value.open.call_args.args[0].data, PUB.registration_body(payload)) + + def test_the_glm_block_of_the_branch17_app_is_accepted(self): + # The block the release lane computed for GLM-5.3-Flash with the 0.10.5-dev.branch.17 app (pinned by the + # Swift suite): canonical and valid, with the declared grant and, per schedule, the pipeline's qualification + # (cut at 45 / 2, text only) and tensor parallel's (images and video, as DevNet's catalog lists them). + block = PUB.load_cluster_runtime(GLM_BLOCK) + PUB.check_cluster_derived_ids(block, '0.10.5-dev.branch.18') + [glm] = block['models'] + self.assertEqual(glm['model'], 'glm-5.3-flash') + self.assertEqual(glm['pair_serving_grant']['mode_families'], ['pipeline', 'tensor_parallel']) + qualifications = glm['parity_qualifications'] + self.assertEqual([(q['schedule'], q['mode'], q['cuts']) for q in qualifications], + [(1, 'pipeline_v1', [22]), (2, 'pipeline_v1', [22]), (1, 'tensor_parallel_v1', []), + (2, 'tensor_parallel_v1', [])]) + for q in qualifications: + self.assertEqual(q['numerics_classes'], ['g17d-nax1-mlx-98bab9d7-macos27.0'] * 2) + self.assertEqual((q['tensor_parallel_shares'], q['promotable'], q['diverged']), (None, True, False)) + self.assertEqual(q['evidence_sha256'], glm['pair_serving_grant']['evidence_sha256']) + media = q['mode'] == 'tensor_parallel_v1' + self.assertEqual((q['request_envelope']['vision'], q['request_envelope']['video']), (media, media)) + + def test_boundary_values_are_accepted(self): + block = cluster_runtime_block() + block['models'] = [dict(block['models'][1], model=f'm{index:02d}') for index in range(64)] + PUB.check_cluster_runtime(block) + version = '0.9.8-dev.branch.7' + PUB.validate(dict(self.payload, version=version, require_app_attest_qualification=False, + url='https://releases.example/' + PUB.object_key(dict(self.payload, version=version)), + cluster_runtime=block), self.dev_env()) + block['models'] = [dict(block['models'][0], model=' ' + '~' * 127)] + PUB.check_cluster_runtime(block) + # A grant of every family; none. + block['models'][0]['pair_serving_grant'] = {'evidence_sha256': 'f' * 64, 'mode_families': list(ALL_FAMILIES)} + PUB.check_cluster_runtime(block) + block['models'][0]['pair_serving_grant'] = None + PUB.check_cluster_runtime(block) + # Eight qualifications; a pipeline cut; a measurement kept for the record; a fraction and an offset; + # the smallest envelope. + block['models'][0]['parity_qualifications'] = [ + dict(qualification(1 + index % 2), numerics_classes=[f'c{index}'] * 2) for index in range(8)] + PUB.check_cluster_runtime(block) + block['models'][0]['parity_qualifications'] = [dict( + qualification(1), mode='pipeline_v1', cuts=[8], promotable=False, diverged=True, + qualified_at='2026-10-31T00:00:00.5+02:00', + request_envelope={'sampling': False, 'tools': False, 'vision': False, 'video': False, + 'max_prompt_tokens': 1, 'max_output_tokens': 1})] + PUB.check_cluster_runtime(block) + + def test_only_prepare_takes_the_block(self): + for operation in ('stage', 'publish', 'download'): + with self.subTest(operation=operation), \ + patch('sys.argv', ['publication', operation, '--directory', str(self.root), + '--cluster-runtime', str(self.write_block(cluster_runtime_block()))]), \ + patch('sys.stderr'), self.assertRaises(SystemExit): + PUB.main() + + class GitHubPublicationTests(PublicationFixture): def fake_github(self, release=None, fail_at=None, content=None): self.release = release From ab67fb9d747e1d6df75785054cc4ebd47121caf1 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Sat, 31 Oct 2026 08:56:33 -0700 Subject: [PATCH 3/6] Prepare provider 0.10.6 (#1695) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * cluster: runtime facts v2 name each model's pair-serving grant; release modes `darkbloom cluster runtime-facts` prints schema darkbloom_cluster_runtime_v2: the v1 digests, unchanged, plus each model's pair_serving_grant. The grant is the public grant a member of the same build reports for the described artifact (ClusterPairServingGrants.grant), null when there is none: its mode families sorted by byte, and evidence_sha256, the SHA-256 of the records it rests on as canonical JSON Lines (ClusterPairServingGrant.records, evidenceSHA256). The canonical encoder writes null rather than omitting it; the strict decoder init(canonical:releaseVersion:) refuses unknown, missing or repeated fields, schema v1, and a model whose derived IDs (release///s2, plus /grant for a granted model) exceed 128 bytes. The model bound is 64. The release modes come back (ClusterRuntimeApprovalFacts+Release.swift): --list-release-models prints the models this build qualifies on a cluster, and --app A --release-candidates DIR describes, for every listed artifact and every catalog model ID among its candidates, the first candidate the app's worker describes as that model. A listed model with no candidate is left out (the environment's catalog lacks it); the output must read back under the strict decoder for this build's version. Co-Authored-By: Claude Opus 5.5 * ci(release): every lane computes cluster_runtime; sent only when enabled The release lane (dev branch, staging, prod) computes the cluster runtime facts of its final signed, notarized app with that app's own CLI and worker, in the step "Compute cluster runtime facts from the final signed app" of build-and-release: after the final hashes, with no secret (the signing keychain is deleted and the identity proven gone first), from the target environment's public catalog and model CDN (provider-cluster-runtime-models.py --environment). A listed model that catalog lacks is left out and named. The job summary shows the block and a run artifact retains it in every lane. The payload carries it (prepare --cluster-runtime) only when CLUSTER_RUNTIME_SEND is true: the run registers a release and the environment's repository variable DEV_, STAGING_ or PROD_CLUSTER_RUNTIME_ENABLED is exactly 'true'. Unset, prepare runs today's command and the payload is byte for byte today's (pinned by digest in the tests), and a facts failure only warns (continue-on-error). Set, a failure fails the release before staging and registration. validate accepts a valid block in every environment and refuses an invalid one and one whose derived approval or grant IDs exceed 128 bytes. Co-Authored-By: Claude Opus 5.5 * fix(release): the registration carries cluster_runtime in its canonical form Contract A defines the block as canonical JSON (keys sorted by byte, no whitespace, no trailing newline). prepare now refuses a block file that is not canonical, and the registration body is encoded without whitespace when, and only when, it carries the block, so the coordinator receives the block's canonical bytes whether it parses them or compares them. A body without the block is byte for byte the one sent before (pinned in the tests). Co-Authored-By: Claude Opus 5.5 * cluster: no derived grants; the owner's public models and their parity qualifications Owner decisions (jonathan308, 2026-10-31): "public traffic should not be manual"; "only glm 5.3 flash should be serving public & qwen 3.8 27b they are both good to go they should be approved for serving". The v2 facts no longer carry pair_serving_grant. A coordinator grant restricts its approval to the families it names, and GLM-5.3-Flash's bundled records hold only a pipeline_v1 run, so a derived grant would stop the GLM tensor-parallel pairs M5 members serve today. ClusterPairServingGrants is back to dev apart from the public-traffic line below. ClusterPublicModels (beside the grants, reviewed in PRs) declares exactly GLM-5.3-Flash (registered_glm53_flash, glm-5.3-flash) and Qwen3.8-27B (registered_qwen38_27b, EigenLabs/Qwen3.8-27B-4bit-mtp): tensor_parallel on schedules 1 and 2, evidence placement two Apple M5 Ultras (applegpu_g17d, NAX on) on macOS 27.0, cuts [], equal shares, qualified 2026-10-31T00:00:00Z, and the SHA-256 of the evidence document docs/reports/2026-10-31-public-cluster-models.md (a test holds them equal). It also names the artifact the runtime registers for each model. Each model's parity_qualifications is [] unless the declaration names its runtime model, catalog ID and artifact; then one object per declared family and schedule: numerics classes of the evidence placement with the block's metallib (g17d-nax1-mlx-98bab9d7-macos27.0 on 0.10.5-dev.branch.15 and .16), cuts, mode, tensor_parallel_shares null, promotable, not diverged, evidence_sha256, qualified_at and the request envelope (ClusterPublicModels.requestEnvelope: sampling, tools, 1,048,576 tokens each way, vision and video as the candidate's catalog entry lists image and video; text only without one). Release candidates carry that entry (catalog.json). The strict decoder and validate check the qualifications as a coordinator does and bound the derived IDs release///s/q. The setup's public-traffic line says a declared model is qualified in its declared family without a record of it. The GLM block the installed 0.10.5-dev.branch.16 app computes from DevNet's catalog is pinned as a golden. The placement check runner compiles the new file. Co-Authored-By: Claude Opus 5.5 * ci(release): candidates carry their catalog entry; validate parity qualifications provider-cluster-runtime-models.py saves each candidate's catalog entry (its id and input_modalities, canonical, catalog.json) beside its manifest and config.json, so the released app's own CLI gives a declared model's request envelope the media the target environment's catalog lists; a malformed modality list fails that entry, none listed means text only. provider-release-publication.py checks parity_qualifications in place of pair_serving_grant: the exact fields, schedule 1 or 2, two numerics classes, the cuts the mode has, null shares, flags, an instant the coordinator accepts, the envelope bounds, video only with vision, no placement twice, at most 8; and bounds every derived approval and qualification ID (release///s/q) at 128 bytes. The pinned GLM block is accepted. Docs and the changelog fragment follow; the release step's comments name the parity qualifications. Co-Authored-By: Claude Opus 5.5 * fix(cluster): the service's part beats into its own heartbeat file Under its supervisor the cluster service beats every 2 s into the file DARKBLOOM_CLUSTER_MEMBER_HEALTH_FILE names. Its part was started with the service's environment unchanged, and a coordinator-paired part (`start --foreground --cluster-member`) beats every 5 s into the file the same key names, with its own pid. The supervisor's liveness guard reads the file every 15 s and treats a beat of another pid as no beat. The three periods are near multiples of each other, so their phases drift by milliseconds per probe: once the part's beat was the last write at six probes in a row, the guard recycled a healthy service ("heartbeat missing for 75 s while its process is alive") and the pair dropped and registered again. Seen on a DevNet leader about every 15 minutes. The part now gets the service's environment with the key pointing at part-health.json beside the service's files. The key stays set, so the part still waits for its registration as a supervised member does. Co-Authored-By: Claude Opus 5.5 * docs: the cluster service part's own heartbeat file Docs Impact failed: ClusterService.swift changed without its mapped architecture document. The cluster serving section now says which file the service and its part each write their heartbeat to, and why. Co-Authored-By: Claude Opus 5.5 * test(cluster): keep the approval fixture alive through the part heartbeat tests Both new tests failed on CI at every run: the member part never started. They dropped the ClusterApprovalMacs fixture (`let (_, service, parts)`), whose deinit removes both homes, so the leader's saved setup was gone before the service's first tick. The fixture now lives until the last check, as in the other tests of the suite. Co-Authored-By: Claude Opus 5.5 * cluster: pair-serving grants again, beside parity qualifications David's finding: a pair member reports only hardware capabilities (DistributedServingEligibility.memberCapabilities: apple_m5 on an M5), and without a pair-serving grant the coordinator holds each member to the model's single-Mac requirements (providerMeetsServingRequirementsLocked), which no member meets for GLM-5.3-Flash (mlx_nax, glm5_next_v1) or Qwen3.8-27B (mlx_nax). No pair forms without a grant, so every model in the v2 facts again carries pair_serving_grant (null, or exactly evidence_sha256 and mode_families) beside parity_qualifications. A declared public model's grant names its declared families with the evidence document's SHA-256. Owner ruling 2026-10-31 ("It should be tensor or pipeline obviously but that shouldn't matter for the coordinator"): ClusterPublicModels declares pipeline and tensor_parallel for both GLM-5.3-Flash and Qwen3.8-27B. Any other model's grant is the one this build's bundled records give its artifact (ClusterPairServingGrants.grant), with the SHA-256 of those records' canonical JSON Lines (ClusterPairServingGrant.records, evidenceSHA256); null when they grant none. The declaration's families drive the parity qualifications: one promotable record per family and schedule, pipeline first (byte order), so each approval's q1 is the pipeline and q2 tensor parallel. A pipeline is pipeline_v1 cut at [num_hidden_layers / 2] of the model's config.json (top level, else text_config: GLM 45 -> [22], Qwen3.8-27B 64 -> [32]); without a layer count its records are left out and the command says so on standard error. An envelope admits media only where the placement serves media (ClusterModelFeaturePolicy.mediaContract): tensor parallel follows the catalog entry, a pipeline is text only. The strict decoder and validate check the grant (1 to 4 known families in byte order, nonzero evidence) and bound release///s/grant at 128 bytes beside the approval and /q IDs. The setup's public-traffic line follows the declaration (pipeline and tensor parallel); tests about the records alone pass publicModels: []. The evidence report says the owner approved both modes for both models, that GLM-5.3-Flash's bundled records hold a pipeline_v1 run while its tensor parallel rests on the owner's decision and the DevNet serving results, and why grants are needed; its SHA-256 is re-pinned. The GLM golden is re-pinned from the installed 0.10.5-dev.branch.17 app, which replaced branch.16 on this Mac. Co-Authored-By: Claude Opus 5.5 * ci(release): validate pair-serving grants and their derived IDs provider-release-publication.py checks each model's pair_serving_grant again (null, or exactly evidence_sha256 and 1 to 4 known mode_families in byte order) beside its parity_qualifications, adds the grant's evidence to the digests it checks, and bounds release///s<1|2>/grant at 128 bytes with the approval and /q IDs. Its tests cover the grant rows, the ID bound for a model with neither, qualifications only, a grant only and both, the /grant and /q IDs, and the branch.17 GLM golden (q1 the pipeline, text only; q2 tensor parallel). The docs (configuration reference, release runbook, inference architecture, test guide), the changelog fragment and the release step's comments describe the grants and why pairs need them, both declared families, the pipeline cut, the per-placement media and the q1/q2 order. Co-Authored-By: Claude Opus 5.5 * release(publication): refuse a registration body over the coordinator's 64 KiB The coordinator reads POST /v1/releases under MaxReleaseRegisterBodyBytes (64 KiB, as http.MaxBytesReader applies it), the same bound as the cluster_runtime block's own, so a block within its bound could take the body over the limit and fail only at publish, after R2 staging. validate (in prepare, stage and publish) now refuses a payload whose registration body exceeds 65,536 bytes, naming its size and the limit. One function (registration_body) builds the bytes it sizes and the bytes registration sends, so they cannot differ. The test grows a valid block to a body of exactly 65,536 bytes (accepted) and 65,537 (refused before staging, with no payload written), refuses the same limit without a block (release notes), and checks that registration sends the sized bytes. Independent review N1. Co-Authored-By: Claude Opus 5.5 * docs(cluster): the declared placement is evidence, not a limit; catalog room Independent review fixes (S1, S2, N2, N3, N4, N7, N10, N15 wording). The configuration reference, the release runbook, the inference page and the changelog say how a coordinator applies the declared qualifications: a promotable record qualifies its approval's whole mode family on any numerics classes, cuts and shares within the envelope (parityQualification, platform df61dd6f9), so public traffic for GLM-5.3-Flash and Qwen3.8-27B is admitted in pipeline and tensor parallel on any Apple silicon pair; the declared placement names the evidence, not a limit. No pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record: both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash serves only the serial schedule, so its schedule 2 entries are inert. The digest-pinned evidence document is unchanged. The runbook adds the catalog-room precondition (64 approvals with the operator's own, 2 per model per release, newest release whole first, older releases left out first), DevNet's numbers on 2026-10-31 (26 served, 4 catalog models: 8 per release, the 4 newest fit), the log check after the first registration (release cluster approvals omitted), the recovery when a facts failure stops a release, "set to true" (GitHub compares case-insensitively; also in the workflow comment), the release-handler link re-pinned to platform df61dd6f9, and "a catalog model ID of a listed artifact". The inference page notes that a grant also bounds owner-formed sessions to its families. The grant's evidence is the passing records it is computed from, without a pass a divergence of the same shape contradicts: said so in the code comment and the reference, with a test row for a family still granted by another pass. Co-Authored-By: Claude Opus 5.5 * chore(release): prepare provider 0.10.6 Set ProviderCore.version to 0.10.6 and mark v0.10.5 as published on 2026-10-30 (tag target d3bbcd064ea290fbeb500e5c51c7870e3695741c). Open the v0.10.6 candidate entry with its upgrade and rollout notes: the first production release with two-Mac clusters (darkbloom cluster over one Thunderbolt 5 cable with RDMA, macOS 26.2 or later; GLM-5.3-Flash and Qwen3.8-27B in tensor parallel); releases carry their cluster runtime facts (#1692), from which a coordinator with darkbloom-platform#643 derives approvals, pair-serving grants and public qualifications, off in production until that coordinator runs with its switches on and migration 58, and PROD_CLUSTER_RUNTIME_ENABLED is set after it and before the tag; no coordinator change or version floor for single-Mac serving; the #1690, #1686, #1680 and #1683 changes; the MLX pins (mlx 72dffa2d and mlx-swift c633d221 unchanged, mlx-swift-lm 2beb401f -> 7933a0fa for SDK #373 only, so the metallib hash should equal v0.10.5's); and what the verbatim entries below are. Update the release runbook: the 0.10.6 scope, the pin, metallib and catalog checks before tagging, the rollout order (the platform with #643, its three switches and migration 58 first, then PROD_CLUSTER_RUNTIME_ENABLED, the dev -> master promotion as a merge commit, the tag and the platform snapshot), platform evidence inspected on 2026-10-31, and the published history. The pending changelog fragments are rendered in the next commit. Co-Authored-By: Claude Opus 5.5 * chore(release): render the pending changelog fragments into provider 0.10.6 Insert the output of python3 scripts/changelog.py render --version 0.10.6 --date 2026-10-31 (all 101 pending fragments) verbatim, without its heading line, below the v0.10.6 upgrade and rollout notes, and remove exactly those 101 fragments. The render ran on this branch's base, origin/dev a0413a8ae, before the v0.10.6 heading existed, because the renderer refuses a version that CHANGELOG.md already names. A render from a git archive export of a0413a8ae is byte-identical. This commit is mechanical, so a later roll-up can revert it, merge dev and render again if more fragments land before this merges. Co-Authored-By: Claude Opus 5.5 * chore(release): name the single-Mac answers that change in 0.10.6 Two client-visible answers of one Mac are new since v0.10.5: a content part of an unknown type is refused with 400 (OpenAIRequestValidationError, from the cluster capability honesty change), and media the model's processor refuses answers 400 invalid_media instead of the retryable 503 (EngineV2VisionPrefill.clientFault). Say so beside "no coordinator change". Both use failure codes the coordinator's closed enum already had in v0.10.5's protocol reference. Co-Authored-By: Claude Opus 5.5 * chore(release): complete the single-Mac changes and production gates in the 0.10.6 notes From the independent review of this preparation: - S1: three answers to coordinator requests change on one Mac, not two. A response_format answer cut off by max_tokens is now a client error (InferenceErrorClassifier: client_error instead of the retryable tool_noncompliance), so the coordinator no longer retries it on another provider. The local API (darkbloom start --local) normalizes a request that fails to decode as the coordinator path does (InboundChatNormalization), returns logprobs where the model captures them, reports usage.completion_tokens_details.reasoning_tokens and answers the cut-off with 422 and its own message (LocalChatUploadResponder, StandaloneServer+HTTP). Two operator changes without a fragment are named too: provider.toml is written owner-only (ProviderConfigFile), and the 0.10.6 updater extracts releases under umask 022 (SelfUpdater). - S2: production needs four cluster settings, including EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES (the coordinator listens on plain HTTP behind Caddy), and App Attest serving for every account (EIGENINFERENCE_APP_ATTEST_SERVING, _ENVIRONMENT=production, _ROLLOUT_PERCENT=100). - S3: PROD_CLUSTER_RUNTIME_ENABLED waits for #643 plus any follow-up fix and for the DevNet proof with the release's dev build: derived release/ approvals and a session on a real pair. - N4: four repeated single-Mac statements (all published in v0.10.0); N5: the 6% is for one request; N6: the SDK pin moved through #1680 and #1684. The rendered entries are unchanged. Co-Authored-By: Claude Opus 5.5 * docs(release): settings, DevNet proof, snapshot promotion and tag checks for 0.10.6 From the independent review of this preparation: - S2: rollout step 1 sets four cluster settings, among them EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES (without it no member connection attaches to pair control behind Caddy, and in the split deployment the trusted-proxy path is the only one), and App Attest serving at a 100% account rollout, because a member without MDM pairs only through App Attest. Evidence rows cite the platform configuration reference, the cluster-control "Member trust" row and appattest/service/config.go. - S3: a DevNet proof step: the 0.10.6 dev build's release/ approvals are listed and a real pair forms a session, on the platform fixes production will run. The variable step checks production /health for that revision; #643 alone is not enough. The DevNet observation (block accepted, no release/ entry) is in the evidence table. - S4: the promotion is a snapshot branch cut at this preparation's merge commit on dev, and before tagging, make changelog-check prints 0 fragments and the tagged commit differs from that merge commit only by master's prod default. - N2: merging into dev starts the DevNet dev-branch release; N5, N6; N7: #644 carries only migration 58; N8: the catalog bounds and what 0.10.6 adds. The cluster runtime facts section now names the trusted-proxy setting and points its production step at the version's rollout. Co-Authored-By: Claude Opus 5.5 * docs(build): describe how a release promotes dev to master The dev branch section said "Never merge dev into master", that dev is master plus one commit, that master pushes publish dev providers and that code changes go to master first. None of that has held since #1635, #1637 and #1688, and the release runbook now promotes dev. Describe it as #1688 did: a snapshot branch of dev merged into master with a merge commit (an admin briefly allows merge commits on the squash-only master ruleset), master's one commit of its own (e9babca4) that keeps plain builds on prod and is reverted on dev by each master-into-dev sync, and dev pushes that publish DevNet releases through release-dev-branch.yml. Co-Authored-By: Claude Opus 5.5 * docs(release): refactor pass on the 0.10.6 notes and runbook From the dedicated refactor pass of this preparation (edits A-F; the optional G and H are not applied). The 101 rendered entries, the version constant and docs/developer/build.md are unchanged. - A: the DevNet proof is rollout step 1 and the production platform step 2, because production deploys the revision that passed the proof. Before, steps 1 and 2 each referred to the other. - B: the notes state the production gate as a condition. The 2026-10-31 DevNet status and the Caddy detail stay in the runbook and its evidence table, because they stop being true at rollout. - C: the notes name the superseded statements that state a wrong current default (widened Qwen fences, SSD prefix-record precision, Qwen3.8 27B tensor-parallel speculation) and the owner's decisions behind the public qualifications. - D: the notes name the MLX stream-fence fix that v0.10.5's pins already contain, and carry the per-build SSD checkpoint fact, which the runbook's metallib check no longer repeats. - E: the dev-branch lane drops two statements superseded since 2026-10-28: master's verify-source accepts a dev push for environment dev, and pull requests into dev need one approval and land as merge commits. - F: Cluster Runtime Facts separates acceptance (darkbloom-platform#643) from derivation (EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES) and no longer points at the per-version section, which the next preparation replaces. Co-Authored-By: Claude Opus 5.5 * fix(cluster): release facts leave out another model's catalog ID of a shared artifact Production's catalog lists the Gemma 4 26B artifact a4722b60 twice: gemma-4-26b and gemma-4-26b-8bit. The build registers two runtime models on it that only the manifest tells apart (registered_gemma4_26b and registered_gemma4_26b_8bit), and only the 8-bit one is qualified on a pair, so only it is a listed release model. ClusterRuntimeApprovalFacts .release required every catalog model ID of a listed artifact to be described as the listed model, and the worker describes gemma-4-26b's manifest as registered_gemma4_26b. Run against production's catalog and CDN, the release's facts step therefore failed ("Qualified cluster models the release cannot describe: gemma-4-26b"), and a production release with PROD_CLUSTER_RUNTIME_ENABLED=true would stop after signing. A catalog model ID whose candidates the worker describes only as another registered model is that model's: a member that installed it runs as that model, which this release does not qualify. It is now left out and named on standard error (note: left out, the catalog model ID of another registered model). A catalog model ID of which the worker describes no candidate at all still fails the step, and so does an empty result, whose message now names what was left out. The new test builds production's shape from the checked-in metadata fixtures (gemma-4-26b and gemma-4-26b-8bit, one configuration): it fails on the previous code with the production error and passes now; a second test checks the note in both directions. The runbook's release step and the configuration reference state the rule. Co-Authored-By: Claude Opus 5.5 * docs(release): 0.10.6 goes to production without a DevNet proof The owner dropped the DevNet proof for this release. The notes' gate bullet said PROD_CLUSTER_RUNTIME_ENABLED is set only after DevNet lists the dev build's derived approvals and a DevNet pair forms a session under one, which would misstate in the permanent history how 0.10.6 shipped. - CHANGELOG.md: the gate is the production coordinator with #643 and its follow-up fix for the split edge and Conductor deployment, migration 58, the four cluster settings and App Attest serving; a new bullet says the release was not proven on DevNet first and that its derived approvals and a pair session under one are first checked in production. - provider-release.md, 0.10.6 rollout: step 1 says there is no DevNet proof and why production is the first coordinator to derive approvals; step 2 names the split-edge fix; step 3 depends on step 2 only; step 5 adds the production pair session as the check of the derived approvals. The 101 rendered entries are unchanged. Co-Authored-By: Claude Opus 5.5 * chore(release): render the release facts fix's fragment into provider 0.10.6 The release facts fix (cluster runtime facts leave out another model's catalog ID of a shared artifact) lands before this preparation and adds one pending fragment. Render it with the other 101 so that changelog.d holds only its README at the tag: - CHANGELOG.md: the v0.10.6 block is a fresh `changelog.py render --version 0.10.6 --date 2026-10-31` of the 102 pending fragments (minus its heading line and the blank line after it), byte for byte; against the 101-fragment render it only inserts the new entry, in filename order. The notes count 102 entries. - changelog.d/cluster-runtime-facts-another-models-catalog-id.md is removed. Co-Authored-By: Claude Opus 5.5 * docs(release): 0.10.6's production gate is the release source alone The notes and runbook required what this mainnet-direct release does not have: a follow-up platform fix for DevNet's split edge and Conductor deployment (darkbloom-platform#652, deferred; production runs one combined coordinator) and EIGENINFERENCE_CLUSTER_PAIRS, which production deliberately leaves unset so that approvals derived from releases are the only source. The facts rollout order still waited for a DevNet proof, the pair guide said production serves no approvals, and the runbook promoted dev to master with a merge commit while 0.10.6 reaches master through squash-merged pull requests. - CHANGELOG.md: the gate is #643 with migration 58 and the three lines production gets (EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true, EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true, EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1), with EIGENINFERENCE_CLUSTER_PAIRS unset; the notes name the verbatim entry that still calls production a coordinator without pair control. The 101 rendered entries are unchanged. - provider-release.md, 0.10.6: step 2 sets those lines and drops the split-edge prerequisite; step 3 names the 409 cluster_runtime_conflict; step 4 merges the clustering PR, the facts fix and this preparation into master, each squash-merged, restacked with restack-after-squash.py; step 5 tags this preparation's squash commit; the pre-tag check reads that commit's subject instead of diffing against a dev merge commit. - provider-release.md, Cluster Runtime Facts rollout order: step 4 is the production order (deploy with those lines and the /health check, PROD_CLUSTER_RUNTIME_ENABLED=true, the tag, then the derived release/0.10.6/... approvals), without a DevNet proof, with the trap: a version first registered without the block never gains one (409). - two-mac-cluster.md and configuration.md: production derives approvals from releases once its coordinator runs #643 with approvals from releases; before that deploy it serves none (404). A derived approval ends 90 days after its release registered. - build.md: dev's changes reach master through pull requests into master; #1688 was a merge-commit promotion, 0.10.6 a squash-merged pull request. Co-Authored-By: Claude Opus 5.5 * docs(release): 0.10.6 reaches master in two pull requests The release facts fix is part of the two-Mac clustering pull request now: master is squash-only and asks for a new approval after every push, so each stacked pull request costs the approver another round. Rollout step 4 of the 0.10.6 section therefore merges two pull requests, the clustering one (#1690 and #1692 from dev with master merged in, and the fixes found while preparing this release, such as the release facts fix) and then this preparation, restacked once with restack-after-squash.py after the first squash. Co-Authored-By: Claude Opus 5.5 * refactor(cluster): refactor pass on the release facts fix Behaviour-preserving cleanup of 35f7b9f09, from the dedicated refactor pass that AGENTS.md requires before the pull request opens. The facts block, --list-release-models and every message and note stay byte for byte the same. - ClusterRuntimeApprovalFacts.release: the left-out list holds the note lines it names (leftOut) instead of a list called othersCatalogIDs that held reason strings and was mapped to those lines afterwards. The doc comment says "whose candidates the worker describes only as another registered model", as the docs do, and that the empty-result error names what was left out. - ClusterRuntimeFactsCommand: one note(_:) writes "note: " to standard error, for the declared families without a qualification and for the catalog IDs release(note:) leaves out, instead of a second copy of that format in a closure. The command's doc comment names both. - ClusterRuntimeApprovalFactsTests: the "another" case of releaseNamesEveryCatalogModelItCannotDescribeAndRefusesAnEmptyResult now passes through the empty-result error, which names the left-out ID; it checks that message's prefix as well as the refusal it already checked. - provider-release.md, release step 6: "every catalog model ID of a listed artifact gets one entry" contradicted the exception the fix added two sentences later. It now reads "every catalog model ID of a listed artifact that it describes as the listed model gets one entry"; the rest of the step is only rewrapped. - configuration.md: the fix's paragraph is rewrapped (one 108-column line); no word changes. Co-Authored-By: Claude Opus 5.5 * docs(release): refactor pass on the 0.10.6 production-gate text From the dedicated refactor pass over 27dedfe11, 8caeea462 and 72bceb8d7. Text only, in docs/operations/provider-release.md: - The platform evidence row named "the three switches" that only DevNet's overlay sets. Since 8caeea462, rollout step 2 lists three other lines (with EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES and without EIGENINFERENCE_CLUSTER_PAIRS), so the row read as if the overlay set those three and "also" the trusted proxies. It now names the switches: EIGENINFERENCE_CLUSTER_PAIRS, EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES and EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING (deploy/gcp/dev/env-overrides at df61dd6f). - Rollout step 1 drops "(mainnet-direct)", a planning label that no other page uses; the step already says the release goes to production without a DevNet proof. CHANGELOG.md is unchanged: the 102 rendered entries and the notes. Co-Authored-By: Claude Opus 5.5 * fix(cluster): Qwen3.8 27B pairs register with the coordinator by default With the default [backend] mtp_mode = "auto", the guided setup planned Qwen3.8 27B tensor parallel with the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry (ClusterConfiguration.validate). The leader's check of a coordinator's approval ran only the attachment's own checks, so it stopped both parts and sent the approval, and the other Mac refused it at its save ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"). The pair served on the leader's local API only, while the setup said it was qualified for public traffic (finding F1 of the 0.10.6 two-Mac proof). The assistant stays local-only: no parity qualification covers its verify windows. The bundled tensor-parallel records of the 27B predate it, and neither the records, the release's cluster_runtime block nor a pair's registration has a speculation field. - The onboarding plans for how the cluster serves: through Darkbloom, auto discovers like off (ClusterPlacementTensorAssistantSelection. discoveryMode), so the default Qwen setup carries no assistant and both Macs accept the approval. darkbloom cluster local keeps it. The service's re-plans follow the saved scope, and forwarded planModels and adopt carry the asking Mac's scope. An explicit on is kept. - ClusterApprovalAttachment.attachment runs the whole ClusterConfiguration.validate on the setup with the approval attached, so the leader refuses an assistant setup before any part stops or anything is sent. The refusal names the reason and the remedy in 163 characters. - A plan that decodes with the assistant says "not offered for public traffic" instead of "qualified for public traffic". Tests: ClusterApprovalTensorAssistantTests (real stores, the other Mac's own approval handling) and the onboarding's public-traffic line for the registered 27B artifact fail on 35f7b9f09 with the live F1 message and pass with the fix; discoveryMode, the plain refusal through the link, the public-traffic line and the CLI scope binding have tests of their own. The release's model list and cluster_runtime block are byte-identical (51c77bdb..., 4fd4ea8a...). Co-Authored-By: Claude Opus 5.5 * fix(cluster): coordinator-side member ends no longer set a pair's approval aside for good ClusterApprovalCheck.memberQuickEnds counted every coordinator-paired part end under 120 s except an unreachable coordinator. A registration the coordinator did not acknowledge in its 10 s negotiation window (a deploy, a restart, a slow coordinator) counted like a local failure. Three in a row set the approval aside as failing, and the same build never took it again; a release-derived approval keeps its ID for the whole release, so the pair served only the leader's local API until someone intervened (provider bug hunt 1.4, probe 8bad154d9). (a) Which ends count - A quick end whose error is ClusterMemberControlError.negotiationFailed leaves the count as it is; a run of 120 s or more still resets it, and an unreachable coordinator still resets it. Every other end counts: a changed input, a crash without an error line, connectionEnded, roleUnsupported. - "The coordinator control connection ended or lost trust" never ends a coordinator-paired part: `start --cluster-member` runs its loop with stopOnDisconnect false, so a dropped connection, an untrusted or offline trust_status and a runtime-outdated status leave it reconnecting. That exit (memberControlEnded) is the distributed leader part's, which the count never includes. A coordinator restart reaches the count only as a registration the restarted coordinator does not accept in time: the negotiation case above. Per platform master 2847f27dd, "untrusted" is sent only for this Mac's own verification (failed or missed attestation challenges, a revoked App Attest credential, a failed security check, a replaced connection), so it would count; "offline" only accompanies the end of the connection. - This complements the coordinator fix that ends each pair session before its shutdown closes the members' sockets (darkbloom-platform fix/coord-shutdown-pair-cancel, 824e82e3c, not yet on master): a deploy then ends members cleanly, and this rule still covers older coordinators, coordinator crashes and slow negotiation. (b) A bounded set-aside - ClusterSetupRecord.ApprovalSetAside gains setAt (wall-clock seconds), which the cluster service records (ClusterApprovalCheck.setAside(by:worker:now:)). step holds a failing approval aside for ClusterApprovalFallback.failingSeconds = 3_600 only; then the same build takes it again. A record without setAt (an older build's) or with a time ahead of the clock is past the bound. The count starts again because each Mac's part that serves locally resets it, so the approval comes back with none. - The status line says when; two-mac-cluster and the configuration reference follow; changelog fragment. Tests (ClusterApprovalWatchTests): coordinatorSideEndsDoNotReachTheFailingLimit, localQuickEndsStillSetTheApprovalAside, aFailingApprovalIsOfferedAgainAnHourAfterItWasSetAside, aSetAsideInTheCurrentRecordFormatReadsCleanlyAndIsPastTheHour. They fail on the old rules (12 issues in 5 tests, with a compile shim for the new field) and pass with the change. The model-approval test now expects an older build's record to be past the hour. Co-Authored-By: Claude Opus 5.5 * docs(cluster): pair Macs do not update themselves; update both by hand Nothing updates Darkbloom on a Mac set up with `darkbloom cluster` (provider bug hunt 1.2): ClusterServiceCommand.runSupervisor builds its supervisor with autoUpdate false, so the update slot never runs; the coordinator-paired part never starts startAutoUpdateMonitor (ProviderLoop+Serve, solo providers only); and the single-Mac provider cannot run beside the cluster (DistributedInstalledProviderExclusion). The docs said otherwise. - two-mac-cluster: a section "Updating Darkbloom on the pair" with the manual procedure, as the code does it: `darkbloom update` on each Mac (UpdateCommand installs; its "Restart the provider" line does not apply without a provider LaunchAgent); the control leader's ClusterService.checkForUpdate compares the pinned worker digests with this Mac's worker file and the other Mac's reported facts every 60 s while serving, then stops both parts, plans the same model again and serves it ("Darkbloom changed on ...: setting the cluster up again for "). The cluster service process itself keeps the release it started with until it starts again: a re-run of `darkbloom cluster` leaves an unchanged login agent alone, so log out and in (or restart). Automatic pair updates are listed as not yet in this build. - cluster-always-on: the login agent's supervisor runs without the update slot; the update-slot row applies to the developer route (`start --cluster-member --always-on`) only, with auto_update on. Co-Authored-By: Claude Opus 5.5 * docs(inference): note that min_p applies on one Mac too abbe697ca made EngineV2Bridge forward an explicit min_p on every single-Mac slot, as a cluster pair already did (intentional: requests without min_p are unchanged). The 0.10.6 fragments did not say so, and ChatRequest.min_p still said it applied on a pair only (provider bug hunt 1.6). - changelog.d/min-p-single-mac.md: the bug hunt's proposed line. - ChatRequest.min_p: applied on every slot; the samplers count a value above 1 as 1 and ignore 0, negative and NaN values; MiMo native media and Nemotron Super refuse a non-zero value. Comment only. Co-Authored-By: Claude Opus 5.5 * docs(cluster): Qwen pairs refuse grammar-constrained JSON before any output; pair updates in the notes The Qwen pair JSON fix is not part of 0.10.6 (refactor pass #2, finding M1). Skipping the grammar on a pair would have answered public JSON-mode requests with no grammar and no answer check, because the provider streams every coordinator request and validates a streamed answer only when a grammar was built. - Two-Mac guide, Qwen section: a JSON response_format request that one Mac would answer under a grammar is refused on a Qwen pair before any output (constrained_decoding_unsupported, HTTP 400). The coordinator moves a public request refused this way to a single Mac, which constrains it (darkbloom-platform fix/coord-pair-refusal-failover); the owner's local cluster API gets the refusal. - changelog.d/cluster-pair-update-by-hand.md: pair Macs set up with darkbloom cluster do not update themselves yet; run darkbloom update on both Macs, then log out and back in, and press m once if the status says the assistant is not offered. Co-Authored-By: Claude Opus 5.5 * chore(release): render F1, the set-aside fix, min_p and the pair update note into provider 0.10.6 The final clustering branch adds four pending fragments to the 102 this preparation rendered: - cluster-qwen-pair-public-without-assistant.md (F1: Qwen3.8 27B pairs register with the coordinator by default); - cluster-pair-coordinator-ends-not-failing.md (a coordinator deploy no longer takes a cluster pair off public traffic); - min-p-single-mac.md (a request's min_p now applies on one Mac too); - cluster-pair-update-by-hand.md (pair Macs set up with darkbloom cluster do not update themselves yet). The Qwen pair JSON fix is not part of 0.10.6, so it has no entry. CHANGELOG.md: the v0.10.6 block is a fresh `changelog.py render --version 0.10.6 --date 2026-10-31` of all 106 fragments pending on the clustering branch (2071bbd79), minus its heading line and the blank line after it, byte for byte. Against the 102-fragment render it only inserts the four entries, in filename order. The notes count 106 entries. The four fragments are removed, so changelog.d holds only its README; the version stays 0.10.6. Co-Authored-By: Claude Opus 5.5 * docs(release): re-run the facts dry run before PROD_CLUSTER_RUNTIME_ENABLED Refactor pass finding m9: rollout step 3 set the variable without asking for the read-only facts dry run, although a production catalog row the worker cannot describe would stop the tag's release after signing once the variable is true. Step 3 now re-runs the release's facts step (scripts/provider-cluster-runtime-facts.sh darkbloom prod) with an unsigned app staged from this preparation's source, as the build job stages it, and requires exit 0 before the variable is set. The order (the coordinator deploy first, then the variable, then the tag) and the 409 cluster_runtime_conflict trap are unchanged. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit dd7da3589a804138a46e6a2b58b2600b6f8ff8f2) * fix(provider): co-resident loads fund every model's KV floor before the proportional split 0.10.5 providers report "loading 'gemma-4-26b-qat-4bit' would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance (fleet KV budget 51467271830 B across 7 slots) — refused", and the same for gpt-oss-20b at 54999766706 B, with every floor far inside the budget. resliceGrants split the fleet KV budget only in proportion to each slot's fp16 rate x min(context, 131072). A resident with a small rate but a real fixed request workspace gets less than its own floor once a seventh model joins: on a 192 GB Mac with Ternary Bonsai 2 27B, Qwen3.8 27B, Qwen3.6 and Qwen3.5 35B-A3B, Gemma 4 26B and Nemotron 3.5 Lightning resident, Lightning (6,144 B/token; nine recurrent generations with its assistant, a floor of at least 1.587 GB) is offered 1.443 GB, while all seven floors total 9.9 GB of the 51.5 GB budget. Given the floors, resliceGrants keeps the proportional result whenever it clears every floor (configurations that load today keep identical grants). Otherwise, if the floors fit, each slot gets its floor plus its weighted share of the rest; if they do not, the proportional result stands and the floor check refuses as before. Every re-slice passes the floors: ProviderLoop and StandaloneServer loads with the MTP target-only retry, the managed Super newcomer, the reserve-raise preflights, native MiMo, and both regrow paths, so an unload or reserve change cannot shrink a slot below its floor. Tests: real EngineV2 residents with their fixed workspace reproduce the refusal through ProviderLoop and StandaloneServer and are admitted after the fix; a plain regrow cut Lightning to zero serving width and now keeps its floor. Pure tests pin the reported budgets, unchanged results when nothing starves, refusal for infeasible or unprovable floors, and Σ ≤ budget. The Super capacity test that used proportional starvation as its trigger now asserts that Super loads at its floor, and a genuine shortfall still refuses. Co-Authored-By: Claude Opus 5.5 * chore(release): render the KV reslice floor fix into provider 0.10.6 The clustering branch adds one pending fragment to the 106 this preparation rendered: kv-reslice-slot-floors.md ("Models load when every model's minimum KV fits"). CHANGELOG.md: the v0.10.6 block is a fresh `changelog.py render --version 0.10.6 --date 2026-10-31` of all 107 fragments pending on the clustering branch (249101fae), minus its heading line and the blank line after it, byte for byte. Against the 106-fragment render it only inserts that entry, in filename order. The notes count 107 entries. The fragment is removed, so changelog.d holds only its README; the version stays 0.10.6. Co-Authored-By: Claude Opus 5.5 * docs(provider): a newcomer's KV floor is checked only when its engine is assembled The re-slice funds every resident's floor first, but a newcomer has no engine yet and counts only the base 1 GiB floor. A newcomer with a small KV rate and its own fixed workspace can therefore still receive less than its floor and fail at assembly with no_kv_headroom: Nemotron 3.5 Lightning loaded seventh beside the reported residents gets 1.443 GB against its 1.587 GB floor (serving width 0), unchanged from 0.10.5. hardware-support.md now states that limit where the floors are described, and inference.md says the re-slice, not every load, refuses only when the floors exceed the fleet KV budget. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 * test(provider): local server regrow and reserve check keep a starved slot's KV floor The fix passes slot floors at both regrow paths and both reserve checks, but only the ProviderLoop pair had a test. Dropping the floors from StandaloneServer.resliceGrowSurvivors and reserveKeepsSurvivorsServiceable left all 350 selected tests passing. The new test mirrors the ProviderLoop one on the same seven-slot scenario: it first checks that the server's own budget starves Lightning under the plain proportional split, then expects the reserve check to pass and the regrow to leave every resident at its floor with serving width, within the budget. With either floors argument removed it fails. Co-Authored-By: Claude Opus 5.5 * docs(provider): the KV floor changelog entry names the refusal it removes "A load is refused only when the minimums together exceed the budget" promised more than the split can check. The model being loaded counts only the 1 GB base minimum until it is built, so Nemotron 3.5 Lightning loaded beside several high-rate models can still fail with no KV headroom, as on 0.10.5. The entry now says the message appears only when the minimums exceed the budget, and states that limit. Release preparation already rendered this fragment into CHANGELOG.md; the matching one-line change there equals changelog.py render of the new fragment. 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: David Tai --- CHANGELOG.md | 799 +++++++++++++++++- changelog.d/cli-download-progress-line.md | 8 - changelog.d/cluster-balanced-equal-cut.md | 3 - ...uster-bonsai-residual-and-gate-pressure.md | 4 - changelog.d/cluster-capability-honesty.md | 7 - changelog.d/cluster-cdn-manifest-pins.md | 4 - .../cluster-control-leader-failover.md | 13 - .../cluster-coordinator-paired-approval.md | 6 - .../cluster-degraded-mode-admission.md | 5 - changelog.d/cluster-dev-install-model-ref.md | 3 - .../cluster-glm-lane-prefill-slices.md | 3 - changelog.d/cluster-glm-pair-parity.md | 3 - changelog.d/cluster-glm-tp-load-setup.md | 3 - changelog.d/cluster-glm-tp-media.md | 3 - ...cluster-glm-tp-prefill-8k-micro-batches.md | 3 - changelog.d/cluster-glm-tp-prefill-levers.md | 3 - changelog.d/cluster-glm-tp-ssd-prefix-tier.md | 3 - changelog.d/cluster-glm-tp-width-invariant.md | 3 - changelog.d/cluster-guided-setup.md | 5 - ...luster-hardware-split-prefix-everywhere.md | 9 - .../cluster-installed-paths-with-spaces.md | 5 - changelog.d/cluster-lane-withdrawal.md | 6 - changelog.d/cluster-local-only.md | 34 - changelog.d/cluster-local-serving.md | 5 - changelog.d/cluster-member-install-grant.md | 5 - ...ter-member-refusal-releases-reservation.md | 4 - .../cluster-member-restart-registration.md | 4 - .../cluster-mimo-pair-qualification.md | 5 - changelog.d/cluster-mode-bound-grants.md | 5 - changelog.d/cluster-model-approvals.md | 6 - ...cluster-model-change-replans-after-stop.md | 4 - changelog.d/cluster-model-provisioning.md | 5 - changelog.d/cluster-onboarding-brand.md | 3 - changelog.d/cluster-onboarding-mac-names.md | 5 - .../cluster-onboarding-mark-on-every-run.md | 3 - .../cluster-onboarding-narrow-windows.md | 3 - changelog.d/cluster-one-command.md | 8 - changelog.d/cluster-paged-kv.md | 4 - .../cluster-pipeline-speculative-records.md | 6 - changelog.d/cluster-planner-pricing-fixes.md | 6 - changelog.d/cluster-prefix-tenant-scope.md | 3 - changelog.d/cluster-qmv-batch-invariant.md | 3 - .../cluster-qwen-m5-ultra-window-layout.md | 3 - .../cluster-qwen-moe-packed-collective.md | 10 - .../cluster-qwen-tensor-lanes-every-row.md | 10 - changelog.d/cluster-qwen-tensor-prefix-ssd.md | 3 - .../cluster-qwen-tensor-rank-ledger.md | 3 - .../cluster-qwen-tensor-speculation.md | 3 - changelog.d/cluster-qwen-tp-exact-vectors.md | 19 - changelog.d/cluster-qwen-tp-fenced-sums.md | 13 - .../cluster-qwen-tp-pipelined-draft.md | 12 - ...luster-qwen-tp-window-submission-switch.md | 9 - changelog.d/cluster-qwen27-native-context.md | 5 - changelog.d/cluster-rdma-system-settings.md | 3 - .../cluster-served-speed-build-scope.md | 4 - changelog.d/cluster-service-after-reboot.md | 5 - .../cluster-service-network-identity.md | 5 - .../cluster-session-rank-lease-keep-warm.md | 10 - changelog.d/cluster-setup-reasoning-probe.md | 3 - changelog.d/cluster-sharded-deployments.md | 6 - .../cluster-ssd-prefix-quantized-records.md | 6 - changelog.d/cluster-stage-kv-quantization.md | 17 - .../cluster-steady-visible-tensor-parallel.md | 13 - changelog.d/cluster-stop-leader-drain.md | 7 - changelog.d/cluster-stop-local-only.md | 3 - changelog.d/cluster-tensor-parallel-first.md | 6 - .../cluster-tensor-parallel-roster-plans.md | 5 - changelog.d/cluster-tensor-share-probes.md | 15 - changelog.d/cluster-tp-feasibility.md | 7 - .../cluster-validation-and-tensor-batching.md | 47 -- changelog.d/cluster-worker-protocol-2.md | 3 - changelog.d/collected-reasoning-truncation.md | 3 - .../distributed-start-signal-restoration.md | 5 - changelog.d/glm-automatic-finite-placement.md | 7 - changelog.d/glm-cluster-still-images.md | 5 - changelog.d/glm-single-mac-speed-shared.md | 7 - ...-tensor-parallel-decode-command-buffers.md | 4 - ...glm-tensor-parallel-mtp-early-proposals.md | 3 - ...lm-tensor-parallel-mtp-vocabulary-split.md | 3 - changelog.d/glm-tensor-parallel.md | 13 - changelog.d/glm53-native-prerequisites.md | 3 - .../local-responses-previous-response-id.md | 4 - changelog.d/media-processor-refusals-400.md | 3 - .../mlx-fast-fence-gpu-queue-starvation.md | 16 - changelog.d/pair-check-reservation-fields.md | 3 - changelog.d/qwen-prefill-steel-tiles.md | 17 - changelog.d/qwen-tp-batched-cohort-drafts.md | 3 - changelog.d/qwen-tp-cohort-synchronization.md | 3 - changelog.d/qwen-tp-exact-batched-drafts.md | 5 - changelog.d/qwen-tp-six-lane-batches.md | 3 - changelog.d/qwen-tp-vector-tiles-measured.md | 3 - changelog.d/qwen-tp-widened-fast-fences.md | 3 - .../qwen-tp-wider-automatic-batching.md | 6 - .../qwen27-feature-preserving-modes.md | 3 - changelog.d/qwen27-media-response-format.md | 8 - changelog.d/qwen27-tp-greedy-exchange.md | 3 - .../qwen27-tp-media-preparation-refusal.md | 12 - changelog.d/qwen27-tp-mtp-depth3.md | 3 - .../qwen27-tp-shared-verify-windows.md | 3 - changelog.d/qwen27-tp-wide-verify-kernel.md | 3 - docs/developer/build.md | 31 +- docs/operations/provider-release.md | 234 +++-- docs/provider/two-mac-cluster.md | 32 +- docs/reference/configuration.md | 2 +- .../Sources/ProviderCore/ProviderCore.swift | 2 +- 105 files changed, 1020 insertions(+), 715 deletions(-) delete mode 100644 changelog.d/cli-download-progress-line.md delete mode 100644 changelog.d/cluster-balanced-equal-cut.md delete mode 100644 changelog.d/cluster-bonsai-residual-and-gate-pressure.md delete mode 100644 changelog.d/cluster-capability-honesty.md delete mode 100644 changelog.d/cluster-cdn-manifest-pins.md delete mode 100644 changelog.d/cluster-control-leader-failover.md delete mode 100644 changelog.d/cluster-coordinator-paired-approval.md delete mode 100644 changelog.d/cluster-degraded-mode-admission.md delete mode 100644 changelog.d/cluster-dev-install-model-ref.md delete mode 100644 changelog.d/cluster-glm-lane-prefill-slices.md delete mode 100644 changelog.d/cluster-glm-pair-parity.md delete mode 100644 changelog.d/cluster-glm-tp-load-setup.md delete mode 100644 changelog.d/cluster-glm-tp-media.md delete mode 100644 changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md delete mode 100644 changelog.d/cluster-glm-tp-prefill-levers.md delete mode 100644 changelog.d/cluster-glm-tp-ssd-prefix-tier.md delete mode 100644 changelog.d/cluster-glm-tp-width-invariant.md delete mode 100644 changelog.d/cluster-guided-setup.md delete mode 100644 changelog.d/cluster-hardware-split-prefix-everywhere.md delete mode 100644 changelog.d/cluster-installed-paths-with-spaces.md delete mode 100644 changelog.d/cluster-lane-withdrawal.md delete mode 100644 changelog.d/cluster-local-only.md delete mode 100644 changelog.d/cluster-local-serving.md delete mode 100644 changelog.d/cluster-member-install-grant.md delete mode 100644 changelog.d/cluster-member-refusal-releases-reservation.md delete mode 100644 changelog.d/cluster-member-restart-registration.md delete mode 100644 changelog.d/cluster-mimo-pair-qualification.md delete mode 100644 changelog.d/cluster-mode-bound-grants.md delete mode 100644 changelog.d/cluster-model-approvals.md delete mode 100644 changelog.d/cluster-model-change-replans-after-stop.md delete mode 100644 changelog.d/cluster-model-provisioning.md delete mode 100644 changelog.d/cluster-onboarding-brand.md delete mode 100644 changelog.d/cluster-onboarding-mac-names.md delete mode 100644 changelog.d/cluster-onboarding-mark-on-every-run.md delete mode 100644 changelog.d/cluster-onboarding-narrow-windows.md delete mode 100644 changelog.d/cluster-one-command.md delete mode 100644 changelog.d/cluster-paged-kv.md delete mode 100644 changelog.d/cluster-pipeline-speculative-records.md delete mode 100644 changelog.d/cluster-planner-pricing-fixes.md delete mode 100644 changelog.d/cluster-prefix-tenant-scope.md delete mode 100644 changelog.d/cluster-qmv-batch-invariant.md delete mode 100644 changelog.d/cluster-qwen-m5-ultra-window-layout.md delete mode 100644 changelog.d/cluster-qwen-moe-packed-collective.md delete mode 100644 changelog.d/cluster-qwen-tensor-lanes-every-row.md delete mode 100644 changelog.d/cluster-qwen-tensor-prefix-ssd.md delete mode 100644 changelog.d/cluster-qwen-tensor-rank-ledger.md delete mode 100644 changelog.d/cluster-qwen-tensor-speculation.md delete mode 100644 changelog.d/cluster-qwen-tp-exact-vectors.md delete mode 100644 changelog.d/cluster-qwen-tp-fenced-sums.md delete mode 100644 changelog.d/cluster-qwen-tp-pipelined-draft.md delete mode 100644 changelog.d/cluster-qwen-tp-window-submission-switch.md delete mode 100644 changelog.d/cluster-qwen27-native-context.md delete mode 100644 changelog.d/cluster-rdma-system-settings.md delete mode 100644 changelog.d/cluster-served-speed-build-scope.md delete mode 100644 changelog.d/cluster-service-after-reboot.md delete mode 100644 changelog.d/cluster-service-network-identity.md delete mode 100644 changelog.d/cluster-session-rank-lease-keep-warm.md delete mode 100644 changelog.d/cluster-setup-reasoning-probe.md delete mode 100644 changelog.d/cluster-sharded-deployments.md delete mode 100644 changelog.d/cluster-ssd-prefix-quantized-records.md delete mode 100644 changelog.d/cluster-stage-kv-quantization.md delete mode 100644 changelog.d/cluster-steady-visible-tensor-parallel.md delete mode 100644 changelog.d/cluster-stop-leader-drain.md delete mode 100644 changelog.d/cluster-stop-local-only.md delete mode 100644 changelog.d/cluster-tensor-parallel-first.md delete mode 100644 changelog.d/cluster-tensor-parallel-roster-plans.md delete mode 100644 changelog.d/cluster-tensor-share-probes.md delete mode 100644 changelog.d/cluster-tp-feasibility.md delete mode 100644 changelog.d/cluster-validation-and-tensor-batching.md delete mode 100644 changelog.d/cluster-worker-protocol-2.md delete mode 100644 changelog.d/collected-reasoning-truncation.md delete mode 100644 changelog.d/distributed-start-signal-restoration.md delete mode 100644 changelog.d/glm-automatic-finite-placement.md delete mode 100644 changelog.d/glm-cluster-still-images.md delete mode 100644 changelog.d/glm-single-mac-speed-shared.md delete mode 100644 changelog.d/glm-tensor-parallel-decode-command-buffers.md delete mode 100644 changelog.d/glm-tensor-parallel-mtp-early-proposals.md delete mode 100644 changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md delete mode 100644 changelog.d/glm-tensor-parallel.md delete mode 100644 changelog.d/glm53-native-prerequisites.md delete mode 100644 changelog.d/local-responses-previous-response-id.md delete mode 100644 changelog.d/media-processor-refusals-400.md delete mode 100644 changelog.d/mlx-fast-fence-gpu-queue-starvation.md delete mode 100644 changelog.d/pair-check-reservation-fields.md delete mode 100644 changelog.d/qwen-prefill-steel-tiles.md delete mode 100644 changelog.d/qwen-tp-batched-cohort-drafts.md delete mode 100644 changelog.d/qwen-tp-cohort-synchronization.md delete mode 100644 changelog.d/qwen-tp-exact-batched-drafts.md delete mode 100644 changelog.d/qwen-tp-six-lane-batches.md delete mode 100644 changelog.d/qwen-tp-vector-tiles-measured.md delete mode 100644 changelog.d/qwen-tp-widened-fast-fences.md delete mode 100644 changelog.d/qwen-tp-wider-automatic-batching.md delete mode 100644 changelog.d/qwen27-feature-preserving-modes.md delete mode 100644 changelog.d/qwen27-media-response-format.md delete mode 100644 changelog.d/qwen27-tp-greedy-exchange.md delete mode 100644 changelog.d/qwen27-tp-media-preparation-refusal.md delete mode 100644 changelog.d/qwen27-tp-mtp-depth3.md delete mode 100644 changelog.d/qwen27-tp-shared-verify-windows.md delete mode 100644 changelog.d/qwen27-tp-wide-verify-kernel.md diff --git a/CHANGELOG.md b/CHANGELOG.md index e897e8dd4e..eaf320c1ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,804 @@ or console deployment, feature activation, model promotion or hardware qualification. Sections marked historical retain the original candidate's qualification, opt-in and deployment limits rather than claiming activation. -## v0.10.5 — candidate (unpublished) +## v0.10.6 — candidate (unpublished) -Prepared on 2026-10-30; tagging and publication are separate steps. +Prepared on 2026-10-31; tagging and publication are separate steps. + +### Upgrade and rollout notes + +- This is the first production release with two-Mac clusters (#1628 with #1407, #1426 and #1577, and the cluster PRs merged after it): run `darkbloom cluster` on each of two Apple silicon Macs joined by one Thunderbolt 5 cable, pick a model, and the pair serves it together. Both Macs need macOS 26.2 or later, RDMA over Thunderbolt turned on by an administrator (System Settings on macOS 27, `rdma_ctl enable` in Recovery on macOS 26) and the same Darkbloom release. The planner chooses tensor parallel or a pipeline; GLM-5.3-Flash and Qwen3.8-27B can serve in tensor parallel, with images and video. `darkbloom cluster local` serves a pair without any coordinator. A Mac that never runs `darkbloom cluster` keeps serving alone. +- Releases carry their cluster runtime facts (#1692): every release lane computes them from the final signed app and shows them in its job summary, and the registration carries them as `cluster_runtime` only while that environment's repository variable is `true`. A coordinator with darkbloom-platform#643 and `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` derives from them the build's cluster approvals, their pair-serving grants and the public qualifications of GLM-5.3-Flash and Qwen3.8-27B in pipeline and tensor parallel (the owner's decisions of 2026-10-31); every other model's clusters serve their owner only. A pair without a cluster approval serves only on its leading Mac's local API, with the `darkbloom start --local` key. +- A production registration carries the block only once `PROD_CLUSTER_RUNTIME_ENABLED=true`, which is set only after the following, and before the tag, because a release registered without the block can never gain one. A coordinator without #643 refuses a registration that carries the block, and the release then fails after signing. + - The production coordinator runs #643, with migration 58 applied and three cluster settings: `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`, `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` and `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` (without it no member connection attaches to pair control behind production's TLS-terminating proxy). Approvals derived from releases are its only approval source: `EIGENINFERENCE_CLUSTER_PAIRS`, the operator's approval table, stays unset. App Attest serving is on for every account (`EIGENINFERENCE_APP_ATTEST_SERVING=true`, `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT=production`, `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT=100`), because a member on macOS 27 without MDM pairs only through App Attest. +- This release was not proven on DevNet first: its derived approvals and a pair session under one are first checked in production. The entry "A Mac pair registers with the coordinator as a cluster member by itself (DevNet)" below predates this: with the coordinator above, production has pair control and serves the approvals derived from this release. +- Single-Mac serving needs no coordinator change and no provider-version floor, but three answers to coordinator requests change, all with codes the coordinator already knows. A content part of an unknown type is refused with 400 instead of being answered from the remaining text. Media the model's processor refuses answers 400 `invalid_media` instead of the retryable 503. A `response_format` answer cut off by `max_tokens` is a client error (`client_error`) instead of the retryable `tool_noncompliance`, so the coordinator no longer retries it on another provider. After the tag the platform snapshots its provider contracts from the tagged commit and sets `LatestProviderVersion` to `0.10.6`; of the 34 snapshotted inputs only `ProviderCore.swift` changes since v0.10.5. +- The local API of one Mac (`darkbloom start --local`) changes too. A request that fails to decode is normalized as on the coordinator path (a scalar `stop`, the `developer` role, messages without content, hosted tools) and decoded again before it is refused. It returns `logprobs` where the model captures them and reports `usage.completion_tokens_details.reasoning_tokens`, and it answers a `response_format` request cut off by `max_tokens` with 422 and a message that says so, instead of "Internal inference failure.". Two operator changes have no entry of their own: `provider.toml` is written owner-only (a group- or world-readable file is tightened at its next save), and the 0.10.6 updater (`darkbloom update` and the automatic update) extracts the next release under `umask 022`, as the installer has since v0.10.0. +- Recent cluster fixes: a registered pair's cluster service is no longer restarted many times a day by its own part's heartbeats (#1690); pair members register GLM-5.3-Flash and Qwen3.8-27B under their pair-serving grant instead of ending a second after they start (#1686); a single Qwen3.8-27B request in tensor parallel decodes about 6% faster on two M5 Ultra with an M5 Ultra verify-window layout (#1680). On every Mac, `darkbloom models download` and the `darkbloom start` picker show one progress line (#1683); without a terminal they print a plain line at most every 30 seconds, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. +- MLX pins: `libs/mlx` and the nested `mlx` (`72dffa2d`) and `libs/mlx-swift` (`c633d221`) are unchanged from v0.10.5. `libs/mlx-swift-lm` moves from `2beb401f` to `7933a0fa`, its fork's `main` (#1680, #1684): SDK #373 adds an M5 Ultra layout table to `AffineQuantizedVectors`, which only the cluster's Qwen tensor-parallel exact projections use, and a layout never changes a result. The MLX core is unchanged, so the tag build's `metallib_hash` should equal v0.10.5's `98bab9d7…614be`, which the dev-branch build of this preparation's base (`a0413a8a`) also registered on DevNet. Complete SSD checkpoints stay per build, because their namespace binds the binary hash: 0.10.6 does not restore those 0.10.5 wrote. Cluster entries below that describe MLX or SDK work (steel tiles, `MLX_QMV_BATCH_INVARIANT`, fast-fence ordering, GPU streams that no longer spin on each other's fences, the GLM-5.3-Flash SDK speedups) describe code that v0.10.5's pins already contain. +- The 107 entries below are the pending fragments rendered verbatim, in filename order. Most were written on the cluster branch, and some record steps that newer entries supersede, wherever those sit in the list: "Fixed" predates GLM-5.3-Flash tensor parallel; widened Qwen tensor-parallel owners keep fast fences, not the event path; the pair's SSD prefix records are `balanced` by default, not exact; and Qwen3.8 27B tensor-parallel text speculation ships (automatic setup drafts three tokens a round). Four single-Mac statements repeat changes that v0.10.0 published: `previous_response_id` on one Mac, "Preserve truncated reasoning in collected responses", the local API's reasoning by model type (two bullets of the `darkbloom cluster local` entry) and the start-time weight hash without the file cache (in the MiMo entry). #1666 (approval check follow-ups) and #1674 (CI shards) have no entry. + +### One progress line for model downloads + +- `darkbloom models download` and the `darkbloom start` picker show one line for the whole model, redrawn in place at most four times a second: a bar, the percent, the bytes, the rate and the time left, leaving out what does not fit the window's width. They no longer print a line for every file or a block of per-file bars. +- The line keeps its shape while the window keeps its width: each figure has a fixed column, sized for its widest form, so the bar and the figures do not move as the numbers change. The rate and the time left appear after 2 seconds, and a time left over 24 hours is not shown. +- The line reads "Verifying" while the files are checked, then ends with one line: `✓ Downloaded (16.3 GB in 2m 10s)`, `✓ is already downloaded (16.3 GB)`, where the download stopped, or `Verification of failed: `. The picker no longer adds its own "Downloaded" line, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. +- Without a terminal (a pipe, a log, the desktop app) the download prints plain lines with no carriage returns: the first at once, then at most one per 30 s and 10 points, one at 100%, and the same last lines. The desktop app reads its download progress from them. +- `darkbloom cluster` shows a model download or a copy over the cable on its live line instead of adding a line every second. A plain transcript keeps the first report, about one per 30 s and 10 points, and the lines for the record. +- Sizes in the line are decimal, as the catalog gives them. + +### Identical Macs split a model evenly + +- When cuts predict the same request time (identical Macs, or equal measured speeds), the placement planner now chooses the one that uses each Mac's hardware capacity most evenly, instead of the earliest cut the second Mac's free memory held at that moment. Two M5 Ultra 256 GB had planned GLM-5.3-Flash 11/34 and then 5/40 of its 45 layers; they now plan it 22/23 whichever Mac leads. A faster split is never traded for balance, and the "Quit apps first" refusal is unchanged. This applies to every model the cluster plans. + +### Bonsai FP32 residual stream and the cluster memory gate under pressure + +- Bonsai (Prism) packs keep their FP32 residual stream on the fused Qwen 3.5 decode, verify and stage paths. The fused residual step rounded each FP32 branch to the stream's FP16 embedding dtype, so the stream stayed FP16 and a Bonsai producer stage's residual left its FP32 contract; such a stream now takes the unfused sum, as the unfused forward computes it. Qwen 27B and the other uniform-dtype rows are unchanged. +- The cluster load gate's room-making pass runs only at normal memory pressure. Above it the gate withdraws all file cache on purpose, and a refusal now stands on the gate's own sample instead of a fresh one taken after the pass. + +### Two-Mac cluster capability honesty + +- A cluster member registers image and video input only when its pair's placed mode serves media (GLM-5.3-Flash and Qwen3.8 27B in tensor parallel), so the coordinator no longer routes media to a pipeline pair that answers text only; a pair registered for media serves only while both Macs report the media contract. +- `darkbloom cluster status` and the pair's `/metrics` report MTP on for GLM-5.3-Flash in tensor parallel, which always decodes with its NextN head (depth 2); they said "MTP off". +- A content part of an unknown type (`input_file`, `input_video`, `refusal`, ...) is refused with HTTP 400 naming the type on the local API of one Mac and of a pair, and with the closed invalid-request error on coordinator requests, instead of being answered from the remaining text. +- With images or video, a GLM-5.3-Flash pair answers the output controls as one Mac does: it withholds hidden reasoning (`reasoning.exclude`, `include_reasoning: false`, `thinking.display: "omitted"`) and refuses a `response_format` JSON answer or a required or named tool call with 400 before any media decode. +- A `response_format` answer the service validates that was cut off by `max_tokens` (a reasoning model can think through the whole budget) now returns 422 saying so, instead of "Internal inference failure." GLM-5.3-Flash, which validates its withheld JSON itself, keeps its typed 422. + +### Cluster models pin the manifest a Mac downloads + +- The cluster worker now pins the model CDN's `manifest.json` bytes for every registered model. GLM-5.3-Flash pinned bytes that no Mac could fetch, so a downloaded GLM was never described and the cluster refused it. Qwen3.5 35B A3B, Qwen3.6 35B A3B, Nemotron 3.5 Lightning, GPT-OSS 20B, MiMo V2.6 Flash and the three Gemma 4 26B entries pinned the production coordinator's re-encoding, whose `created_at` is different on each environment, so DevNet could not use them. The files and aggregate digests are unchanged; only the pinned serialization of each manifest is different. +- A cluster folder with the earlier bytes is repaired when setup next lists the models, with no hand step. This includes a folder copied over the cable from the other Mac, which has no download receipt on this Mac. The cluster store fetches the published manifest (the CDN first, then the coordinator) and writes it in place only when it names the same model, version, aggregate and files and this Mac's worker takes it. Weight files are not written. When nothing answers, the folder stays as it is and the repair is tried again a minute later. When the published manifest names other files, the folder stays as it is and the worker refuses it as before. + +### Derived cluster control leader, failover, `darkbloom cluster` on every member + +- If one Mac goes away the cluster keeps itself running and re-forms by itself when it is back; `darkbloom cluster` works on either Mac. +- The cluster's control leader is derived, not the Mac where onboarding started: once a plan is adopted its rank 0 leads (requests enter there and registration v3 treats the plan's first member as the head); otherwise the member present that holds the model alone, then the most memory, the most GPU cores and the lowest member identity (from its Secure Enclave key pin). Leadership is a claim with a term, persisted in each Mac's setup record so a restart re-forms the same way; claims are totally ordered (term, then identity), travel only over the pairing-keyed link control channel, and a member refuses a superseded claim so a stale leader steps down. A leader acts on the cluster only after every plan member confirmed its claim. +- The leader renews a control lease with each member at the rank lease's cadence (5 s / 30 s) on a listener and edge epoch of its own. When the leader's lease expires the survivor takes over at the next term; a leader left alone serves the model on that Mac alone when the planner said it holds it alone (the ordinary single-Mac local server under the Mac's own identity: "degraded: serving on this Mac alone"), and otherwise says it cannot serve and runs nothing. When the missing Mac answers again the pair re-forms by itself and control returns to rank 0. +- `darkbloom cluster` works on any member: status, test request, model change, stop and start, and a verify-teardown summary of every Mac are forwarded to the control leader and its answer is shown. A model change while serving drains both Macs' parts before the setup changes. +- Failover serves alone only on a verdict for the plan saved now: the planner's alone verdicts are recorded with the plan's SHA-256, travel with the lease under it and are dropped for any other plan, and a refused (stale) lease never rewrites them; a member that has a new setup but not yet its verdicts says it cannot serve rather than load a model the planner never checked for it. A Mac re-paired with another Mac starts a new leadership history at term 0 instead of carrying the old pair's claim (which named the gone Mac and not the new one). +- Serving alone waits for the absence grace (10 minutes of peer or link absence, for every model and Mac): control still fails over at lease expiry (30 s), but until the grace ends the leader keeps its part ready for the missing Mac, its status says how long until it serves alone, and a Mac back before the grace re-forms the pair with nobody serving alone. A developer (debug) build may shorten the grace with `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS`. +- A Mac restarted with a saved leader claim acts as the leader (model change, setup write, start, stop; forwarded or typed) only once the other Mac confirmed the claim, or once the confirmation window passed with no member reachable; a superseded claim steps down first and the command goes to the current leader. +- The control lease runs on the continuous clock, which keeps counting while a Mac sleeps: a woken leader no longer counts a Mac that left during the sleep as present, and a woken member gives its leader one lease time awake before it takes over. +- The solo readiness check names this Mac's own solo server (its process, checked by start time, holds the listening socket) instead of trusting any server on the port; another program on the port is reported as such. +- `darkbloom cluster verify-teardown` counts only this cluster's processes: its workers carry this Mac's member identity, its owners run this install's executable or own one of its workers. Other cluster homes' processes (another identity or install, a check's fake workers) are listed apart and do not fail the check. +- A rank 0 told to stop while it is still starting exits promptly: the signal handler is installed first (a stop is latched, never lost), the wait for the follower ends within 0.2 s of the stop, and the cluster service repeats SIGTERM every 5 s while it waits (never SIGKILL). + +### A Mac pair registers with the coordinator as a cluster member by itself (DevNet) + +- After the Test stage passes, `darkbloom cluster` reads the cluster approvals the coordinator serves (`GET /v1/cluster/approvals`, from the operator approval file) and takes the entry whose model, prefill schedule and eight digests match this pair's installed app and model. Each Mac checks it against its own files before it saves it, and both Macs save it, or neither does. Both Macs then run as coordinator-paired members, owner-only, and the status says "Registered with the coordinator as a cluster member" with the approval and its end. +- The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching entry when the saved one ends within a day. An approval that ended is removed before a part starts, and the pair serves on the leader's local API again. +- When the coordinator gives no answer for 10 minutes (the absence grace), the pair serves on the leader's local API, and it is registered again when the coordinator answers with a matching entry. +- A coordinator without pair control (production, staging) or without a matching entry changes nothing: the saved setups stay byte for byte as they were. `darkbloom cluster local` never asks the coordinator. A pair approval saved by hand with `darkbloom cluster configure` is never removed. + +### Cluster: degraded mode only where single-Mac Darkbloom serves the model + +- When the other Mac goes away, a Mac serves the model alone only if single-Mac Darkbloom would serve that model on it (the same runtime requirements `darkbloom start --local` applies, such as an Apple M5 chip for Qwen3.8 27B) and the planner said it fits in that Mac's memory. Otherwise its status says it cannot serve the model alone and waits for the other Mac; the cluster re-forms by itself when it is back. A single-Mac server that still ends right after starting three times in a row is not started again until the cluster re-forms. +- The deployment line ("Serving … across both Macs: pipeline, M5 Ultra 40 layers / M3 Ultra 8 layers") is the same on whichever Mac leads, also when the model's first part runs on the other Mac. Models are listed by their catalog names. +- A stopped cluster's `darkbloom cluster` offers `v` (check that both Macs released their memory) on the leading Mac too, not only on a member. + +### Cluster setup finds models a dev install downloaded + +- `darkbloom-dev cluster` (and a staging install's) lists and uses the models that install downloaded. The cluster's model lookup read only production's `refs/main`, while a dev or staging install records its downloads under its own ref (`refs/darkbloom-dev`), so on a Mac with only a dev install the leader's download step failed with "downloaded, but the product's model store does not list it". It now reads the install's own ref, then production's, as single-Mac model discovery does. + +### GLM pair: a joining prompt no longer stalls decoding lanes + +- While other lanes decode on a GLM-5.3-Flash tensor-parallel pair, a joining lane's prefill runs in layer slices of about 500 ms, one slice a step, with every decoding lane's step after it, so decoding streams wait about 0.6 s instead of a whole 8K chunk (about 2.3 s). The lane with the shortest remaining prompt prefills first, and a prompt that fits one slice runs between another prompt's slices. Tokens are the same as a request served alone. + +### GLM pair: logprobs on lanes, reasoning exclusion and MTP metrics + +- A GLM-5.3-Flash tensor-parallel pair serves `logprobs` / `top_logprobs` on batch lanes (it refused them with 503 when lanes were on), clamps `top_logprobs` to 20 as single-Mac does, accepts `reasoning: {"exclude": true}` (it answered 400), and reports MTP rounds, proposals and acceptances, its KV ledger, waiting requests and prefix-cache status on `/metrics`. + +### GLM tensor-parallel setup reads metadata once, beside the link + +- A GLM-5.3-Flash tensor-parallel rank parses its model metadata once (the prepared loader's inventory) and does that work on its own thread while the link comes up, instead of serially before it; tensor-name matching runs on bytes. Setup before the load intent drops from about 5.7 s to about 3 s a rank, and `open` to about 0. Loaded weights are byte-identical and every file is still hashed. + +### GLM images and video on a tensor-parallel pair + +- A GLM-5.3-Flash pair serving in tensor parallel accepts image and video input as the single-Mac product does: the leader runs the product's media decode, processor and prompt expansion, rank 0 reproduces the same patches (checked by digest) off its executor and runs the vision tower when the request opens, and both ranks prefill the same spliced embeddings. Batch lanes carry media requests too, with the same arithmetic as a request served alone. Media requests decode with MTP rounds like text (the NextN history is primed with the media features) and without prefix reuse. Rank 0 now loads the vision tower (1.13 GB) with the tensor-parallel shard. + +### GLM tensor-parallel prefill: 8K micro-batches on long prompts + +- Long prompts on a GLM-5.3-Flash tensor-parallel pair prefill in 32K-token graphs with 8,192-row micro-batches where every micro-batch's cross-Mac sums stay hidden behind the rest of the graph; shorter prompts keep their current plan. Prompt prefixes are still kept every 4,096 tokens, and DSA top-k selection keeps each row's original candidates, so outputs are bit-identical. A 31.5K-token prompt prefills about 4 % faster on two M5 Ultra. + +### GLM tensor-parallel prefill: faster bit-identical kernels + +- GLM-5.3-Flash prompts prefill a little faster on a tensor-parallel pair: each hyper-connection site (89 per forward on both Macs) computes the expanded residual streams inside the products that read them, about 9 % faster per site, roughly 5 ms per 4,096 prompt tokens. Outputs are bit-identical. + +### GLM-5.3-Flash tensor-parallel prefix SSD tier + +- A GLM-5.3-Flash pair serving in tensor parallel keeps its prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt starts with its prefix restored after both Macs restart. Each Mac writes its own state at a prompt's kept 4,096-token boundary (its heads' linear-attention state, its copy of the sparse-attention histories and the MTP history) behind serving, once the request finished, read from the memory tier's pages without copying them first. The sealed prefix vote now counts SSD records; a boundary taken from an SSD record on either Mac is restored only after a second exchange confirms both Macs have it, otherwise both prefill from zero. A restored request writes the record into its own pages. Records store the sparse-attention latents at the pair's checkpoint precision (`balanced` by default, older rows approximate after a restore; see the quantized SSD prompt-prefix records entry); with `native` records a restored request produces the same tokens and logits as a request that prefilled the whole prompt. Records are scoped by the artifact, both builds and the MTP policy, never by the session. The same `DARKBLOOM_CLUSTER_PREFIX_SSD_*` settings, budgets and daily write limit apply. The prefix agreement field becomes `glm5-next-tensor-parallel-prefix-v2`. + +### GLM pair: experimental speculative depth by load (off by default) + +- A GLM-5.3-Flash tensor-parallel pair can verify one NextN proposal a round while three or more requests decode together and two otherwise (`DARKBLOOM_GLM_TP_MTP_DEPTH_POLICY=load`, threshold `DARKBLOOM_GLM_TP_MTP_LOAD_LANES`, 2 through 8, default 3), with `DARKBLOOM_GLM_TP_WIDTH_INVARIANT=1` (implied by `load`) giving verification rows one arithmetic in more window shapes. It is off by default: on two M5 Ultra Macs it raised the aggregate of 4 and 8 concurrent requests by about 11 %, but some concurrent requests' outputs differed from the same request alone, so it stays a diagnostic until that is fixed. Both Macs' cluster services must set the same values; the default keeps today's outputs bit for bit. + +### Clearer cluster setup and recovery + +- Follow five visible setup stages, see the default model before pressing Enter, and use a shorter status menu on either Mac. +- Preserve plain text when output is redirected or color is disabled. +- Report a failed test request with a status-and-retry step instead of announcing that setup succeeded. + +### Hardware-only cluster split, prompt-prefix cache for every family, GLM cluster residency + +- The split across the Macs is chosen from each Mac's hardware and measured speed alone: free pages, cached files and what other programs hold never move it. A range fits a Mac when its whole need is within the GPU's working set, the allocator's and buffer limits, and what the Mac's memory gate can admit at rest (physical memory less the system's own wired share and the file cache macOS always keeps, 10/27 of the rest). The live answer per Mac is still shown ("Quit apps on … first") and the load gate still decides each load. +- Gemma 4 pairs keep and reuse the prompt prefix too: each sliding-window layer's window is kept at every frontier and restored exactly, so a repeated 3,521-token prompt's first token comes in 0.08 s instead of 0.98 s on an M3 Ultra + M5 Max pair, and after both Macs restart the SSD tier gives it back in 0.23 s. +- GLM-5.3-Flash pairs keep and reuse the prompt prefix (resident and encrypted SSD tiers) with the same two-rank agreement as the other families: DSA histories are kept once per prompt, KDA state per frontier. +- A GLM stage holds standing GPU residency, as MiMo's does: without it every command buffer made its tens of gigabytes of weights resident again and decode fell to 0.5 tok/s (30 tok/s on one Mac with it, same tokens). +- A GLM pair always uses the keyed, encrypted data plane, including over the paired link; a model `config.json` up to 32 MiB is accepted (GLM's NVFP4 configuration is 10 MB); a model folder whose bytes are a catalog entry's is listed by that entry's name. + +- Compact GLM convolution and recurrent cache states at transaction ownership boundaries before using the smaller retained-state reservation. Keep pending prefill histories and cast allocations charged per layer, enabling automatic 2048-token placement without choosing a hardware-specific split. + +### Cluster planning accepts a DevNet app's install path + +- Planning a two-Mac cluster with a DevNet build no longer fails every model with "Peer installation paths must be absolute and shell-safe". The DevNet app is installed as `Darkbloom Dev.app`; a saved cluster setup now accepts a space in the installed owner and worker executables, the model directory, and the native member's metallib and resource library. +- Shell syntax, relative paths and `..` are still refused, and the developer SSH route still checks every path it puts in a remote command. +- The orphan sweep, the teardown check and `cancel-all` now find a DevNet build's `darkbloom-dev cluster worker-owner`, and the cluster service stop finds a `darkbloom-dev cluster service`. Before, they knew only the production `darkbloom` name. + +### Independent cluster lane withdrawal + +Fixed cluster batch cancellation so withdrawing an admitted request that has +not started retires that request without interrupting another request waiting +for token credit. Accepting a start command closes the withdrawal window, and +duplicate cancellation messages share the pending retirement acknowledgment. + +### `darkbloom cluster local`: a Mac pair serving without a coordinator + +- `darkbloom cluster local [model]` sets up and serves the pair exactly as `darkbloom cluster` does, but no Mac of the cluster contacts a coordinator: no registration, heartbeat, public traffic or billing, and serving needs no network beyond the cable. A coordinator can therefore never refuse the start. +- The API is on the leading Mac's local endpoint with the same API key as `darkbloom start --local`; it listens on every network of that Mac (LAN or tailnet) unless `--bind` names an address (`--bind 127.0.0.1` keeps it on the Mac). `darkbloom local` prints the base URL, a `network:` URL and the key. +- The choice is kept across restarts and reboots until changed: in `darkbloom cluster`, `l` serves locally only and `p` serves through Darkbloom again; a serving cluster restarts its leading part that way and the screen waits until it serves. +- A cable moved to another Thunderbolt port no longer leaves both Macs unreachable: each cluster service follows the cable to the new port within a few seconds. +- A cluster set up from the plain `darkbloom` command (the installer's link on the PATH) now starts its leading part; it used to stop with "Installed local owner is unsafe or not executable". +- `darkbloom cluster local` on the Mac that joins a pairing carries on to the model choice (it runs on the leader over the cable) instead of sending you to the other Mac. +- The model list shows one line per model (its size and how it is split, or how it gets onto the Macs); what moves and the planner's reason are said once a model is chosen, and the public-traffic line only when serving through Darkbloom. Two models with the same name show their ids. A part that keeps ending the same way is said after three tries instead of repeating, errors read as words (not `invalid("…")`), and pairing waits for the cable's address instead of failing with developer options. +- A smaller Mac takes the share of a model it can hold: the stage memory gate's 6 GiB floor and 4 GiB loading headroom (measured on 256 GiB Macs) now scale with the Mac's memory below 96 GiB (36 GB Mac: 2.25 / 1.5 GiB). A one-layer part on a 36 GB Mac was refused before. "Restart to free memory" is said only when nothing else frees enough; a choice made on the member survives a leader restart; the model list keeps the last catalog it read when the catalog does not answer. +- Hardware run on an M4 Max 36 GB + M5 Max 128 GB pair (Gemma 4 26B QAT, local only): another server on port 8000 (oMLX) no longer makes every start end after both Macs loaded: the port is checked before anything loads and the leading part takes the next free port; Gemma's thought-channel markers no longer reach `content` on the local API (the cluster's API parses reasoning by the model's type, as the coordinator path does); the leader no longer re-sends its cache settings every 15 s to a member that drove the onboarding; the ready screen's deployment line is the running setup's, not one recorded for an earlier start. +- The leading Mac downloads a catalog model the cluster serves whatever its chip: Qwen 3.8 27B's single-Mac requirement (an M5's neural accelerators) no longer stops an M4 Max leader from fetching it for the pair; single-Mac serving keeps its own check. +- Models the cluster takes from this Mac's own model store (Qwen 3.5 9B, a freshly downloaded Qwen 3.8 27B) are offered and copied again: their manifest is the catalog's exact file (the CDN lists the files in another order, which was refused), and a copy written earlier is corrected once. +- On a 36 GB Mac the prompt-prefix cache works: a memory-bound context keeps room for it (a repeated 5.5K-token prompt starts in 0.28 s instead of 7.1 s); a thinking model's reasoning streams from its first token on the cluster's API; each Mac keeps its worker's own log (`~/.darkbloom/cluster-setup/worker.log`). +- `darkbloom cluster local` answers at the same address and with the same key whichever Mac the plan makes rank 0: the other Mac passes the same port to the API over the cable, both Macs keep one API key, and `darkbloom local` shows it on either Mac. The port is 8000 when both Macs have it free, else the lowest port from 8000 to 8020 free on both, and it is kept while it stays free on both (another server on 8000 on one Mac no longer puts the API on 8000 or 8001 by which Mac is rank 0). +- A model chosen on a member is fetched there (it said "Nothing to copy: plan again."); a model's manifest is the encoding this Mac's worker accepts (GPT-OSS 20B was refused); the plan uses the other Mac's served speeds; the start screen no longer prints index estimates as seconds; the test request counts a thinking model's reasoning. +- PrismML Bonsai 2 27B serves on a pair with a 36 GB Mac: the worker's idle context check no longer recomputes the stage plan's constants for every step of its search (it outlasted the 10 s a request waits, so every request failed); a failing local request leaves a line in the log. +- A Mac whose memory moved after the plan (apps opened, cache refilled) no longer makes the pair retry the same split forever: after two load refusals for memory the leading Mac plans the model again on the memory now. +- The local API (single Mac and cluster alike) parses Gemma 4's thought channel and GPT-OSS's Harmony markers out of `content` by the model's type; think-tag models keep the raw stream there, as before, so the cluster still answers exactly as a single Mac does. +- Before a part starts, the model's own pages are dropped from the Mac's file cache (no privileges; the files are untouched): the load gate does not count active cache, and right after a download a 36 GB Mac's share was refused. +- The relay on the Mac that is not rank 0 is hardened: it listens only when the API listens on every address, bounds its connections and idle time, never closes a descriptor another thread may reuse, survives running out of descriptors, and leaves another local server's discovery file alone. +- A 36 GB Mac in everyday use keeps its share: a request on a loaded part asks only for what it needs plus headroom, and when the gate is short only because it does not count file cache the kernel could drop, the worker lets the kernel drop it first (stopped at any sign of compression, swap or pressure); "Quit apps" is no longer said for that case. +- When the cable moves to a Thunderbolt port that was never set up, `darkbloom cluster` says so and sets it up with one key (f); the service's log says what to do. +- The local API (single Mac and cluster) puts every model's reasoning in its own field, Qwen and Nemotron included, on chat completions and the Responses API; a stream whose prompt opens no think block still streams its answer at once. +- Shorter onboarding screens: models held back for the same reason share one line, two Macs running different Darkbloom builds are named as such ("install the same Darkbloom on both") instead of "Planning failed (Peer native build differs from the capability)", models the cluster cannot run say "not supported on a cluster yet", and the development-build service line says only what to do after a restart (the reason is in the service log). + +- Guided cluster setup shows five stages, names the default model choice, refreshes peer labels from the authenticated Mac, and reports completion only after the test response succeeds. Terminal color respects `NO_COLOR`; redirected output stays plain. + +- Cluster members prevent idle sleep while a deployment is serving or waiting for its peer; assertions remain held until the child and relay stop, then are released. +- A cluster service recovering a model process from its previous run keeps waiting after the cleanup deadline, keeps that process visible and protected from idle sleep, and starts no replacement model until it exits. + +- Raise cluster worker output support from 4,096 to 32,768 tokens, with 65,536 combined prompt/output tokens subject to model and live per-rank memory limits. Refuse requests over the advertised bounds rather than truncating them. + +- Keep fixed-scope model reservations at their full serving context when recent short requests tune automatic placement. GLM placement includes the native transport buffers and allocator bounds, so those requests cannot make an oversized split appear loadable. + +### A Mac pair serves locally when its coordinator has no cluster support + +- A cluster whose coordinator cannot take its cluster member role (unreachable, or a coordinator that answers the member's registration as an ordinary provider's because it predates the role) now serves on the leader's local API only, with the same local token as `darkbloom start --local`, instead of restarting every 38 s without ever serving. No public traffic reaches it and nothing is advertised to the coordinator; the Macs stay held for the cluster as before. +- The onboarding screen and `darkbloom cluster` status say so in one line: "Serving locally on this Mac's API; public serving needs a coordinator with cluster support." The next start registers normally once the coordinator supports the role. +- A coordinator that refuses this member or its pairing is still a refusal: that start fails as before. + +### Cluster pairs register GLM-5.3-Flash and Qwen3.8 27B as cluster members + +A pair started with a coordinator approval (DevNet) now registers both Macs as cluster members for GLM-5.3-Flash and Qwen3.8 27B. Before, each Mac's member part ended about a second after it started, with "Cluster member control connection ended", and after three tries the pair served on the leader's local API only. + +The member applied the single-Mac requirements (`mlx_nax`, and `glm5_next_v1` for GLM) to its model in two places: before connecting, and when building its registration, which left the model out of `cluster_models`. A member reports hardware-only capabilities, and its pair-serving grant admits its model, so both places now follow the grant. A solo provider keeps the single-Mac requirements. + +### Cluster member refusals and stops release what they hold + +- A cluster member that refuses an inference request because it has no live pair slot now sends `service_reservation_released` with its 503, on the receive path, in the dispatcher and in the request handler. A request that raced a pair-slot retirement left its reservation held on the coordinator before. The handler refusal also settles the request's prefix-cache lookup receipt. The 503 answer is unchanged. +- A session that ends while the leader still forms its pair (slot publication and warmup canary) retires the published slot before the leader sends `native_pair_owner_released`. The receipt went out while the slot was still published before. + +### Cluster member restarts re-register when the coordinator comes back + +- A cluster member (leader or follower) that starts while its coordinator is briefly away keeps its reconnects inside its registration wait: a retry the backoff would place after the wait is made at its end and is given its own terms, as is an attempt already under way when the wait ends, so a coordinator that returns before the wait ends is reached and its in-time acceptance is honoured. +- A wait in which the coordinator was never reached now says so ("The coordinator could not be reached …") instead of "Coordinator did not accept the control-only member role."; the role check itself is unchanged. + +### MiMo V2.6 Flash on the two-Mac pair + +- MiMo V2.6 Flash can be served by an M5 Ultra and an M3 Ultra together. +- MiMo pair runs produce qualification records (the reference names its request and is compared on it), and MiMo V2.6 Flash is granted on an M5 Ultra + M3 Ultra pair by its six records (pipeline at the planner's cut, in the order the records passed; the mirrored order is refused). +- The provider's start-time weight hash reads with the file cache off (`F_NOCACHE`, same digest, earlier readers kept as fallbacks), so hashing a 172 GB model no longer fills the Mac's file cache before the memory gate decides. The memory gate is unchanged. + +### Pair-serving grants bound to the mode their records ran + +- A qualification record now grants only its own mode family (pipeline variants, pipeline with speculative rounds, tensor parallel, or the off-by-default hand-off modes) and only the chip classes in the roles it ran; a phase-split pass no longer opens pipeline or tensor-parallel placements. A diverged record withholds its own family; an inconclusive one neither grants nor withholds. The planner keeps to the same rule, and a start checked without its mode is refused. +- Seven pipeline qualification records on an M3 Ultra + M5 Ultra pair at the planner's sharded cut (Qwen3.5 9B and Qwen3.8 27B at cut 4 and 8 and Nemotron 3.5 Lightning at cut 8 with the M3 Ultra leading; both Qwen 35B A3B models at cut 36 and Ternary Bonsai 2 27B at cut 56 with the M5 Ultra leading; GPT-OSS 20B at cut 20, which stays withheld by its earlier diverged pipeline records) are bundled: every model the pair served only through phase-split records on these Macs now has a pipeline grant of its own. +- The onboarding offers exactly what a start serves: a model whose chosen placement any rank's grant check would refuse (GPT-OSS 20B, withheld by its diverged pipeline records although cut 20 passed) is listed as not served, with the reason, instead of being offered and then refused at start. + +### A Mac pair keeps its DevNet cluster approval across provider updates + +- The coordinator can serve a model approval: a cluster approval that names the model, its prefill schedule and its serving terms, but no build. The pair takes it when its model, schedule and artifact are the saved setup's, and it computes no build facts for it. Entries pinned to one build are matched as before. +- After an update, the re-adopted setups find the same model approval at the next check, so the pair is registered with the coordinator again with no new entry from the operator. +- Under a model approval each Mac registers its plan with its own runtime (worker, capability, resource policy and profile), and a session starts only with that runtime. Each Mac hashes its worker against its saved setup and its metallib and resource library against the digests it took when it registered. +- When the pair set a model approval aside because its parts kept failing, the next update can take it again. The same build does not take it again. + +### Changing a serving cluster's model plans again once its memory is free + +- Changing the model of a serving two-Mac cluster (`m` in `darkbloom cluster`, or `darkbloom cluster local `) now plans again after both Macs have stopped their parts and given back their memory, and starts that plan. Before, it started the plan made while the old parts still held the memory, where tensor parallel did not fit, so a pipeline started instead. GLM-5.3-Flash on two M5 Ultras came back at less than half the speed (47.9 instead of 126.9 tokens/s in the setup's test request), serving the pipeline's 65,536-token context instead of its native 1,048,576. +- The leading Mac's own re-plan after two load refusals for memory starts the plan made once both parts stopped and gave back their memory, too. + +### Cluster model provisioning without manual downloads + +- `darkbloom cluster` needs no `--model-dir`: the cluster keeps its models in a store beside the product's model cache, and models single-Mac Darkbloom installed are cloned in (APFS clones, the catalog's exact manifest bytes). +- A model one Mac lacks is copied over the Thunderbolt cable on the pairing-keyed link control channel (encrypted records, 4 MiB chunks acknowledged after the receiver wrote and hashed them, resumable). The receiving Mac accepts only a manifest whose digest this build's qualification records pin, refuses hard links, unexpected files, an occupied destination and too little free disk, writes uncached, and has its own worker check the staged files before an exclusive rename into place. +- A catalog model neither Mac has is downloaded once on the leader (the product downloader, written and verified uncached through the new opt-in `ModelDownloader.uncachedWrites`), then copied. A copy predicted under 30 s at the rate measured on these Macs starts by itself (`n` within 3 s stops it). + +### Animated Darkbloom cluster setup + +`darkbloom cluster` setup now opens with the Darkbloom mark, which blooms in on color UTF-8 terminals at least 40 columns wide. Stage headings show a step meter, and long work (cable check, reading both Macs, planning, loading, first tokens) shows a live line that the next transcript line replaces. `DARKBLOOM_NO_ANIMATION` or `CI` keeps the mark and meter but stops the motion. Narrow or non-UTF-8 terminals keep colored headings only. `NO_COLOR`, `TERM=dumb` and redirected output stay byte-for-byte plain. The model-free onboarding checks cover all four presentations (438 checks). + +### Cluster setup names "this Mac" and "the other Mac" + +- `darkbloom cluster` names the two Macs from the screen that shows them: "this Mac" and "the other Mac (Apple M5 Ultra, 256 GB)" in pairing, the machine list, each model's split ("this Mac 50% / the other Mac 50%"), the serving and API lines, status, teardown checks and copies. Two identical Macs were both "Apple M5 Ultra, 256 GB", and the API line did not say it was on the other Mac. Answers the leader gives to the other Mac are worded for that Mac's screen. +- The Mac that joins a waiting leader stops after pairing, also when started with `darkbloom cluster local`; it says to run that on the Mac that leads instead of showing a second model list. +- A model one Mac holds twice (the catalog's download beside the cluster's own copy of the same files) is listed once, and a supported model is never listed as "not supported on a cluster yet" for a copy the cluster worker does not take. + +### Darkbloom mark on every `darkbloom cluster` run + +Running `darkbloom cluster` again on a Mac that is already in a cluster (the leader or a member) now opens with the same Darkbloom mark as the first setup, beside "Darkbloom cluster" and what can be done there (status, test, change model, stop). It follows the same terminal rules as the setup: color UTF-8 terminals with room for the mark draw it, `DARKBLOOM_NO_ANIMATION` or `CI` keep it still, and `NO_COLOR`, `TERM=dumb` and redirected output print the two heading lines as plain text. The onboarding checks cover the leader and the member, in color and plain. + +### Cluster setup in narrow terminal windows + +In a colour terminal between 40 and 56 columns wide, `darkbloom cluster` setup no longer smears the Darkbloom mark: the mark and its bloom appear only when its widest row fits, and narrower windows keep the step meter and live lines. A live progress line wider than the window is now cut to one row, so the line that replaces it no longer leaves its first half in scrollback. + +### One command for a cluster: `darkbloom cluster` + +- Run `darkbloom cluster` on each Mac, pick a model, done. `darkbloom cluster setup` is the same command; with no terminal it says where to run it. +- Choosing the model starts it (3 s to press n); no second question. The screen then says how the model is served in one line, for example "Serving Qwen3.8-27B across both Macs: pipeline, M3 Ultra 40 layers / M5 Ultra 24 layers", and where the API is ("API at http://localhost:8000 on "). +- Models that fit in the Macs' free memory now are listed first, a model that does not fit says what frees the memory, and the fit is checked again right before the start. A model the pair may not serve with this release is listed under "Not offered" ("Not yet qualified on this pair of Macs") instead of failing after a long wait. +- Two cables: the onboarding asks which one to use. The cable check prints plain lines ("Cable found.", "Cable ready."). macOS's one Local Network prompt is announced before it appears, and a denied prompt is named with where to allow it. +- After a Darkbloom update the cluster sets itself up again by itself ("Updating the cluster setup after a Darkbloom update."). After a restart, the screen says whether the Mac comes back by itself (automatic login) or once someone logs in (FileVault). +- A start that does not finish shows each Mac's last error and offers `d` to save a redacted diagnostics file. Error messages name only `darkbloom cluster`; `plan`, `configure`, `console`, `pair` and the other developer subcommands and options are hidden from the help. + +### Cluster KV in pages + +- GLM-5.3-Flash tensor-parallel ranks, GLM pipeline stages, Qwen 3.5 pipeline stages (MTP heads included), Qwen tensor-parallel shards, Gemma 4 stages (any lane count) and Nemotron 3.5 stages keep request KV in page pools instead of contiguous per-request arrays. Prefix entries share pages (refcounted, copy on write at a shared partial page) instead of copying histories, and a GLM tensor-parallel request is charged its pages (about 18.4 KB a token a rank) rather than the contiguous growth charge. Outputs are bitwise the contiguous ones. `DARKBLOOM_CLUSTER_GLM_PAGED_KV=0` keeps contiguous GLM tensor-parallel KV for diagnosis. +- GLM tensor-parallel (solo) and GLM pipeline requests start with their prompt's pages plus a 1,024-token granule and grow between steps, with no context cap; a request whose growth the memory gate refuses ends at `length` without touching others. GLM page pools compile their kernels at load and keep up to `DARKBLOOM_CLUSTER_GLM_PAGED_RETAIN_MB` (2,048 MB a rank) of slabs between requests. + +### A coordinator deploy no longer takes a cluster pair off public traffic + +- A pair registered with the coordinator serves on the leader's local API instead when its coordinator-paired parts end three times in a row right after starting. A part that ended because the coordinator did not accept its registration within the 10-second window counted too, although the coordinator decided that end: it happens during a coordinator deploy, right after a restart, or while the coordinator is slow. Such an end no longer counts. Ends with a local cause, such as a changed input or a crash, still count. +- This complements a coordinator that ends each pair session before it shuts down, which makes a deploy's ends cleaner: the provider rule still covers coordinators without that change, coordinator crashes and slow registrations. +- A pair set aside this way is offered to the coordinator again with the same approval an hour later, or at once with a later approval. Before, only a later approval, the approval's end or a Darkbloom update brought it back, so it could serve only the leader's local API for the rest of the release. + +### Pair Macs set up with `darkbloom cluster` do not update themselves yet + +- Darkbloom on a Mac set up with `darkbloom cluster` does not update itself yet. To update a pair, run `darkbloom update` on both Macs, then log out and back in, so that the cluster service runs the new release. If `darkbloom cluster` status then says that Qwen's speculative assistant is not offered for public traffic, press `m` once in `darkbloom cluster` to plan the model again. + +### Speculative rounds on the pipeline, recorded and on by default + +- A qualification (recording) request now runs a pipeline's speculative rounds (`pipeline_mtp_v1`) as served, and its decoding rank records the accepted timeline: one step per selected token (its row's digest and highest candidates), so the near-tie rule reads every accepted token. Drafts never change the accepted output. +- A qualification record may carry the decode speed timed runs of its own placement and request measured, in its mode and as the plain pipeline (`darkbloom-cluster-pair-check record --timing-mode/--timing-plain`). A passing `pipeline_mtp_v1` record grants the pipeline-with-speculative-rounds family, and the planner credits the rounds with its measured speed-up until the pair has served the same placement both with and without the rounds and its own speed-up replaces it: the rounds are planned by default where lossless and measured faster. The onboarding line reads "pipeline with speculative decoding". +- Records on an M3 Ultra + M5 Ultra pair at the planner's sharded shapes: Qwen3.8 27B at cut 8 (tokens equal to both single-Mac references and to the plain pipeline; 57.7 against 35.6 tok/s), Qwen3.5 9B at cut 4 (near tie at a true tie; 130.9 against 75.1 tok/s) and MiMo V2.6 Flash at cut 47 (tokens equal at 1,024 and 4,096 prompt tokens; 59.2 against 43.1 tok/s). Output matches a single Mac's up to near ties, as the pipeline's does: the verify window's arithmetic differs in its last bits from one-token decode. +- A member's roster plan may name `pipeline_mtp_v1`; a role-aware coordinator must list it too before it accepts such a plan. + +### Cluster planner pricing fixes + +- GLM-5.3 Flash tensor parallel: the plan now counts the NextN (MTP) layer every Mac holds beside its share (4.2 GB), the request memory its speculative rounds add, and the decode speed-up the rounds measured, so it no longer admits a pair the load gate then refuses or predicts decode too slow. Two M5 Ultra 256 GB still plan it as tensor parallel on equal shares with eight concurrent requests, on a new pair and after the first load measured the link. +- A pipeline's prompt hop across the cable is priced by the bytes it carries (a GLM chunk is 64 MiB), from the link probe's two record sizes, instead of as one 4 MiB record. +- Requests that answer fewer than 64 tokens (the warm-up canary, the setup's test answer, readiness probes, a quick "Say hi") are no longer speed records, so they no longer choose the mode or the request a plan is made for. +- A Mac with a model loaded no longer runs the GPU speed benchmark when the other Mac checks for updates every minute or plans: it uses the speed index it last measured while idle. + +### Two-Mac cluster prompt prefixes per tenant + +Both Macs of a cluster now keep and reuse prompt prefixes, in memory and in their encrypted SSD tiers, only for the request's own tenant, as one Mac does: the leader gives both ranks each request's cache switch and a SHA-256 digest of its cache scope (never the scope itself), every prefix key and SSD record scope carries that digest, and a request whose prefix cache is off (a remote request without a cache scope, or a GLM or Qwen request with images or video) reuses and keeps nothing on either Mac. Before, every request on the pair shared one prefix cache. Requests from the local endpoint carry no partition and keep the earlier behavior and bytes. Both ranks bind the partition into the request fingerprint they compare, so ranks given different partitions fail the request. `darkbloom-cluster-pair-check request --request-prefix-cache off|tenant:SALT` writes a qualification request with a partition. + +### A request's tokens do not depend on what it is batched with on the new MLX core + +- Cluster workers, the single-Mac reference and the tensor-parallel check now set `MLX_QMV_BATCH_INVARIANT=1` before MLX starts, unless their launcher set it. The cluster's MLX core then keeps quantized products of a few rows (speculative verify windows, rows of several requests in one launch) on its per-vector kernels, as before it took MLX main's new kernels for 6 to 16 NVFP4 rows and 8 or more affine rows, whose results change with the row count. A request served beside others keeps the bytes it gets alone. Each process logs `darkbloom-qmv-batch-invariant-v1` with the value and who set it. Single-Mac serving is unchanged. + +### Faster Qwen tensor-parallel decode on two M5 Ultra + +- Qwen3.8 27B tensor parallel on two M5 Ultra decodes about 6% faster for one request (75.8 to 80.5 tok/s at 256 tokens, 62.7 to 66.8 at 1,024). The exact decode projections take a layout measured on the M5 Ultra for a verify window's vectors (rows in registers). Outputs are unchanged byte for byte, and other chips keep their layouts. + +### Pack Qwen MoE tensor-parallel expert and shared reductions + +Qwen routed-expert tensor parallelism now carries the shared expert's float32 +partial in the routed experts' collective: two collectives per layer instead of +three, with every summed and rounded value unchanged. The load agreement +(`qwen-moe-down-projections-f32-sum-before-weighting-packed-v3`) and the +tensor-parallel check's launch version refuse mixed builds. Placement now +charges the top-K expert rows once per layer instead of the largest payload on +every collective, and the request ledger charges the packed payload's source +partials. Full-model hardware qualification on the pair is still required. + +### Qwen3.8 27B pairs register with the coordinator by default + +- A Qwen3.8 27B pair set up with `darkbloom cluster` now registers with the coordinator and can serve public traffic. With the default `[backend] mtp_mode = "auto"`, the setup used to carry the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry. The other Mac therefore refused every cluster approval ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"), and the pair served on the leader's local API only, although the setup said it was qualified for public traffic. +- The assistant's speculative decoding has no parity qualification, so it stays on local clusters. Under `auto`, a cluster served through Darkbloom is planned without it, as are the re-plans after an update or a memory refusal. `darkbloom cluster local` keeps it. The cost is speed: on two M5 Ultras, one request decodes at about 40 tokens/s without the assistant and about 93 tokens/s with it. +- `mtp_mode = "on"` keeps the assistant in either case. A cluster served through Darkbloom is then not offered to the coordinator, and the setup says so in its public-traffic line instead of claiming qualification. +- The leader now checks a coordinator's approval with every rule the save applies, the assistant rule included, before it stops either Mac's part or sends anything over the cable. The pair is not offered, with the reason in one line: `Not offered for pairing: this Mac's check refused it: Qwen's speculative assistant serves local clusters only …`. +- Public speculative decoding for Qwen pairs needs qualification evidence of its own and is a follow-up. + +### Request-owned tensor-parallel lanes for every Qwen row + +- Every Qwen tensor-parallel row (Qwen3.5 9B, Qwen3.8 27B, Qwen3.5 and Qwen3.6 35B A3B) now serves through the request-owned batch path the 27B used: main's paged KV host, independent lanes at capacities 1 to 8, the resident and SSD prompt-prefix tiers, committed-token logprobs, and automatic widening that keeps the running shares. Each row's LOAD reservation, placement quote and widening quote are priced by its own geometry (its per-rank KV heads and recurrent state, and a routed-expert row's packed MoE partials). Capacity one is the same path one lane wide. A row that can also run the pipeline keeps the pipeline as a planning candidate while tensor parallel is priced by its quote. +- A routed-expert cohort runs each row's router, shared expert and selected experts with that row's own arithmetic and sends every row's packed expert and shared partials in one collective, so a wider cohort still issues two collectives a layer and every row's tokens equal its solo bytes (`moe-rows-one-collective-v1` in the load agreement). +- The Qwen3.5 9B's inline head now runs as the tensor-parallel speculative assistant beside the 27B's (the assistant inventory and quote follow each row's configuration). The A3B rows' heads are routed-expert layers the tensor assistant does not load, so they serve without speculation. +- Each rank's cut of a row-parallel projection, expert bank or expert input column is copied once into a row-major buffer at LOAD. The interior-axis gather left a transposed view, which every quantized matmul and expert gather copied whole at each call: a routed-expert decode step copied the rank's gate/up and down expert banks for every layer, and every row copied each dense row-parallel weight. Values are unchanged. +- A tensor-parallel decode step is submitted to the GPU layer by layer while it is built (`Qwen35LayerSubmission`), and decode steps, assistant rounds and their selection encode into command buffers of up to 100 operations instead of the worker's 16, as GLM's TP decode does. Tokens are unchanged. +- Batched decode rows take each row-parallel projection's cached FP32 scales and biases, the ones its single-row forward reuses (`QuantizedLinear.independentRowsForward`), instead of widening the BF16 constants inside every quantized matmul, where MLX made that widening on the thread's default GPU stream rather than the caller's. A widened step no longer spans two GPU streams there, and two kernels a projection a step go away. Values are unchanged. +- The single-lane tensor-parallel owner is retired with its own page pool, its prefix cache and `DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV`; Qwen tensor parallel now requires the authenticated sealed data plane, and each lane reserves its full context at LOAD instead of growing by granules. +- Full-artifact qualification on the pair is still required. + +### Qwen27 tensor-parallel prefix SSD tier + +Keep the Qwen27 TP batch owner's prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt restores its prefix after both Macs restart. Each rank writes its own shard (and the assistant's trusted history) behind serving after bilateral clean retirement. The sealed vote now counts SSD records, and a second exchange confirms that both ranks restored, or both prefill from zero. Records are scoped by plan, shares, artifact, storage, both builds and assistant policy, never by membership epoch. The prefix agreement field becomes `qwen-tensor-parallel-prefix-v2`. + +### Qwen27 tensor-parallel ranks reserve only their own heads + +Each tensor-parallel rank now reserves the request state it actually holds: its own KV heads, linear-attention heads, and its own rows and columns of the fused projections and projection constants under the chosen split. The replicated assistant, hidden-width buffers and gathered logits stay whole on both ranks. Setup quotes both ranks of every supported split. Placement charges each Mac its own figure. It keeps a split for later widening only when, on each Mac, the serving owner's weights and request plus the widened load fit, because widening is previewed before the old owner is released. On a busy second Mac, onboarding can therefore pick a split that widens to two speculating requests instead of one that never can. The whole-model figure remains the bound either rank stays under. + +### Qwen27 tensor-parallel resident assistant + +Discover and fully quote the catalog Qwen27 embedded assistant during normal cluster setup, retaining the native inventory policy through bilateral launch and READY. Eligible concurrent requests keep independent histories and accepted-token credits while sharing captured target verification; ordinary media, logprob and history-filter paths retain their capabilities. Price surviving cohort backing, the next verification window and assistant prefix ownership through checked retirement. Explicit MTP off retains the fully quoted ordinary target. Full-artifact correctness and release qualification remain separate from component fixtures. Bound the assistant's trusted-history flush to evaluated 512-row blocks (first draft and ordinary decode), and price a verify window by what it writes: partial-page replacements and segment slack, not a second history. At the 64K profile the whole-model bound for one speculating request fell from about 66 GiB to 22 GiB, and for two from 96 GiB to 36 GiB; installed qualification is separate. The saved setup's status binding carries the speculation the session derives, so a pair serving the resident assistant reads as ready instead of stale and automatic setup finishes; capacity-one refusals keep their capacity or deadline reason. The resident owner's memory gate measures compression and swap-out from the start of each served scope instead of the owner's whole life (limits unchanged), so ordinary background compression on a busy Mac no longer refuses later requests. Concurrent speculative requests verify each request's draft window with that request's own single-window arithmetic inside one collective per row-parallel projection, so they emit exactly the tokens they emit alone. One batched product changed kernel at four three-column windows and altered near-tie tokens. + +### Qwen tensor-parallel decode with batch-invariant projections + +Every Qwen tensor-parallel plain decode step, verify window and batched row +(the 9B, the 27B and the dense projections of both 35B A3B rows) now projects +through the SDK's batch-invariant affine kernel. Each position of a speculative +verify window therefore has the bits of the plain decode step that computes the +same token, and each concurrent row the bits it has alone, at any cohort width. +This changes the rounding of every decode projection relative to MLX's own +kernels, so recorded tensor-parallel references must be regenerated once. + +A row-parallel projection reads its bf16 activation directly and writes its +FP32 partial (no separate widening launch and no FP32 copy of its scales), and +its rounded all-sum feeds the fused residual step, so a step runs far fewer GPU +launches. Each rank logs the arithmetic it resolved once per load +(`darkbloom-aqv-kernel-v1`: exact vectors, the kernel's arithmetic and words +per lane on that GPU family, its layouts), and the pair binds whether exact +vectors are on into its load agreement, so two ranks that resolved it +differently refuse to load. `DARKBLOOM_QWEN_TP_EXACT_VECTORS=0` (diagnostic +only, never forwarded to an installed rank) keeps MLX's kernels. + +### Qwen tensor-parallel ranks wait for each all-sum in the kernel that reads it + +The Qwen 3.5 residual step (`ResidualRMSNorm`) now reads its FP32 tensor-parallel +all-sum as a fenced input, as GLM's hyper-connection sites already did, and a +worker turns `MLX_METAL_FENCED_INPUTS` on for every tensor-parallel family whose +kernels read their sums that way (`ClusterResidentModelCatalog.Family +.tensorParallelSumsAreFencedInputs`; a launcher's own value is kept). The kernel +that reads a sum then waits for the CPU itself instead of MLX's separate +fence-wait launch, about 128 of them per verify window of the 27B. MLX consults +the setting only for inputs a kernel declares fenced, so every other launch is +unchanged, and only where the GPU waits changes, never a value. The fused fence +update stays a launcher's choice. Each rank logs the choice (`fenced_sums=` in +`darkbloom-aqv-kernel-v1`) and binds it into the load agreement. + +### Qwen tensor-parallel speculative rounds keep the GPU busy + +A single-request speculative round no longer waits for each assistant draft +step before building the next one, and no longer waits for the drafts before +building the verify window: the draft chain and the window are submitted back +to back, and the window itself is submitted layer by layer as a decode step +already was. The drafted tokens' vocabulary check is evaluated with the window +and read when the window is confirmed. Every rank still runs the same +collectives in the same order, the emitted tokens are unchanged, and a failure +on either rank fails the round on both. Batched rounds keep their draft +schedule. `DARKBLOOM_QWEN_TP_MTP_PIPELINED_DRAFT=0` (diagnostic only) waits for +each draft step. + +### Faster Qwen tensor-parallel verification: windows evaluated whole + +Qwen tensor-parallel speculative verify windows are evaluated whole instead of +being submitted to the GPU one decoder layer at a time. On two M5 Ultra Macs +serving Qwen3.8 27B this makes a single request about 18 % faster (60 against +51 tokens per second) and four concurrent requests about 5 % faster, with +identical outputs. `DARKBLOOM_QWEN_TP_WINDOW_LAYER_SUBMISSION=1` (diagnostic, +never forwarded to an installed rank) submits windows by layer again; both +ranks bind the choice into their load agreement. + +### Qwen3.8 27B at its native context on a tensor-parallel pair + +- A Qwen3.8 27B pair serving in tensor parallel accepts the context a single Mac serves: prompts up to 262,143 tokens and up to 32,768 output tokens within 262,144 (previously 32,768 + 32,768 within 65,536). LOAD and the planner still size the pair for the 32,768 + 32,768 request at every width (one to eight lanes), so no lane reserves KV for the whole context in advance. Each longer request is charged at its own context when a rank reserves it, and each rank's live memory gate admits it or refuses it alone (HTTP 503 with the context the pair serves now) while other requests keep running. Readiness and keep-warm answers carry that serving context. The 27B's pipeline modes and every other Qwen row keep their limits. +- Qwen tensor-parallel paged lanes reserve their prompt and a 1,024-token granule when they open and grow between steps, instead of reserving every page of the prompt and output at once. Outputs are unchanged byte for byte. +- The 27B's worker profile, load agreement and installed setup fingerprints change. Existing 27B setups re-plan after the update, and 27B pair qualification records are recorded again. + +### RDMA setup guidance for macOS 27 + +When RDMA over Thunderbolt is turned off, `darkbloom cluster` and its setup screens now point a Mac on macOS 27 or later to Apple's switch in System Settings (Privacy & Security, RDMA over Thunderbolt, then restart) instead of macOS Recovery. Macs on macOS 26 keep the Recovery steps with `rdma_ctl enable`. Darkbloom still never changes the setting itself. + +### Releases carry their cluster runtime facts + +- Every release lane (dev branch, staging, prod) now computes the cluster runtime facts of its final signed app with that app's own CLI and worker: the digests of the cluster worker, placement tool, Metal library and paged-attention source, and for each model the build qualifies on a cluster and the environment's catalog has, the digests of its capability and its pair-serving grant. The job summary and a run artifact show them in every release. +- Each model's pair-serving grant lets a coordinator form its two-Mac pairs: a pair member reports only hardware capabilities, so without a grant no pair of GLM-5.3-Flash or Qwen3.8-27B forms. A declared public model's grant names its declared mode families; any other model's is the grant of the build's own qualification records, or none. +- GLM-5.3-Flash and Qwen3.8-27B are declared for public cluster traffic in pipeline and tensor parallel (owner decisions, 2026-10-31): their entries carry parity qualifications from which a coordinator derives their public qualifications, and it applies them to each declared mode family on any Apple silicon pair, with sampling and tools, and in tensor parallel images and video as the environment's catalog lists them. The qualifications name the evidence placement (two Apple M5 Ultras; a pipeline cut at half the model's layers), not a limit; no pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record, so both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash runs the serial prefill schedule only, so its schedule 2 entries are inert. Every other model's clusters serve their owner only. The setup says a declared model is qualified for public traffic in pipeline and tensor parallel. +- The release registration carries the facts as `cluster_runtime` only when that environment's repository variable (`DEV_CLUSTER_RUNTIME_ENABLED`, `STAGING_CLUSTER_RUNTIME_ENABLED`, `PROD_CLUSTER_RUNTIME_ENABLED`) is `true`; a coordinator that accepts the block then approves the build's two-Mac clusters automatically. Unset, the registration is unchanged and a failure to compute the facts only warns. +- `darkbloom cluster runtime-facts` (hidden) prints schema `darkbloom_cluster_runtime_v2`: the same digests as before plus each model's `pair_serving_grant` and `parity_qualifications`. + +### Cluster runtime facts leave out another model's catalog ID of a shared artifact + +- A release's cluster runtime facts no longer fail when one artifact is listed under the catalog IDs of two registered models. Production lists `gemma-4-26b` and `gemma-4-26b-8bit` for the same Gemma 4 26B artifact, and the build registers them as two runtime models that only the manifest tells apart. Only the 8-bit one is qualified on a pair, so `darkbloom cluster runtime-facts --release-candidates` stopped with "Qualified cluster models the release cannot describe: gemma-4-26b", and a production release with `PROD_CLUSTER_RUNTIME_ENABLED=true` would have stopped after signing. +- A catalog model ID whose candidates the build's worker describes only as another registered model is now that model's: it is left out of the facts and named on standard error (`note: left out, the catalog model ID of another registered model: …`). A catalog model ID of which the worker describes no candidate at all still fails the step. + +### Cluster served speeds count only for the build that served them + +- A two-Mac pair's planner and request router now use a served request's speed only for the worker build that served it. Each speed record in `~/.darkbloom/cluster/served-speed.json` names every rank's worker build; records from another build, including every record written before this release, give no speed and age out of the file, so a new build plans from the share probes and link measurements until it has served. Speeds served by older, slower builds no longer hold a tensor-parallel split where the current build's own probes balance it. The plan is still made for the prompt and answer lengths the pair's clients send. +- The plan says how many records it left out (`N record(s) from other worker builds ignored`). `darkbloom-cluster-plan plan --served` and `route --served` use records only for the build named with `--served-build SHA256`. + +### The cluster comes back after a reboot + +- After a restart each Mac serves again once it is logged in (by itself with automatic login on); `darkbloom cluster` says which applies to each Mac. +- `darkbloom cluster` (leader and members) installs this Mac's cluster service as a per-user LaunchAgent (`io.darkbloom.cluster-service.`): launchd starts it at login and runs it under the cluster supervisor (`darkbloom cluster service --supervise`), which restarts it after 15 s doubling to 300 s and parks it after three quick failures; launchd restarts only a supervisor that crashed. Running `darkbloom cluster` again keeps an unchanged agent, replaces a changed one, restarts a parked one, and takes over from a service an earlier version started in a terminal. Nothing is asked beyond the cluster link's one approval. +- `darkbloom cluster stop` stops this Mac's cluster service and removes its login agent (on the leader the cluster stops serving first); unpairing the last pairing (`darkbloom cluster pair --forget`) removes it too. `darkbloom status` shows whether the cluster service starts at login, whether it runs, and its supervisor's phase. + +### Cluster background network identity + +- Associate the cluster login service with its enclosing app so macOS can retain Local Network approval when the setup terminal exits. +- Replace older unassociated jobs through the normal cluster command; preserve idempotent startup and stop behavior. +- Keep socket failure details in lease diagnostics and explain the session lifetime of an ad-hoc development service. + +### The cluster service is no longer restarted while its pair is registered + +A pair registered with the coordinator could restart the cluster service of a Mac many times a day (about every 15 minutes on one DevNet leader: "heartbeat missing for 75 s while its process is alive"), and each restart dropped the pair for a short time. The Mac's part inherited the service's heartbeat file and wrote its own heartbeats into it, and the supervisor does not count a heartbeat from another process. The part now writes its heartbeats to a file of its own (`~/.darkbloom/cluster-setup/part-health.json`). + +### Cluster sessions without a fixed lifetime; rank lease and keep-warm + +- A model served by two Macs stays loaded and serving until you stop it, and a Mac that disappears is reported at once instead of stalling. +- A two-Mac cluster session has no fixed lifetime and no request count any more. The 300-second session (1,800 for MiMo), the sixteen-request cap, the installed session's teardown at its deadline, the rotation to a new session after sixteen requests and the member session's 900-second cap are removed; a loaded model stays resident and serving until it is stopped (`darkbloom stop`, an operator unload, an autopilot model switch) or a real failure is detected. The capability record drops `maxLifetimeSeconds` and `maxRequests`. +- Each worker holds a renewable rank lease instead (S03): armed before its weights load at most one grant away, renewed every 5 s for 30 s by its owner with an `extendDeadline` line on the worker's control pipe, which the worker reads from launch, through the load. An owner that stops renewing (it stopped, died or lost its link) leaves the worker to end by itself within the time to live, through the forced exit that releases MLX's wired memory first. The leader renews each remote owner's lease the same way (`renew` frames), and each owner renews its own worker's. +- A cluster member honors the coordinator's grant lease (S15): `native_pair_lease` frames move its deadline (a grant may leave at most 120 s plus 5 s of clock allowance); an established session survives a dropped control connection for the 90-second grace, and the member claims it again with `resume` in its registration. +- Keep-warm, on by default (S27): a GPU pulse on each worker's own executor every half second while idle once the first request has run (back-off for a minute after a slow submission), and a 1x16 data-plane exchange both ranks run about once a second while idle, sequenced by the leader; a failed exchange ends the session cleanly. `darkbloom-cluster-pair-check --keep-warm off` and the worker's `--keep-warm off` turn it off for comparison. +- `darkbloom-cluster-pair-check` takes any number of repetitions, idle gaps between them (`--idle-seconds`) and a qualification switch that stops renewing both leases (`--stop-renewals-after-seconds`). +- A Mac that vanishes from a cluster is a stated failure, not a stall: when the other member's link control connection closes or goes silent and does not come back within the link's own re-dial time (5 s for a closed connection, 10 s for a silent one with the default link timing, never past the 30 s rank lease), the leader fails the request in flight at once with the reason (`link edge: follower lost: ...`), stops waiting for cleanup proofs that can no longer arrive (the session is quarantined, rank 1 stays unproven, the other Mac's own lease and device journal still end its rank), and exits instead of lingering for minutes; the follower likewise fences a vanished leader's session at once instead of at the end of its lease. A follower that releases a session without a cleanup proof (its owner ended at launch) ends the leader's wait the same way. The follower now says why its rank ended (its worker's last word, e.g. the stage-load memory gate's refusal) and the leader's incident carries it, so such a start is classified `memory_gate_refused` with the follower's own numbers instead of an unexplained `peer_lost`. A cluster member whose coordinator control connection ends or loses trust says why (`Distributed serving stops: .`) and exits with a failure status. The stale bootstrap-directory check no longer connects to a listener's socket (a connect could fail a live launch); it reads the descriptor tables instead. +- Nothing of a dead cluster session is left behind (orphan eradication, ported from the owner's oMLX and ThunderMLX lifecycle work). An orphan sweep runs at every member's start and end and before every supervised restart, and on demand as `darkbloom cluster reap [--json] [--no-wait]`: a worker or owner whose parent process is gone is given its own contract (the rank lease, the owner's longest signal allowance and the forced exit's dead-man) to end, then SIGTERM, and SIGKILL only after the kill margin, and only while its process number still holds the same process (same start time; a reused number is never signalled); a device journal whose owner died is cleared through `cluster recover`'s proof; bootstrap directories whose socket no process holds any more are removed. `darkbloom cluster verify-teardown [--json] [--baseline-wired-bytes N] [--samples N]` reports, after a stop, whether any cluster process, wired memory above the baseline (tolerance: the larger of 1 GiB and 1/128 of physical memory), stranded journal or bootstrap directory is left (`darkbloom_cluster_teardown_verification_v1`, exit 1 when not clean). `darkbloom cluster cancel-all` force-cancels every request served on this Mac on its own: SIGUSR1 makes an owner fence its worker (the protocol's own drain) and a worker end its requests through the forced exit. A forced exit whose release keeps completing durable writes (`ProcessForcedExit.noteProgress`) gets its 20 s dead-man extended exactly once, to 40 s, and never otherwise. Every rank is started with MLX's command-buffer bounds (`MLX_MAX_OPS_PER_BUFFER=16`, `MLX_MAX_MB_PER_BUFFER=512`) unless the operator pinned them. + +### Cluster setup respects model reasoning defaults + +- Cluster setup tests a response using each model's default reasoning controls, so GLM-5.3 Flash no longer rejects the generic probe because it sends a binary thinking override. Reasoning-only output remains visible when the test token budget expires. + +### Cluster pairs serve sharded deployments by default + +- The planner chooses tensor parallel or a pipeline for the Macs it detects; phase split, phase split with MTP, the pipeline-prefill/tensor-decode hybrid and the per-request "alone" route are kept but off by default, reachable only behind `DARKBLOOM_CLUSTER_HANDOFF_MODES=1`, and a setup saved with one of them is refused at start without it. The onboarding's deployment line names the sharded mode. +- Qwen models with an MTP head and MiMo V2.6 Flash can decode as speculative rounds across the pipeline (`pipeline_mtp_v1`): the last Mac holds the head and a copy of the token embedding, drafts, and both Macs verify the drafts in one window. The planner credits the rounds only from what the same placement served with and without them, and a pair serves them only where its own qualification records pass. +- MiMo V2.6 Flash keeps prompt prefixes on both Macs, in memory and in the encrypted SSD tier, restored on both or neither. +- The pair's SSD prompt-cache tier carries its daily write cap across restarts, keeps other plans' records within one byte budget instead of wiping them, stores speculative history once per record, reads records page-aligned without a copy, and hashes model files in parallel. + +### Quantized SSD prompt-prefix records on the two-Mac cluster + +- The pair's encrypted SSD prompt-prefix records now store attention rows at the single-Mac checkpoint precision, `balanced` by default, like every other model's checkpoints: older rows in 4-bit keys and values (affine groups of 64, FP32 scale and offset, keys Hadamard-rotated) and each record's newest 128 rows exact. Recurrent, convolution and speculative-head state stays exact. A Qwen 3.8 27B tensor-parallel rank's attention rows at 32,768 tokens take about 3.2 times fewer bytes; GLM-5.3-Flash DSA layers about 1.8 times fewer, in pipeline and tensor parallel (BF16 latents; its index keys, pool gates and MTP history stay exact). Live KV stays native. +- A prefix restored from a quantized record is close to, not identical with, computing it again. `engine_v2_kv_checkpoint_quantization = "native"` (or `DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION=native`, per model with `engine_v2_kv_checkpoint_quantization_by_model`) keeps the pair's records byte-exact. Both Macs must resolve the same precision: the leader does not sync it, and the ranks bind it into their load agreement and refuse to load otherwise. Records of one precision are never restored under another. +- Quantizing a decoded row again does not give it back (the codec is not idempotent on its own output), so a record written from a request that was itself restored from a record keeps the restored rows' first encoding instead of quantizing them again: through repeated restore-and-extend cycles, such as a long conversation, each restored row stays as it was first stored. +- `darkbloom-cluster-tp-check run --prefix-records native|balanced|k8v4|k8v8` measures a record on real weights: per-layer errors, bytes against a native record, the prompt tail scored from the captured and the restored state, and the output after the restore. `darkbloom-cluster-pair-check --prefix-ssd-quantization` selects the workers' record precision. + +### Two-Mac clusters follow the provider's KV quantization + +- A pair's stage KV now uses the same live precision a single Mac uses for the + model: `engine_v2_kv_quantization` (global or per model) and + `DARKBLOOM_CBV2_KV_QUANTIZATION`, resolved on each Mac and passed to its + worker. The default stays native; pairs whose Macs keep it are unchanged. +- With `balanced`, `k8v4` or `k8v8`, the Qwen 3.5 family (Bonsai included), + Gemma 4 and Nemotron 3.5 stages and every Qwen tensor-parallel row's + request-owned lanes (9B, 27B, Qwen3.5/3.6 35B A3B, any capacity) store packed KV on the provider's own pool, after the same kernel check, + and their memory planning counts packed rows. Both Macs must resolve the same + precision; otherwise their load agreements differ and the pair refuses to + load. Set the pair's model to `native` per model to keep a packed global + setting off the pair. +- Packed stages keep no prompt prefixes, as on one Mac for packed KV. Phase + split, GPT-OSS and GLM refuse a packed precision; MiMo stays native. The pair's SSD prefix records stay exact native states. +- `DARKBLOOM_CLUSTER_KV_BACKEND=contiguous` is removed: cluster stage KV is + paged only. + +### Steadier, visible tensor-parallel choice in two-Mac clusters + +- Keep each pair's last eight link measurements from the last 30 days and plan + on their median, so one fast or slow load no longer switches a model between + tensor parallel and a pipeline. Link files from earlier releases still read. +- End a model's line in the setup's model list with a short reason when the + model supports tensor parallel but is split otherwise, such as "tensor + parallel: slower here"; models without tensor parallel show nothing extra. +- Explain that Qwen3.8 27B leaves out the pipeline because only tensor parallel + keeps images, video and logprobs, instead of saying no pipeline fits. +- Read the saved link measurements in `darkbloom-cluster-plan plan` when + `--link` is not given (or `--link-probes FILE`), say so, and print reduction + costs in ms or µs. + +### Cluster stop ordering + +- A paired leader now retires its owned part before asking its follower to stop, preserving the native shutdown channel. Failed retirement or missing peer acknowledgement keeps the login service available for recovery and returns an error. + +Require a fresh local supervision acknowledgement before stopping the peer so stale idle status cannot bypass a child start already in flight. + +Keep follower lease intent alive through local planned drain; serialize background serve/stop reconciliation and wait for outstanding running leases before publishing stop acknowledgement. A stop the pair could not finish exits with status 1 and the pair's reason, without usage text. + +### Stop a cluster Mac whose peer is gone + +`darkbloom cluster stop --local-only` stops only this Mac's cluster service and removes its login agent. It never asks the other Mac, for when that Mac is gone for good. Without the flag, a leader still drains the pair first and keeps its service when the member cannot acknowledge. The output says that the other Mac was not asked to stop. + +### Two-Mac clusters place tensor parallel first wherever it fits + +- A model whose tensor-parallel layout fits both Macs is now set up in tensor parallel even where the speed estimate favored a pipeline; the setup says so ("the model fits, so both Macs share every layer of every token") instead of claiming a gain it does not predict. A setup that loads now still goes ahead of tensor parallel that would not, and predictions are still shown. +- A new pair's first setup is tensor parallel too: before any load has measured the cable, it plans on the same assumed sealed reduction a forced plan uses, labelled as assumed. +- Automatic widening never assumes a link cost: it plans only on the pair's own recent sealed link measurement, and without one it keeps the running setup. +- `darkbloom-cluster-plan plan --tensor-parallel-first` plans the same way; without the flag the plan tool keeps the speed comparison. + +### A tensor-parallel cluster registers with the coordinator + +- A pair that serves a model in tensor parallel (GLM-5.3-Flash, Qwen3.8-27B) now registers its roster plan with the coordinator. The plan names `tensor_parallel_v1` and no layer cut, as the coordinator requires; before, the member registered the stage end as a cut, refused its own plan, and the pair served only its local API. A setup with unequal tensor-parallel shares is refused at registration until the plan carries its shares. +- The onboarding's start line for a cluster that serves through Darkbloom no longer says public serving is off in this build: it serves its owner's requests, and public requests where Darkbloom has qualified the model and split. +- A plan in `pipeline_prefill_tensor_decode_v1` (pipeline prefill, tensor-parallel decode) also registers: the coordinator lists the mode, and the member no longer refuses its own plan. + +### Tensor-parallel shares balanced by each Mac's measured speed + +- Time each Mac's own share of a dense Qwen model when it loads in tensor + parallel (at most about a second and a half, alone, nothing crossing the + cable), and keep each Mac's newest timing per share and model for 30 days on + the leading Mac. The next plan balances the shares by those timings: with the + timings an M3 Ultra and an M5 Max measured, Qwen3.8 27B is planned 1:1 + instead of 2:1 after one load. A Mac short of memory skips the timing, and it + never fails a load. +- Stop predicting a larger tensor-parallel share faster than a smaller one: a + Mac's measured shares are no longer drawn toward its whole-model speed, and + what the pair served corrects all of a Mac's measured shares alike. +- Read the saved share timings in `darkbloom-cluster-plan plan` (or + `--share-probes FILE`) and name the shares used, as the setup plans. +- A load that serves the speculative head balances its shares on each Mac's measured verify window rather than its single-token step, because its rounds run windows: on the Qwen3.8 27B pair that moves the split from 3:2 to about even. + +### Fixed + +- Automatic cluster planning considers tensor-parallel placements independently + of pipeline layer cuts and counts enumerated candidates instead of unused + pipeline-cut combinations against its search limit. Unsupported runtime modes and rank counts now explain the pipeline + fallback before requesting a link measurement, without claiming an unmeasured + speedup. This does not enable tensor parallelism for GLM. + +### Cluster validation, tensor batching and media ownership + +- Repair local two-Mac setup, installed lane propagation, encrypted peer agreement, + request-scoped placement and delayed automatic batch replacement without + weakening native teardown, memory or failed-qualification gates. +- Preserve measured shard rates and independently price native batch capacity; + exact Qwen3.8 27B retains feature-preserving TP selection with the complete + native request reservation coexisting with LOAD scratch and allocator demand. +- Preview Qwen27 widths 8, 4 and 2 against current bilateral memory before + replacing the serving owner, then recheck the exact proposed width after release. +- Pass the indexed devices, recorded keyed pair-link costs and filtered served + history into automatic replacement, allowing its tensor candidates to be + considered instead of silently using an unmeasured link. +- Add Qwen27 independent TP histories, grouped collectives, per-request sampling + and captured logprobs, with checked bilateral cancellation and retirement. +- Coalesce nearby Qwen27 TP token acknowledgments within the existing bounded + scheduling window so ready rows can decode together; joining, prefill, + cancellation and retirement continue without waiting for a silent client. +- Reuse mutually held original-grid Qwen27 TP prefixes with bounded resident + snapshots, fresh per-request histories, separately priced capture/cache banks + and publication only after bilateral clean retirement. +- Route exact Qwen27 images and video through bounded provider preparation and + the native vision owner, retaining encoded data and host/native allowances + until their respective completion fences. Unsupported controls refuse explicitly. +- Bind streamed logprobs to committed content events and repair local HTTP + reasoning, sampling, usage and tool/constraint parity handling. +- Repair Qwen expert reductions and mixed-router accounting; add Bonsai packed-row + arithmetic and qualification coverage; preserve Gemma prompt arithmetic, + catalog aliases and prefix restore/chunk semantics. +- Repair GPT-OSS, MiMo and Nemotron native independent-history batching, paging, + cancellation and prefix behavior, including existing MiMo speculative/phase + state accounting. Historical phase support is not TP release qualification. +- Order fast Metal fence waits after current-pass GPU producers through the + matching native core pin; installed clustered-concurrency validation remains required. +- Retain explicit full-model hardware gates. Component tests and source support + do not establish universal TP, media parity or release readiness; Qwen27 TP + text speculation remains unfinished; full-artifact prefix/media qualification + and final automatic-planner validation remain separate gates. + +- Preserve an explicit local fast-synchronization diagnostic choice through both installed TP owner and native worker launches. Only canonical `0` or `1` is forwarded; normal defaults and placement remain unchanged. + +Every tensor-parallel worker, widened Qwen rows included, keeps fast synchronization; explicit local synchronization choices still take precedence. Native batching and model capabilities remain enabled. + +Authenticated Qwen3.8 27B TP owners now use the same fully priced request-owned execution at one lane and wider capacities. Automatic capacity changes preserve the tensor split, preventing capacity changes from switching the attention path or repartitioning arithmetic. The original exact-output acceptance gate remains required. + +- Forward an explicit local eager-fence-commit diagnostic through the installed tensor owner and native worker, reporting its canonical value at startup while preserving the default. +- Report completed decode steps by actual batch width once per retired or failed scope, without request content or extra memory samples. + +### Cluster worker protocol 2: prompts cross as packed token IDs + +- A cluster reservation carries its prompt as packed little-endian token IDs (base64) with an explicit count instead of a JSON number array, and the leader builds a relayed command's link wire once. A 31.5K-token reservation decodes in about 1 ms per hop instead of about 12 ms, which shortens time to first token on long prompts. Both Macs must run the same release: a Mac on the previous protocol is refused at setup or pairing ("Install the same Darkbloom release on both Macs, then run `darkbloom cluster` again"), never in the middle of a request. + +### Preserve truncated reasoning in collected responses + +- Keep unfinished prompt-side thinking in reasoning fields for collected Chat and Responses, retrieval and continued history. Preserve explicit parser overrides, native parsed channels and token usage. + +### Distributed startup signal restoration + +Distributed startup restores both SIGTERM and SIGINT dispositions, including +handler flags and blocked signals, even when one signal was already ignored. +A termination request received before serving starts remains latched. + +### GLM cluster prefill and finite-calibration placement + +- Scan all structural cuts against current local device bounds and choose a common feasible cut through the existing performance-aware planner. +- Run the selected cut through the installed signed quotation and finite owner path; preserve explicit diagnostic cuts. +- Keep predicted speed, measured-best throughput and calibrated serving eligibility distinct. Public GLM endpoint eligibility is unchanged. +- Raise the registered GLM NVFP4 cluster candidate's prefill chunk cap to 2048 while retaining bounded authenticated logical arrays, raw frames and records. Keep the workspace conservative pending scope-matched native/host peak qualification; other models' default caps and public qualification records remain unchanged. +- Allow finite calibration up to 2048 prompt/chunk tokens with the existing 16-output cap and at most 2064 context. Automatic chunk hints ignore prompts shorter than their configured chunk and match artifact identity when available; fallback uses the current model/worker caps without creating a qualification grant. + +### Bounded GLM cluster still-image candidate + +- Add bounded encoded PNG ingress, rank-0 native GLM vision loading and causal feature splicing to the private two-rank pipeline, with additive memory charges and cold media prefix isolation. +- Require the explicit local image qualification profile through `darkbloom cluster local glm-5.3-flash --private-glm-image-qualification`; ordinary text serving rejects images before reservation and excludes the vision tower from planning and LOAD. +- Keep video unqualified and audio refused. Full-model image correctness, memory, cancellation and real CLI/HTTP qualification remain required before a serving modality can be advertised. + +### GLM-5.3-Flash SDK speedups shared with the single-Mac release + +- The SDK's pipelined KDA prefill recurrence now also covers 64 heads on an 80-core M5 Ultra (two + value-row ranges per GPU core): one Mac and each GLM pipeline stage prefill faster with bit-identical + outputs; a tensor-parallel rank's 32 heads keep their cut, so tensor-parallel GLM is unchanged. +- The CBv2 MTP loop can submit every draft step as soon as it is built (on for the single-Mac GLM + profile); the two-Mac GLM path runs its own speculation loop and is unchanged. + +### GLM tensor-parallel decode command buffers and sum fences + +- GLM tensor-parallel decode steps, MTP rounds and lane rounds encode up to 100 operations a Metal command buffer instead of the rank guard's 16, which prefill keeps; each further buffer cost about 10 µs of GPU time (13.24 to 12.56 ms a decode step on two M5 Ultra, tokens identical). +- GLM tensor-parallel workers let the hyper-connection site wait for each all-sum in-kernel (`MLX_METAL_FENCED_INPUTS`; a launcher value is kept). The fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: its multi-threadgroup path (partials above 32 KB) never signals the CPU, which stalled batched lanes about 0.7 s a round. + +### GLM tensor-parallel MTP rounds submit their proposals early + +- A GLM tensor-parallel MTP round (solo or batched lanes) submits its NextN priming and proposals as soon as they are built, so the GPU computes them while the host builds the verification forward instead of idling through the whole round's build: a depth-2 round 23.06 to 21.64 ms (95.9 to 102.7 tok/s) and two lanes 115.2 to 121.6 tok/s on two M5 Ultra, tokens and top logits identical. `darkbloom-cluster-tp-check glm --mtp-early none|proposals|layers` compares the modes. + +### GLM tensor-parallel greedy MTP rounds split the head's vocabulary + +- A greedy GLM tensor-parallel MTP round (solo or batched lanes) reads out only its half of the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum (each rank's half maximum and argmax; rank 0's lower index wins a tie, as MLX's argmax does): a depth-2 round 21.32 to 21.05 ms on two M5 Ultra, tokens and top logits identical. Sampled rounds keep the whole head. `darkbloom-cluster-tp-check glm --mtp-vocab-split yes|no` compares them. + +### GLM-5.3-Flash runs tensor parallel across two Macs + +- `darkbloom cluster` can now serve GLM-5.3-Flash text requests with both Macs working on every layer (tensor parallel) instead of each Mac holding half the layers. On two M5 Ultra 256 GB it chooses this by itself once the cable has been measured: the setup's test answered at 51 tokens/s against 42 for the layer split, and long prompts prefill at about 3,300 tokens/s against 1,450 (one Mac alone: about 1,800), and decode runs at 53 tokens/s. Every byte between the Macs stays encrypted. A repeated prompt prefix (a chat's history) is reused on both Macs instead of prefilled again. Image requests still use the layer split. +- The cable measurement that decides between the two modes now times the encrypted sum as a running model pays it, not cold: it had read three times slower and kept tensor parallel from being chosen. +- The Macs exchange GLM's per-layer sums at half the size: the model's own 16-bit values instead of the same values widened to 32 bits, with an identical result. Prompts prefill about 14% faster. +- Tensor-parallel decode is faster: the worker lets each GPU command buffer take whole expert banks instead of committing one at every expert layer (about 88 commits a token instead of 22), and MLX spends less host time per kernel launch. On two M5 Ultra, decode went from 53 to about 57 tokens/s through the API (62 in the bench). +- Fixed a hang where the GPU could wait forever on an encrypted sum between two GPU steps. +- What a tensor-parallel setup served no longer resets the speeds the planner learned from a pipeline the same Macs served: it corrects only the tensor-parallel figures. Before, after serving in tensor parallel the planner priced the layer split as fast as one Mac alone and switched back to it. This applies to every model the cluster plans. +- The hardware speed prior no longer counts every routed expert of a mixture-of-experts model as read on each decode step. It counts only the experts a token is routed to, and it does not count replicated weights as divided by a tensor-parallel share. +- Greedy GLM-5.3-Flash requests in tensor parallel now decode speculatively with the model's own next-token-prediction layer, which each Mac now also loads (about 4.2 GB more per Mac): each step checks the layer's guess together with the next token and keeps both when the guess is right, so greedy decode produces more tokens per step (two guesses a step: about 76 tokens/s against 63 in the bench on two M5 Ultra). Sampled requests decode as before. +- Tensor-parallel prefill is faster: each encrypted sum between the Macs is now sealed, sent, opened and added in 256 KiB pieces as they become ready instead of as one block, so the encryption overlaps the transfer (a 15.7K-token prompt prefilled at 3,812 tokens/s against 3,554 in the bench). Every piece is still authenticated, and a piece that does not open fails the request. +- Tensor-parallel decode no longer waits between steps for the serving process's answer to each token (whether to go on). The token is handed over at once and the answer is read once the next step is running, so its round trip overlaps the GPU work (two M5 Ultra through the API: about 73.5 to 77 tokens/s). A stop request still ends the output exactly where it was asked for; one extra step may be computed and is never sent. +- GLM-5.3-Flash decodes and prefills faster on Apple silicon, on one Mac and across two: fewer and faster GPU launches for the hyper-connection, mixture-of-experts and sparse-attention steps, and less CPU time per launch. Outputs are unchanged bit for bit. On two M5 Ultra through the API, decode went from about 78 to 90 tokens/s and long-prompt prefill from about 3,470 to 3,540 tokens/s. + +### GLM-5.3-Flash native prerequisites + +- Use one peer-status observation for each finite GLM terminal-context decision, avoiding a false transport-loss rejection across an expected peer close while preserving exact acknowledgment consumption, frozen connection identity and durable owner/fence retirement. Encrypted loopback CPU coverage does not qualify model, GPU, RDMA or serving behavior. + +### Models load when every model's minimum KV fits + +- Loading a model beside others no longer fails with "would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance" while the KV budget still covers every model's minimum. The split gave each model a share in proportion to its per-token KV cost alone. A resident model with a small per-token cost and a fixed per-request workspace, such as Nemotron 3.5 Lightning with its assistant on, could get less than its own minimum and block every further load. Now, when that would happen, each model gets its minimum first and the rest of the budget is split as before; the message now appears only when the minimums together exceed the budget. The model being loaded counts only the 1 GB base minimum until it is built, so Lightning itself can still fail to load, with no KV headroom, when it joins several high-rate models. +- A split that already gives every model its minimum is unchanged. Unloading a model, or a change to the activation reserve, no longer shrinks another model below its minimum. + +### The local Responses API continues a conversation from `previous_response_id` + +- `/v1/responses` on a single Mac and on a cluster now honours `previous_response_id`: the request continues the earlier input and that response's output, as with OpenAI. A follow-up that sends only a `function_call_output` item resolves its tool call instead of failing with 400, and a later turn remembers earlier ones. +- An ID this process does not hold (never served, sent with `"store": false`, dropped from the bounded in-memory store, or from before a restart) returns 400 with code `previous_response_not_found`. + +### Media the model's processor refuses answers 400 on one Mac and on a pair + +- An image or video the model's processor refuses now returns HTTP 400 `Invalid media input.` (`invalid_media`) on one Mac and on a two-Mac pair: for Qwen 3.5 and 3.8 a side below 32 pixels (a 16×16 PNG, for one; the processor does not upscale it) or an aspect ratio above 200:1, a video without a decodable track, or more media than a processor takes. It returned the retryable 503 capacity answer, so the coordinator tried other providers that refuse it the same way. + +### A request's `min_p` now applies on one Mac too + +- A request's `min_p` now applies on one Mac too, as it already did on a cluster pair: tokens less likely than `min_p` times the most likely token are dropped before sampling (values above 1 count as 1). Requests without `min_p`, or with 0, are unchanged. + +### One GPU stream per decode graph, and no GPU-on-GPU fence spins + +With MLX fast fences (`MLX_METAL_FAST_SYNCH=1`) a widened Qwen 3.8 27B +tensor-parallel owner could stop at its first multi-row plain decode (the c14, +c17 and c39 stalls). MLX cast each batched 4-bit projection's bfloat16 scales +and biases to float32 on the thread's default GPU stream instead of the stream +the caller passed, and mlx-swift runs everything else on its own process-wide +stream, so that decode graph ran on two GPU streams. A fast GPU fence wait is a +kernel that spins on its queue until the other queue's timestamp arrives, and +Metal does not promise that the other queue runs meanwhile, so both queues +stopped. The casts (and MLX's other helper ops that dropped the caller's +stream) now stay on the caller's stream, and a GPU stream never spins on +another GPU stream: it waits on a shared event, while the CPU <-> GPU +collective waits keep the spinning fast path. Synchronization only: tokens are +unchanged. Widened Qwen 3.8 27B owners stay on the event path until a two-Mac +acceptance with fast fences passes on this fix. + +### Pair-check reservations keep their media + +- `darkbloom-cluster-pair-check` hands each worker the whole reservation when it moves the deadline to that worker's clock. It dropped still images and Qwen image/video input, so those qualification requests reached the workers without their media. The owner and peer-link hops re-time reservations with the same field-preserving copy. + +### Faster prompts on Macs without neural accelerators + +- MLX's steel affine quantized matmul computes prompt-sized products (256 rows + or more, 64-aligned outputs) in 64-row x 32-column tiles for 16-bit inputs and + 32 x 64 for FP32 partials instead of 32 x 32 on GPUs without neural + accelerators (M1-M4, and the M3 Ultra rank of a pair). On the M3 Ultra alone a + 4,096-token prompt took 2.5% less time (27B 12.37 -> 12.06 s, 9B 3.55 -> 3.46 s) + with the same tokens. `MLX_QMM_STEEL_TILE=32` restores the previous tile. +- Qwen tensor-parallel prompt frames are submitted to the GPU every four layers + while they are built (`DARKBLOOM_QWEN_TP_PREFILL_STRIDE=0` restores whole-frame + evaluation). With both changes the 27B pair at 1:1 reached its first token + 1.4-3.1% sooner (4K 8.22 -> 8.08 s, 16K 36.7 -> 35.5 s, 32K 81.8 -> 80.0 s) and + the 9B pair 1.1-2.3% sooner (4K 2.63 -> 2.60 s, 32K 27.5 -> 26.9 s), with the + same tokens. +- Diagnostics: `darkbloom-cluster-tp-check qwen-prefill` (one rank's prompt + frames, layers and projections), `DARKBLOOM_QWEN_TP_PREFILL_FRAME_TIMING=1` + and `pair-check --worker-environment`. + +### Concurrent tensor-parallel requests draft together + +- When several speculative requests on a two-Mac tensor-parallel pair draft in the same round, their assistant steps now run as one batch: one head call and one pair of sealed exchanges per draft step for every row, instead of one per row. Six concurrent requests need about a third of the reductions they needed before, and every request still produces exactly the tokens it produces alone. + +### Concurrent tensor-parallel requests verify together + +- Concurrent speculative requests on a two-Mac tensor-parallel pair now stay in one verify cohort. A request that still has up to one round of accepted tokens waiting joins the next round from its own settled position instead of waiting for its queue to drain, so requests that started a step apart no longer take turns verifying alone. Every request still produces exactly the tokens it produces alone. + +### Concurrent tensor-parallel requests share each draft step's weight reads + +- On a two-Mac tensor-parallel pair, speculative drafts now use the same batch-invariant kernel as decoding. When several requests draft in the same round, every draft step after the first runs all of them through one assistant pass, and every head call serves all of them, so each weight is read once per step for the whole batch instead of once per request. With eight concurrent Qwen3.8 27B requests, a round's draft work on one Mac fell from about 38 to 24 ms. +- A request proposes the same tokens alone and in a batch of any size, and every request still produces exactly the tokens the model produces without speculation. Proposals can differ from the previous kernels at near-ties, so the share of accepted proposals can shift slightly; the output never does. +- Both Macs must use the same draft kernel or the pair refuses to load. `DARKBLOOM_QWEN_TP_MTP_EXACT_DRAFTS=0` (diagnostic only, never forwarded to an installed rank) keeps the previous kernels. Single-Mac speculative decoding is unchanged. + +### Six-request tensor-parallel batches + +- Automatic batching on a two-Mac tensor-parallel pair can now choose six concurrent requests, between four and eight, when eight do not fit. Pipeline batching keeps its widths of two, four and eight. + +### Qwen tensor-parallel verification keeps its measured weight-read tiles + +- Two-Mac tensor-parallel Qwen pairs verify concurrent requests with tiles of at most five vectors per weight read again (tiles of four past five), instead of whole-cohort tiles of eight or sixteen. On two M5 Ultra Macs serving Qwen3.8 27B, four concurrent requests reach about 90 tokens per second together instead of 73, with identical outputs. + +### Widened Qwen tensor-parallel owners keep fast fences + +Qwen tensor-parallel owners with more than one lane (Qwen3.8 27B, and the Qwen3.5 9B and both 35B A3B rows) keep MLX's fast fence waits instead of the slower event path. The stall that once stopped a widened pair right after a request finished is fixed at its cause: MLX kept a batched step on one GPU stream, and batched rows no longer convert their scales each step. + +### Wider automatic batching on two-Mac pairs + +- A two-Mac tensor-parallel owner now reserves much less memory per request, so automatic batching can widen past two concurrent requests when the Macs have room. A request no longer reserves its own full-history attention gather (decode and verification read pages in place, and one shared gather serves the single prompt frame a step runs). After a speculative round, a request keeps only its own recurrent rows instead of the whole round's. A long prompt's draft history moves into the assistant's cache as the prompt is read instead of waiting whole for the first draft. For Qwen3.8 27B with 32K-token prompts and 32K-token outputs, two, four and eight requests reserve 16.1, 25.7 and 45.5 GiB per Mac at an equal split, down from 21.4, 40.5 and 86.0 GiB. Qwen3.5 9B and the 35B A3B rows shrink the same way. +- Before replacing a running owner with a wider one, the preview now counts that owner's loaded weights on each Mac as free, because they are released before the wider owner loads. It does so only for a replacement that keeps the same split. The owner's unused request reservation is never counted, and the memory check after release is unchanged. A width that fails that check is not credited again for 10 minutes. +- Every width that automatic batching refuses is logged as one line, `cluster.batch_replan refused lanes=N`. It gives the phase (preview or after release), the reason, and each Mac's need, admissible memory, shortfall, weights and fit, in bytes. +- Every request still produces exactly the tokens it produces alone. + +### Qwen27 feature-preserving cluster modes + +Keep images, video and committed-token logprobs in the registered Qwen3.8 27B cluster route by admitting tensor parallel before unchanged speed ranking. Replan old pipeline setups instead of silently serving fewer features, retain native link/shape/memory gates, and require matching actual media READY and logprob support before creating the bridge. Other model and GLM mode policies remain unchanged. + +### Qwen27 media response formats + +- Accept image/video `response_format` requests through the cluster's existing + Qwen27 media path, using the same JSON prompt preparation and nonstream + JSON/schema post-validation as standalone serving. +- Preserve forced-media-tool refusals and default processor policy. Streaming + remains prompt-guided; this does not add token-level grammar enforcement or + establish full-model media/schema accuracy. + +### Qwen27 tensor-parallel greedy choices without full-vocabulary gathers + +Qwen27 tensor-parallel speculative decoding no longer moves complete vocabulary rows between the Macs for greedy work. Each draft step and each greedy verification column reduces a rank's vocabulary shard to its maximum and first index (plus a non-finite count when verifying), and one small exchange gives both Macs the same choice: the complete row's first maximum, with the lower index winning ties. Greedy verification also drops its separate choice broadcast. Sampled requests and logprobs still gather complete rows. + +### Qwen 3.8 27B pair media: preparation on its own stream, refused alone + +- A Qwen 3.8 27B tensor-parallel pair no longer ends both workers when rank 0's + media preparation fails. Rank 0 prepares a request's image or video patches at + admission, on a CPU stream of its own while its executor waits, so another + thread's failed CPU work can no longer fail the preparation (after the main + merge, MLX overlaps evaluations across threads and hands a stream's stored + error to whichever caller synchronizes it next; the pair's media requests + failed this way after a dozen had passed). A preparation that does not + reproduce the leader's patches refuses that request alone with a retryable + error and its reason in the worker log, and the pair keeps serving. A vision + tower failure still ends the workers. + +### Qwen27 tensor-parallel speculative depth 3 + +Automatic Qwen27 tensor-parallel setup now drafts three tokens a round instead of two. On the installed pair the assistant's first and second drafts were accepted 87% and 84% of the time, so a third proposal adds about 0.6 tokens a round for one more draft step; the verify window stays bound by one weight pass. Every emitted token is still the target's own choice. + +### Faster concurrent Qwen27 tensor-parallel verification + +Concurrent Qwen27 tensor-parallel requests now share each quantized projection's call when verifying their speculative windows, as long as the combined rows stay below MLX's vector-kernel limit for the device. Every request keeps the arithmetic it has alone. Draft proposals no longer need their own broadcast: both Macs read them from the same small exchange. A new `darkbloom-tp-mtp-profile-v1` worker line splits each round's time into draft, build, verify, gather, choose and settle. + +### Fewer weight reads for concurrent Qwen27 verification + +Concurrent Qwen27 tensor-parallel speculative windows now go through an exact four-bit projection kernel where it is faster than MLX's own calls: it reads each projection's weights once for up to eight verify rows (two four-column windows), where MLX's vector kernel reads them once for every five. On the M5 Max it keeps one output row per thread (up to 20% faster); on the M3 Ultra the row-parallel FP32 partials use two rows per thread (1.5-2.1x faster) and other projections keep MLX's calls. Each row keeps MLX's own `qmv_wide` reduction, so every request still gets byte-identical results to running alone; other GPU families keep MLX's calls. + +## v0.10.5 + +Published 2026-10-30 ([release](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5)). ### Upgrade and rollout notes diff --git a/changelog.d/cli-download-progress-line.md b/changelog.d/cli-download-progress-line.md deleted file mode 100644 index e882171317..0000000000 --- a/changelog.d/cli-download-progress-line.md +++ /dev/null @@ -1,8 +0,0 @@ -### One progress line for model downloads - -- `darkbloom models download` and the `darkbloom start` picker show one line for the whole model, redrawn in place at most four times a second: a bar, the percent, the bytes, the rate and the time left, leaving out what does not fit the window's width. They no longer print a line for every file or a block of per-file bars. -- The line keeps its shape while the window keeps its width: each figure has a fixed column, sized for its widest form, so the bar and the figures do not move as the numbers change. The rate and the time left appear after 2 seconds, and a time left over 24 hours is not shown. -- The line reads "Verifying" while the files are checked, then ends with one line: `✓ Downloaded (16.3 GB in 2m 10s)`, `✓ is already downloaded (16.3 GB)`, where the download stopped, or `Verification of failed: `. The picker no longer adds its own "Downloaded" line, and `darkbloom models download` ends with `Cached at ` instead of `Done. Cached at `. -- Without a terminal (a pipe, a log, the desktop app) the download prints plain lines with no carriage returns: the first at once, then at most one per 30 s and 10 points, one at 100%, and the same last lines. The desktop app reads its download progress from them. -- `darkbloom cluster` shows a model download or a copy over the cable on its live line instead of adding a line every second. A plain transcript keeps the first report, about one per 30 s and 10 points, and the lines for the record. -- Sizes in the line are decimal, as the catalog gives them. diff --git a/changelog.d/cluster-balanced-equal-cut.md b/changelog.d/cluster-balanced-equal-cut.md deleted file mode 100644 index 1f720fec21..0000000000 --- a/changelog.d/cluster-balanced-equal-cut.md +++ /dev/null @@ -1,3 +0,0 @@ -### Identical Macs split a model evenly - -- When cuts predict the same request time (identical Macs, or equal measured speeds), the placement planner now chooses the one that uses each Mac's hardware capacity most evenly, instead of the earliest cut the second Mac's free memory held at that moment. Two M5 Ultra 256 GB had planned GLM-5.3-Flash 11/34 and then 5/40 of its 45 layers; they now plan it 22/23 whichever Mac leads. A faster split is never traded for balance, and the "Quit apps first" refusal is unchanged. This applies to every model the cluster plans. diff --git a/changelog.d/cluster-bonsai-residual-and-gate-pressure.md b/changelog.d/cluster-bonsai-residual-and-gate-pressure.md deleted file mode 100644 index 4bac41a79f..0000000000 --- a/changelog.d/cluster-bonsai-residual-and-gate-pressure.md +++ /dev/null @@ -1,4 +0,0 @@ -### Bonsai FP32 residual stream and the cluster memory gate under pressure - -- Bonsai (Prism) packs keep their FP32 residual stream on the fused Qwen 3.5 decode, verify and stage paths. The fused residual step rounded each FP32 branch to the stream's FP16 embedding dtype, so the stream stayed FP16 and a Bonsai producer stage's residual left its FP32 contract; such a stream now takes the unfused sum, as the unfused forward computes it. Qwen 27B and the other uniform-dtype rows are unchanged. -- The cluster load gate's room-making pass runs only at normal memory pressure. Above it the gate withdraws all file cache on purpose, and a refusal now stands on the gate's own sample instead of a fresh one taken after the pass. diff --git a/changelog.d/cluster-capability-honesty.md b/changelog.d/cluster-capability-honesty.md deleted file mode 100644 index f2a482d364..0000000000 --- a/changelog.d/cluster-capability-honesty.md +++ /dev/null @@ -1,7 +0,0 @@ -### Two-Mac cluster capability honesty - -- A cluster member registers image and video input only when its pair's placed mode serves media (GLM-5.3-Flash and Qwen3.8 27B in tensor parallel), so the coordinator no longer routes media to a pipeline pair that answers text only; a pair registered for media serves only while both Macs report the media contract. -- `darkbloom cluster status` and the pair's `/metrics` report MTP on for GLM-5.3-Flash in tensor parallel, which always decodes with its NextN head (depth 2); they said "MTP off". -- A content part of an unknown type (`input_file`, `input_video`, `refusal`, ...) is refused with HTTP 400 naming the type on the local API of one Mac and of a pair, and with the closed invalid-request error on coordinator requests, instead of being answered from the remaining text. -- With images or video, a GLM-5.3-Flash pair answers the output controls as one Mac does: it withholds hidden reasoning (`reasoning.exclude`, `include_reasoning: false`, `thinking.display: "omitted"`) and refuses a `response_format` JSON answer or a required or named tool call with 400 before any media decode. -- A `response_format` answer the service validates that was cut off by `max_tokens` (a reasoning model can think through the whole budget) now returns 422 saying so, instead of "Internal inference failure." GLM-5.3-Flash, which validates its withheld JSON itself, keeps its typed 422. diff --git a/changelog.d/cluster-cdn-manifest-pins.md b/changelog.d/cluster-cdn-manifest-pins.md deleted file mode 100644 index 1c56afb2fd..0000000000 --- a/changelog.d/cluster-cdn-manifest-pins.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster models pin the manifest a Mac downloads - -- The cluster worker now pins the model CDN's `manifest.json` bytes for every registered model. GLM-5.3-Flash pinned bytes that no Mac could fetch, so a downloaded GLM was never described and the cluster refused it. Qwen3.5 35B A3B, Qwen3.6 35B A3B, Nemotron 3.5 Lightning, GPT-OSS 20B, MiMo V2.6 Flash and the three Gemma 4 26B entries pinned the production coordinator's re-encoding, whose `created_at` is different on each environment, so DevNet could not use them. The files and aggregate digests are unchanged; only the pinned serialization of each manifest is different. -- A cluster folder with the earlier bytes is repaired when setup next lists the models, with no hand step. This includes a folder copied over the cable from the other Mac, which has no download receipt on this Mac. The cluster store fetches the published manifest (the CDN first, then the coordinator) and writes it in place only when it names the same model, version, aggregate and files and this Mac's worker takes it. Weight files are not written. When nothing answers, the folder stays as it is and the repair is tried again a minute later. When the published manifest names other files, the folder stays as it is and the worker refuses it as before. diff --git a/changelog.d/cluster-control-leader-failover.md b/changelog.d/cluster-control-leader-failover.md deleted file mode 100644 index b6e338be34..0000000000 --- a/changelog.d/cluster-control-leader-failover.md +++ /dev/null @@ -1,13 +0,0 @@ -### Derived cluster control leader, failover, `darkbloom cluster` on every member - -- If one Mac goes away the cluster keeps itself running and re-forms by itself when it is back; `darkbloom cluster` works on either Mac. -- The cluster's control leader is derived, not the Mac where onboarding started: once a plan is adopted its rank 0 leads (requests enter there and registration v3 treats the plan's first member as the head); otherwise the member present that holds the model alone, then the most memory, the most GPU cores and the lowest member identity (from its Secure Enclave key pin). Leadership is a claim with a term, persisted in each Mac's setup record so a restart re-forms the same way; claims are totally ordered (term, then identity), travel only over the pairing-keyed link control channel, and a member refuses a superseded claim so a stale leader steps down. A leader acts on the cluster only after every plan member confirmed its claim. -- The leader renews a control lease with each member at the rank lease's cadence (5 s / 30 s) on a listener and edge epoch of its own. When the leader's lease expires the survivor takes over at the next term; a leader left alone serves the model on that Mac alone when the planner said it holds it alone (the ordinary single-Mac local server under the Mac's own identity: "degraded: serving on this Mac alone"), and otherwise says it cannot serve and runs nothing. When the missing Mac answers again the pair re-forms by itself and control returns to rank 0. -- `darkbloom cluster` works on any member: status, test request, model change, stop and start, and a verify-teardown summary of every Mac are forwarded to the control leader and its answer is shown. A model change while serving drains both Macs' parts before the setup changes. -- Failover serves alone only on a verdict for the plan saved now: the planner's alone verdicts are recorded with the plan's SHA-256, travel with the lease under it and are dropped for any other plan, and a refused (stale) lease never rewrites them; a member that has a new setup but not yet its verdicts says it cannot serve rather than load a model the planner never checked for it. A Mac re-paired with another Mac starts a new leadership history at term 0 instead of carrying the old pair's claim (which named the gone Mac and not the new one). -- Serving alone waits for the absence grace (10 minutes of peer or link absence, for every model and Mac): control still fails over at lease expiry (30 s), but until the grace ends the leader keeps its part ready for the missing Mac, its status says how long until it serves alone, and a Mac back before the grace re-forms the pair with nobody serving alone. A developer (debug) build may shorten the grace with `DARKBLOOM_DEBUG_CLUSTER_SOLO_GRACE_SECONDS`. -- A Mac restarted with a saved leader claim acts as the leader (model change, setup write, start, stop; forwarded or typed) only once the other Mac confirmed the claim, or once the confirmation window passed with no member reachable; a superseded claim steps down first and the command goes to the current leader. -- The control lease runs on the continuous clock, which keeps counting while a Mac sleeps: a woken leader no longer counts a Mac that left during the sleep as present, and a woken member gives its leader one lease time awake before it takes over. -- The solo readiness check names this Mac's own solo server (its process, checked by start time, holds the listening socket) instead of trusting any server on the port; another program on the port is reported as such. -- `darkbloom cluster verify-teardown` counts only this cluster's processes: its workers carry this Mac's member identity, its owners run this install's executable or own one of its workers. Other cluster homes' processes (another identity or install, a check's fake workers) are listed apart and do not fail the check. -- A rank 0 told to stop while it is still starting exits promptly: the signal handler is installed first (a stop is latched, never lost), the wait for the follower ends within 0.2 s of the stop, and the cluster service repeats SIGTERM every 5 s while it waits (never SIGKILL). diff --git a/changelog.d/cluster-coordinator-paired-approval.md b/changelog.d/cluster-coordinator-paired-approval.md deleted file mode 100644 index eb30795823..0000000000 --- a/changelog.d/cluster-coordinator-paired-approval.md +++ /dev/null @@ -1,6 +0,0 @@ -### A Mac pair registers with the coordinator as a cluster member by itself (DevNet) - -- After the Test stage passes, `darkbloom cluster` reads the cluster approvals the coordinator serves (`GET /v1/cluster/approvals`, from the operator approval file) and takes the entry whose model, prefill schedule and eight digests match this pair's installed app and model. Each Mac checks it against its own files before it saves it, and both Macs save it, or neither does. Both Macs then run as coordinator-paired members, owner-only, and the status says "Registered with the coordinator as a cluster member" with the approval and its end. -- The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching entry when the saved one ends within a day. An approval that ended is removed before a part starts, and the pair serves on the leader's local API again. -- When the coordinator gives no answer for 10 minutes (the absence grace), the pair serves on the leader's local API, and it is registered again when the coordinator answers with a matching entry. -- A coordinator without pair control (production, staging) or without a matching entry changes nothing: the saved setups stay byte for byte as they were. `darkbloom cluster local` never asks the coordinator. A pair approval saved by hand with `darkbloom cluster configure` is never removed. diff --git a/changelog.d/cluster-degraded-mode-admission.md b/changelog.d/cluster-degraded-mode-admission.md deleted file mode 100644 index 3a07971197..0000000000 --- a/changelog.d/cluster-degraded-mode-admission.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster: degraded mode only where single-Mac Darkbloom serves the model - -- When the other Mac goes away, a Mac serves the model alone only if single-Mac Darkbloom would serve that model on it (the same runtime requirements `darkbloom start --local` applies, such as an Apple M5 chip for Qwen3.8 27B) and the planner said it fits in that Mac's memory. Otherwise its status says it cannot serve the model alone and waits for the other Mac; the cluster re-forms by itself when it is back. A single-Mac server that still ends right after starting three times in a row is not started again until the cluster re-forms. -- The deployment line ("Serving … across both Macs: pipeline, M5 Ultra 40 layers / M3 Ultra 8 layers") is the same on whichever Mac leads, also when the model's first part runs on the other Mac. Models are listed by their catalog names. -- A stopped cluster's `darkbloom cluster` offers `v` (check that both Macs released their memory) on the leading Mac too, not only on a member. diff --git a/changelog.d/cluster-dev-install-model-ref.md b/changelog.d/cluster-dev-install-model-ref.md deleted file mode 100644 index 2cc1136b94..0000000000 --- a/changelog.d/cluster-dev-install-model-ref.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup finds models a dev install downloaded - -- `darkbloom-dev cluster` (and a staging install's) lists and uses the models that install downloaded. The cluster's model lookup read only production's `refs/main`, while a dev or staging install records its downloads under its own ref (`refs/darkbloom-dev`), so on a Mac with only a dev install the leader's download step failed with "downloaded, but the product's model store does not list it". It now reads the install's own ref, then production's, as single-Mac model discovery does. diff --git a/changelog.d/cluster-glm-lane-prefill-slices.md b/changelog.d/cluster-glm-lane-prefill-slices.md deleted file mode 100644 index 1efb613b86..0000000000 --- a/changelog.d/cluster-glm-lane-prefill-slices.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: a joining prompt no longer stalls decoding lanes - -- While other lanes decode on a GLM-5.3-Flash tensor-parallel pair, a joining lane's prefill runs in layer slices of about 500 ms, one slice a step, with every decoding lane's step after it, so decoding streams wait about 0.6 s instead of a whole 8K chunk (about 2.3 s). The lane with the shortest remaining prompt prefills first, and a prompt that fits one slice runs between another prompt's slices. Tokens are the same as a request served alone. diff --git a/changelog.d/cluster-glm-pair-parity.md b/changelog.d/cluster-glm-pair-parity.md deleted file mode 100644 index 9153b83e0f..0000000000 --- a/changelog.d/cluster-glm-pair-parity.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: logprobs on lanes, reasoning exclusion and MTP metrics - -- A GLM-5.3-Flash tensor-parallel pair serves `logprobs` / `top_logprobs` on batch lanes (it refused them with 503 when lanes were on), clamps `top_logprobs` to 20 as single-Mac does, accepts `reasoning: {"exclude": true}` (it answered 400), and reports MTP rounds, proposals and acceptances, its KV ledger, waiting requests and prefix-cache status on `/metrics`. diff --git a/changelog.d/cluster-glm-tp-load-setup.md b/changelog.d/cluster-glm-tp-load-setup.md deleted file mode 100644 index ea61b8cc10..0000000000 --- a/changelog.d/cluster-glm-tp-load-setup.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel setup reads metadata once, beside the link - -- A GLM-5.3-Flash tensor-parallel rank parses its model metadata once (the prepared loader's inventory) and does that work on its own thread while the link comes up, instead of serially before it; tensor-name matching runs on bytes. Setup before the load intent drops from about 5.7 s to about 3 s a rank, and `open` to about 0. Loaded weights are byte-identical and every file is still hashed. diff --git a/changelog.d/cluster-glm-tp-media.md b/changelog.d/cluster-glm-tp-media.md deleted file mode 100644 index b65a8e4cd1..0000000000 --- a/changelog.d/cluster-glm-tp-media.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM images and video on a tensor-parallel pair - -- A GLM-5.3-Flash pair serving in tensor parallel accepts image and video input as the single-Mac product does: the leader runs the product's media decode, processor and prompt expansion, rank 0 reproduces the same patches (checked by digest) off its executor and runs the vision tower when the request opens, and both ranks prefill the same spliced embeddings. Batch lanes carry media requests too, with the same arithmetic as a request served alone. Media requests decode with MTP rounds like text (the NextN history is primed with the media features) and without prefix reuse. Rank 0 now loads the vision tower (1.13 GB) with the tensor-parallel shard. diff --git a/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md b/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md deleted file mode 100644 index 6ea8da946f..0000000000 --- a/changelog.d/cluster-glm-tp-prefill-8k-micro-batches.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel prefill: 8K micro-batches on long prompts - -- Long prompts on a GLM-5.3-Flash tensor-parallel pair prefill in 32K-token graphs with 8,192-row micro-batches where every micro-batch's cross-Mac sums stay hidden behind the rest of the graph; shorter prompts keep their current plan. Prompt prefixes are still kept every 4,096 tokens, and DSA top-k selection keeps each row's original candidates, so outputs are bit-identical. A 31.5K-token prompt prefills about 4 % faster on two M5 Ultra. diff --git a/changelog.d/cluster-glm-tp-prefill-levers.md b/changelog.d/cluster-glm-tp-prefill-levers.md deleted file mode 100644 index aa8c26fda4..0000000000 --- a/changelog.d/cluster-glm-tp-prefill-levers.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel prefill: faster bit-identical kernels - -- GLM-5.3-Flash prompts prefill a little faster on a tensor-parallel pair: each hyper-connection site (89 per forward on both Macs) computes the expanded residual streams inside the products that read them, about 9 % faster per site, roughly 5 ms per 4,096 prompt tokens. Outputs are bit-identical. diff --git a/changelog.d/cluster-glm-tp-ssd-prefix-tier.md b/changelog.d/cluster-glm-tp-ssd-prefix-tier.md deleted file mode 100644 index 3d7a9db4e8..0000000000 --- a/changelog.d/cluster-glm-tp-ssd-prefix-tier.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM-5.3-Flash tensor-parallel prefix SSD tier - -- A GLM-5.3-Flash pair serving in tensor parallel keeps its prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt starts with its prefix restored after both Macs restart. Each Mac writes its own state at a prompt's kept 4,096-token boundary (its heads' linear-attention state, its copy of the sparse-attention histories and the MTP history) behind serving, once the request finished, read from the memory tier's pages without copying them first. The sealed prefix vote now counts SSD records; a boundary taken from an SSD record on either Mac is restored only after a second exchange confirms both Macs have it, otherwise both prefill from zero. A restored request writes the record into its own pages. Records store the sparse-attention latents at the pair's checkpoint precision (`balanced` by default, older rows approximate after a restore; see the quantized SSD prompt-prefix records entry); with `native` records a restored request produces the same tokens and logits as a request that prefilled the whole prompt. Records are scoped by the artifact, both builds and the MTP policy, never by the session. The same `DARKBLOOM_CLUSTER_PREFIX_SSD_*` settings, budgets and daily write limit apply. The prefix agreement field becomes `glm5-next-tensor-parallel-prefix-v2`. diff --git a/changelog.d/cluster-glm-tp-width-invariant.md b/changelog.d/cluster-glm-tp-width-invariant.md deleted file mode 100644 index 6e84420020..0000000000 --- a/changelog.d/cluster-glm-tp-width-invariant.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM pair: experimental speculative depth by load (off by default) - -- A GLM-5.3-Flash tensor-parallel pair can verify one NextN proposal a round while three or more requests decode together and two otherwise (`DARKBLOOM_GLM_TP_MTP_DEPTH_POLICY=load`, threshold `DARKBLOOM_GLM_TP_MTP_LOAD_LANES`, 2 through 8, default 3), with `DARKBLOOM_GLM_TP_WIDTH_INVARIANT=1` (implied by `load`) giving verification rows one arithmetic in more window shapes. It is off by default: on two M5 Ultra Macs it raised the aggregate of 4 and 8 concurrent requests by about 11 %, but some concurrent requests' outputs differed from the same request alone, so it stays a diagnostic until that is fixed. Both Macs' cluster services must set the same values; the default keeps today's outputs bit for bit. diff --git a/changelog.d/cluster-guided-setup.md b/changelog.d/cluster-guided-setup.md deleted file mode 100644 index 6708f5b7e2..0000000000 --- a/changelog.d/cluster-guided-setup.md +++ /dev/null @@ -1,5 +0,0 @@ -### Clearer cluster setup and recovery - -- Follow five visible setup stages, see the default model before pressing Enter, and use a shorter status menu on either Mac. -- Preserve plain text when output is redirected or color is disabled. -- Report a failed test request with a status-and-retry step instead of announcing that setup succeeded. diff --git a/changelog.d/cluster-hardware-split-prefix-everywhere.md b/changelog.d/cluster-hardware-split-prefix-everywhere.md deleted file mode 100644 index 306b24009c..0000000000 --- a/changelog.d/cluster-hardware-split-prefix-everywhere.md +++ /dev/null @@ -1,9 +0,0 @@ -### Hardware-only cluster split, prompt-prefix cache for every family, GLM cluster residency - -- The split across the Macs is chosen from each Mac's hardware and measured speed alone: free pages, cached files and what other programs hold never move it. A range fits a Mac when its whole need is within the GPU's working set, the allocator's and buffer limits, and what the Mac's memory gate can admit at rest (physical memory less the system's own wired share and the file cache macOS always keeps, 10/27 of the rest). The live answer per Mac is still shown ("Quit apps on … first") and the load gate still decides each load. -- Gemma 4 pairs keep and reuse the prompt prefix too: each sliding-window layer's window is kept at every frontier and restored exactly, so a repeated 3,521-token prompt's first token comes in 0.08 s instead of 0.98 s on an M3 Ultra + M5 Max pair, and after both Macs restart the SSD tier gives it back in 0.23 s. -- GLM-5.3-Flash pairs keep and reuse the prompt prefix (resident and encrypted SSD tiers) with the same two-rank agreement as the other families: DSA histories are kept once per prompt, KDA state per frontier. -- A GLM stage holds standing GPU residency, as MiMo's does: without it every command buffer made its tens of gigabytes of weights resident again and decode fell to 0.5 tok/s (30 tok/s on one Mac with it, same tokens). -- A GLM pair always uses the keyed, encrypted data plane, including over the paired link; a model `config.json` up to 32 MiB is accepted (GLM's NVFP4 configuration is 10 MB); a model folder whose bytes are a catalog entry's is listed by that entry's name. - -- Compact GLM convolution and recurrent cache states at transaction ownership boundaries before using the smaller retained-state reservation. Keep pending prefill histories and cast allocations charged per layer, enabling automatic 2048-token placement without choosing a hardware-specific split. diff --git a/changelog.d/cluster-installed-paths-with-spaces.md b/changelog.d/cluster-installed-paths-with-spaces.md deleted file mode 100644 index 53345c0999..0000000000 --- a/changelog.d/cluster-installed-paths-with-spaces.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster planning accepts a DevNet app's install path - -- Planning a two-Mac cluster with a DevNet build no longer fails every model with "Peer installation paths must be absolute and shell-safe". The DevNet app is installed as `Darkbloom Dev.app`; a saved cluster setup now accepts a space in the installed owner and worker executables, the model directory, and the native member's metallib and resource library. -- Shell syntax, relative paths and `..` are still refused, and the developer SSH route still checks every path it puts in a remote command. -- The orphan sweep, the teardown check and `cancel-all` now find a DevNet build's `darkbloom-dev cluster worker-owner`, and the cluster service stop finds a `darkbloom-dev cluster service`. Before, they knew only the production `darkbloom` name. diff --git a/changelog.d/cluster-lane-withdrawal.md b/changelog.d/cluster-lane-withdrawal.md deleted file mode 100644 index 63f1c1c6e2..0000000000 --- a/changelog.d/cluster-lane-withdrawal.md +++ /dev/null @@ -1,6 +0,0 @@ -### Independent cluster lane withdrawal - -Fixed cluster batch cancellation so withdrawing an admitted request that has -not started retires that request without interrupting another request waiting -for token credit. Accepting a start command closes the withdrawal window, and -duplicate cancellation messages share the pending retirement acknowledgment. diff --git a/changelog.d/cluster-local-only.md b/changelog.d/cluster-local-only.md deleted file mode 100644 index 59e702be00..0000000000 --- a/changelog.d/cluster-local-only.md +++ /dev/null @@ -1,34 +0,0 @@ -### `darkbloom cluster local`: a Mac pair serving without a coordinator - -- `darkbloom cluster local [model]` sets up and serves the pair exactly as `darkbloom cluster` does, but no Mac of the cluster contacts a coordinator: no registration, heartbeat, public traffic or billing, and serving needs no network beyond the cable. A coordinator can therefore never refuse the start. -- The API is on the leading Mac's local endpoint with the same API key as `darkbloom start --local`; it listens on every network of that Mac (LAN or tailnet) unless `--bind` names an address (`--bind 127.0.0.1` keeps it on the Mac). `darkbloom local` prints the base URL, a `network:` URL and the key. -- The choice is kept across restarts and reboots until changed: in `darkbloom cluster`, `l` serves locally only and `p` serves through Darkbloom again; a serving cluster restarts its leading part that way and the screen waits until it serves. -- A cable moved to another Thunderbolt port no longer leaves both Macs unreachable: each cluster service follows the cable to the new port within a few seconds. -- A cluster set up from the plain `darkbloom` command (the installer's link on the PATH) now starts its leading part; it used to stop with "Installed local owner is unsafe or not executable". -- `darkbloom cluster local` on the Mac that joins a pairing carries on to the model choice (it runs on the leader over the cable) instead of sending you to the other Mac. -- The model list shows one line per model (its size and how it is split, or how it gets onto the Macs); what moves and the planner's reason are said once a model is chosen, and the public-traffic line only when serving through Darkbloom. Two models with the same name show their ids. A part that keeps ending the same way is said after three tries instead of repeating, errors read as words (not `invalid("…")`), and pairing waits for the cable's address instead of failing with developer options. -- A smaller Mac takes the share of a model it can hold: the stage memory gate's 6 GiB floor and 4 GiB loading headroom (measured on 256 GiB Macs) now scale with the Mac's memory below 96 GiB (36 GB Mac: 2.25 / 1.5 GiB). A one-layer part on a 36 GB Mac was refused before. "Restart to free memory" is said only when nothing else frees enough; a choice made on the member survives a leader restart; the model list keeps the last catalog it read when the catalog does not answer. -- Hardware run on an M4 Max 36 GB + M5 Max 128 GB pair (Gemma 4 26B QAT, local only): another server on port 8000 (oMLX) no longer makes every start end after both Macs loaded: the port is checked before anything loads and the leading part takes the next free port; Gemma's thought-channel markers no longer reach `content` on the local API (the cluster's API parses reasoning by the model's type, as the coordinator path does); the leader no longer re-sends its cache settings every 15 s to a member that drove the onboarding; the ready screen's deployment line is the running setup's, not one recorded for an earlier start. -- The leading Mac downloads a catalog model the cluster serves whatever its chip: Qwen 3.8 27B's single-Mac requirement (an M5's neural accelerators) no longer stops an M4 Max leader from fetching it for the pair; single-Mac serving keeps its own check. -- Models the cluster takes from this Mac's own model store (Qwen 3.5 9B, a freshly downloaded Qwen 3.8 27B) are offered and copied again: their manifest is the catalog's exact file (the CDN lists the files in another order, which was refused), and a copy written earlier is corrected once. -- On a 36 GB Mac the prompt-prefix cache works: a memory-bound context keeps room for it (a repeated 5.5K-token prompt starts in 0.28 s instead of 7.1 s); a thinking model's reasoning streams from its first token on the cluster's API; each Mac keeps its worker's own log (`~/.darkbloom/cluster-setup/worker.log`). -- `darkbloom cluster local` answers at the same address and with the same key whichever Mac the plan makes rank 0: the other Mac passes the same port to the API over the cable, both Macs keep one API key, and `darkbloom local` shows it on either Mac. The port is 8000 when both Macs have it free, else the lowest port from 8000 to 8020 free on both, and it is kept while it stays free on both (another server on 8000 on one Mac no longer puts the API on 8000 or 8001 by which Mac is rank 0). -- A model chosen on a member is fetched there (it said "Nothing to copy: plan again."); a model's manifest is the encoding this Mac's worker accepts (GPT-OSS 20B was refused); the plan uses the other Mac's served speeds; the start screen no longer prints index estimates as seconds; the test request counts a thinking model's reasoning. -- PrismML Bonsai 2 27B serves on a pair with a 36 GB Mac: the worker's idle context check no longer recomputes the stage plan's constants for every step of its search (it outlasted the 10 s a request waits, so every request failed); a failing local request leaves a line in the log. -- A Mac whose memory moved after the plan (apps opened, cache refilled) no longer makes the pair retry the same split forever: after two load refusals for memory the leading Mac plans the model again on the memory now. -- The local API (single Mac and cluster alike) parses Gemma 4's thought channel and GPT-OSS's Harmony markers out of `content` by the model's type; think-tag models keep the raw stream there, as before, so the cluster still answers exactly as a single Mac does. -- Before a part starts, the model's own pages are dropped from the Mac's file cache (no privileges; the files are untouched): the load gate does not count active cache, and right after a download a 36 GB Mac's share was refused. -- The relay on the Mac that is not rank 0 is hardened: it listens only when the API listens on every address, bounds its connections and idle time, never closes a descriptor another thread may reuse, survives running out of descriptors, and leaves another local server's discovery file alone. -- A 36 GB Mac in everyday use keeps its share: a request on a loaded part asks only for what it needs plus headroom, and when the gate is short only because it does not count file cache the kernel could drop, the worker lets the kernel drop it first (stopped at any sign of compression, swap or pressure); "Quit apps" is no longer said for that case. -- When the cable moves to a Thunderbolt port that was never set up, `darkbloom cluster` says so and sets it up with one key (f); the service's log says what to do. -- The local API (single Mac and cluster) puts every model's reasoning in its own field, Qwen and Nemotron included, on chat completions and the Responses API; a stream whose prompt opens no think block still streams its answer at once. -- Shorter onboarding screens: models held back for the same reason share one line, two Macs running different Darkbloom builds are named as such ("install the same Darkbloom on both") instead of "Planning failed (Peer native build differs from the capability)", models the cluster cannot run say "not supported on a cluster yet", and the development-build service line says only what to do after a restart (the reason is in the service log). - -- Guided cluster setup shows five stages, names the default model choice, refreshes peer labels from the authenticated Mac, and reports completion only after the test response succeeds. Terminal color respects `NO_COLOR`; redirected output stays plain. - -- Cluster members prevent idle sleep while a deployment is serving or waiting for its peer; assertions remain held until the child and relay stop, then are released. -- A cluster service recovering a model process from its previous run keeps waiting after the cleanup deadline, keeps that process visible and protected from idle sleep, and starts no replacement model until it exits. - -- Raise cluster worker output support from 4,096 to 32,768 tokens, with 65,536 combined prompt/output tokens subject to model and live per-rank memory limits. Refuse requests over the advertised bounds rather than truncating them. - -- Keep fixed-scope model reservations at their full serving context when recent short requests tune automatic placement. GLM placement includes the native transport buffers and allocator bounds, so those requests cannot make an oversized split appear loadable. diff --git a/changelog.d/cluster-local-serving.md b/changelog.d/cluster-local-serving.md deleted file mode 100644 index 5dd2441c14..0000000000 --- a/changelog.d/cluster-local-serving.md +++ /dev/null @@ -1,5 +0,0 @@ -### A Mac pair serves locally when its coordinator has no cluster support - -- A cluster whose coordinator cannot take its cluster member role (unreachable, or a coordinator that answers the member's registration as an ordinary provider's because it predates the role) now serves on the leader's local API only, with the same local token as `darkbloom start --local`, instead of restarting every 38 s without ever serving. No public traffic reaches it and nothing is advertised to the coordinator; the Macs stay held for the cluster as before. -- The onboarding screen and `darkbloom cluster` status say so in one line: "Serving locally on this Mac's API; public serving needs a coordinator with cluster support." The next start registers normally once the coordinator supports the role. -- A coordinator that refuses this member or its pairing is still a refusal: that start fails as before. diff --git a/changelog.d/cluster-member-install-grant.md b/changelog.d/cluster-member-install-grant.md deleted file mode 100644 index 869cb8c71b..0000000000 --- a/changelog.d/cluster-member-install-grant.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster pairs register GLM-5.3-Flash and Qwen3.8 27B as cluster members - -A pair started with a coordinator approval (DevNet) now registers both Macs as cluster members for GLM-5.3-Flash and Qwen3.8 27B. Before, each Mac's member part ended about a second after it started, with "Cluster member control connection ended", and after three tries the pair served on the leader's local API only. - -The member applied the single-Mac requirements (`mlx_nax`, and `glm5_next_v1` for GLM) to its model in two places: before connecting, and when building its registration, which left the model out of `cluster_models`. A member reports hardware-only capabilities, and its pair-serving grant admits its model, so both places now follow the grant. A solo provider keeps the single-Mac requirements. diff --git a/changelog.d/cluster-member-refusal-releases-reservation.md b/changelog.d/cluster-member-refusal-releases-reservation.md deleted file mode 100644 index 6df4c98753..0000000000 --- a/changelog.d/cluster-member-refusal-releases-reservation.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster member refusals and stops release what they hold - -- A cluster member that refuses an inference request because it has no live pair slot now sends `service_reservation_released` with its 503, on the receive path, in the dispatcher and in the request handler. A request that raced a pair-slot retirement left its reservation held on the coordinator before. The handler refusal also settles the request's prefix-cache lookup receipt. The 503 answer is unchanged. -- A session that ends while the leader still forms its pair (slot publication and warmup canary) retires the published slot before the leader sends `native_pair_owner_released`. The receipt went out while the slot was still published before. diff --git a/changelog.d/cluster-member-restart-registration.md b/changelog.d/cluster-member-restart-registration.md deleted file mode 100644 index bc2e222c28..0000000000 --- a/changelog.d/cluster-member-restart-registration.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster member restarts re-register when the coordinator comes back - -- A cluster member (leader or follower) that starts while its coordinator is briefly away keeps its reconnects inside its registration wait: a retry the backoff would place after the wait is made at its end and is given its own terms, as is an attempt already under way when the wait ends, so a coordinator that returns before the wait ends is reached and its in-time acceptance is honoured. -- A wait in which the coordinator was never reached now says so ("The coordinator could not be reached …") instead of "Coordinator did not accept the control-only member role."; the role check itself is unchanged. diff --git a/changelog.d/cluster-mimo-pair-qualification.md b/changelog.d/cluster-mimo-pair-qualification.md deleted file mode 100644 index 2a1d20cf40..0000000000 --- a/changelog.d/cluster-mimo-pair-qualification.md +++ /dev/null @@ -1,5 +0,0 @@ -### MiMo V2.6 Flash on the two-Mac pair - -- MiMo V2.6 Flash can be served by an M5 Ultra and an M3 Ultra together. -- MiMo pair runs produce qualification records (the reference names its request and is compared on it), and MiMo V2.6 Flash is granted on an M5 Ultra + M3 Ultra pair by its six records (pipeline at the planner's cut, in the order the records passed; the mirrored order is refused). -- The provider's start-time weight hash reads with the file cache off (`F_NOCACHE`, same digest, earlier readers kept as fallbacks), so hashing a 172 GB model no longer fills the Mac's file cache before the memory gate decides. The memory gate is unchanged. diff --git a/changelog.d/cluster-mode-bound-grants.md b/changelog.d/cluster-mode-bound-grants.md deleted file mode 100644 index a29612cdac..0000000000 --- a/changelog.d/cluster-mode-bound-grants.md +++ /dev/null @@ -1,5 +0,0 @@ -### Pair-serving grants bound to the mode their records ran - -- A qualification record now grants only its own mode family (pipeline variants, pipeline with speculative rounds, tensor parallel, or the off-by-default hand-off modes) and only the chip classes in the roles it ran; a phase-split pass no longer opens pipeline or tensor-parallel placements. A diverged record withholds its own family; an inconclusive one neither grants nor withholds. The planner keeps to the same rule, and a start checked without its mode is refused. -- Seven pipeline qualification records on an M3 Ultra + M5 Ultra pair at the planner's sharded cut (Qwen3.5 9B and Qwen3.8 27B at cut 4 and 8 and Nemotron 3.5 Lightning at cut 8 with the M3 Ultra leading; both Qwen 35B A3B models at cut 36 and Ternary Bonsai 2 27B at cut 56 with the M5 Ultra leading; GPT-OSS 20B at cut 20, which stays withheld by its earlier diverged pipeline records) are bundled: every model the pair served only through phase-split records on these Macs now has a pipeline grant of its own. -- The onboarding offers exactly what a start serves: a model whose chosen placement any rank's grant check would refuse (GPT-OSS 20B, withheld by its diverged pipeline records although cut 20 passed) is listed as not served, with the reason, instead of being offered and then refused at start. diff --git a/changelog.d/cluster-model-approvals.md b/changelog.d/cluster-model-approvals.md deleted file mode 100644 index 8f02cae17f..0000000000 --- a/changelog.d/cluster-model-approvals.md +++ /dev/null @@ -1,6 +0,0 @@ -### A Mac pair keeps its DevNet cluster approval across provider updates - -- The coordinator can serve a model approval: a cluster approval that names the model, its prefill schedule and its serving terms, but no build. The pair takes it when its model, schedule and artifact are the saved setup's, and it computes no build facts for it. Entries pinned to one build are matched as before. -- After an update, the re-adopted setups find the same model approval at the next check, so the pair is registered with the coordinator again with no new entry from the operator. -- Under a model approval each Mac registers its plan with its own runtime (worker, capability, resource policy and profile), and a session starts only with that runtime. Each Mac hashes its worker against its saved setup and its metallib and resource library against the digests it took when it registered. -- When the pair set a model approval aside because its parts kept failing, the next update can take it again. The same build does not take it again. diff --git a/changelog.d/cluster-model-change-replans-after-stop.md b/changelog.d/cluster-model-change-replans-after-stop.md deleted file mode 100644 index 2bd4d6d938..0000000000 --- a/changelog.d/cluster-model-change-replans-after-stop.md +++ /dev/null @@ -1,4 +0,0 @@ -### Changing a serving cluster's model plans again once its memory is free - -- Changing the model of a serving two-Mac cluster (`m` in `darkbloom cluster`, or `darkbloom cluster local `) now plans again after both Macs have stopped their parts and given back their memory, and starts that plan. Before, it started the plan made while the old parts still held the memory, where tensor parallel did not fit, so a pipeline started instead. GLM-5.3-Flash on two M5 Ultras came back at less than half the speed (47.9 instead of 126.9 tokens/s in the setup's test request), serving the pipeline's 65,536-token context instead of its native 1,048,576. -- The leading Mac's own re-plan after two load refusals for memory starts the plan made once both parts stopped and gave back their memory, too. diff --git a/changelog.d/cluster-model-provisioning.md b/changelog.d/cluster-model-provisioning.md deleted file mode 100644 index 82207df882..0000000000 --- a/changelog.d/cluster-model-provisioning.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster model provisioning without manual downloads - -- `darkbloom cluster` needs no `--model-dir`: the cluster keeps its models in a store beside the product's model cache, and models single-Mac Darkbloom installed are cloned in (APFS clones, the catalog's exact manifest bytes). -- A model one Mac lacks is copied over the Thunderbolt cable on the pairing-keyed link control channel (encrypted records, 4 MiB chunks acknowledged after the receiver wrote and hashed them, resumable). The receiving Mac accepts only a manifest whose digest this build's qualification records pin, refuses hard links, unexpected files, an occupied destination and too little free disk, writes uncached, and has its own worker check the staged files before an exclusive rename into place. -- A catalog model neither Mac has is downloaded once on the leader (the product downloader, written and verified uncached through the new opt-in `ModelDownloader.uncachedWrites`), then copied. A copy predicted under 30 s at the rate measured on these Macs starts by itself (`n` within 3 s stops it). diff --git a/changelog.d/cluster-onboarding-brand.md b/changelog.d/cluster-onboarding-brand.md deleted file mode 100644 index 11ad8048c6..0000000000 --- a/changelog.d/cluster-onboarding-brand.md +++ /dev/null @@ -1,3 +0,0 @@ -### Animated Darkbloom cluster setup - -`darkbloom cluster` setup now opens with the Darkbloom mark, which blooms in on color UTF-8 terminals at least 40 columns wide. Stage headings show a step meter, and long work (cable check, reading both Macs, planning, loading, first tokens) shows a live line that the next transcript line replaces. `DARKBLOOM_NO_ANIMATION` or `CI` keeps the mark and meter but stops the motion. Narrow or non-UTF-8 terminals keep colored headings only. `NO_COLOR`, `TERM=dumb` and redirected output stay byte-for-byte plain. The model-free onboarding checks cover all four presentations (438 checks). diff --git a/changelog.d/cluster-onboarding-mac-names.md b/changelog.d/cluster-onboarding-mac-names.md deleted file mode 100644 index cb7194c746..0000000000 --- a/changelog.d/cluster-onboarding-mac-names.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster setup names "this Mac" and "the other Mac" - -- `darkbloom cluster` names the two Macs from the screen that shows them: "this Mac" and "the other Mac (Apple M5 Ultra, 256 GB)" in pairing, the machine list, each model's split ("this Mac 50% / the other Mac 50%"), the serving and API lines, status, teardown checks and copies. Two identical Macs were both "Apple M5 Ultra, 256 GB", and the API line did not say it was on the other Mac. Answers the leader gives to the other Mac are worded for that Mac's screen. -- The Mac that joins a waiting leader stops after pairing, also when started with `darkbloom cluster local`; it says to run that on the Mac that leads instead of showing a second model list. -- A model one Mac holds twice (the catalog's download beside the cluster's own copy of the same files) is listed once, and a supported model is never listed as "not supported on a cluster yet" for a copy the cluster worker does not take. diff --git a/changelog.d/cluster-onboarding-mark-on-every-run.md b/changelog.d/cluster-onboarding-mark-on-every-run.md deleted file mode 100644 index b3a07a23ba..0000000000 --- a/changelog.d/cluster-onboarding-mark-on-every-run.md +++ /dev/null @@ -1,3 +0,0 @@ -### Darkbloom mark on every `darkbloom cluster` run - -Running `darkbloom cluster` again on a Mac that is already in a cluster (the leader or a member) now opens with the same Darkbloom mark as the first setup, beside "Darkbloom cluster" and what can be done there (status, test, change model, stop). It follows the same terminal rules as the setup: color UTF-8 terminals with room for the mark draw it, `DARKBLOOM_NO_ANIMATION` or `CI` keep it still, and `NO_COLOR`, `TERM=dumb` and redirected output print the two heading lines as plain text. The onboarding checks cover the leader and the member, in color and plain. diff --git a/changelog.d/cluster-onboarding-narrow-windows.md b/changelog.d/cluster-onboarding-narrow-windows.md deleted file mode 100644 index c9fe35337d..0000000000 --- a/changelog.d/cluster-onboarding-narrow-windows.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup in narrow terminal windows - -In a colour terminal between 40 and 56 columns wide, `darkbloom cluster` setup no longer smears the Darkbloom mark: the mark and its bloom appear only when its widest row fits, and narrower windows keep the step meter and live lines. A live progress line wider than the window is now cut to one row, so the line that replaces it no longer leaves its first half in scrollback. diff --git a/changelog.d/cluster-one-command.md b/changelog.d/cluster-one-command.md deleted file mode 100644 index eb0ccad1ec..0000000000 --- a/changelog.d/cluster-one-command.md +++ /dev/null @@ -1,8 +0,0 @@ -### One command for a cluster: `darkbloom cluster` - -- Run `darkbloom cluster` on each Mac, pick a model, done. `darkbloom cluster setup` is the same command; with no terminal it says where to run it. -- Choosing the model starts it (3 s to press n); no second question. The screen then says how the model is served in one line, for example "Serving Qwen3.8-27B across both Macs: pipeline, M3 Ultra 40 layers / M5 Ultra 24 layers", and where the API is ("API at http://localhost:8000 on "). -- Models that fit in the Macs' free memory now are listed first, a model that does not fit says what frees the memory, and the fit is checked again right before the start. A model the pair may not serve with this release is listed under "Not offered" ("Not yet qualified on this pair of Macs") instead of failing after a long wait. -- Two cables: the onboarding asks which one to use. The cable check prints plain lines ("Cable found.", "Cable ready."). macOS's one Local Network prompt is announced before it appears, and a denied prompt is named with where to allow it. -- After a Darkbloom update the cluster sets itself up again by itself ("Updating the cluster setup after a Darkbloom update."). After a restart, the screen says whether the Mac comes back by itself (automatic login) or once someone logs in (FileVault). -- A start that does not finish shows each Mac's last error and offers `d` to save a redacted diagnostics file. Error messages name only `darkbloom cluster`; `plan`, `configure`, `console`, `pair` and the other developer subcommands and options are hidden from the help. diff --git a/changelog.d/cluster-paged-kv.md b/changelog.d/cluster-paged-kv.md deleted file mode 100644 index d81a3fcf6d..0000000000 --- a/changelog.d/cluster-paged-kv.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster KV in pages - -- GLM-5.3-Flash tensor-parallel ranks, GLM pipeline stages, Qwen 3.5 pipeline stages (MTP heads included), Qwen tensor-parallel shards, Gemma 4 stages (any lane count) and Nemotron 3.5 stages keep request KV in page pools instead of contiguous per-request arrays. Prefix entries share pages (refcounted, copy on write at a shared partial page) instead of copying histories, and a GLM tensor-parallel request is charged its pages (about 18.4 KB a token a rank) rather than the contiguous growth charge. Outputs are bitwise the contiguous ones. `DARKBLOOM_CLUSTER_GLM_PAGED_KV=0` keeps contiguous GLM tensor-parallel KV for diagnosis. -- GLM tensor-parallel (solo) and GLM pipeline requests start with their prompt's pages plus a 1,024-token granule and grow between steps, with no context cap; a request whose growth the memory gate refuses ends at `length` without touching others. GLM page pools compile their kernels at load and keep up to `DARKBLOOM_CLUSTER_GLM_PAGED_RETAIN_MB` (2,048 MB a rank) of slabs between requests. diff --git a/changelog.d/cluster-pipeline-speculative-records.md b/changelog.d/cluster-pipeline-speculative-records.md deleted file mode 100644 index 441957f4ce..0000000000 --- a/changelog.d/cluster-pipeline-speculative-records.md +++ /dev/null @@ -1,6 +0,0 @@ -### Speculative rounds on the pipeline, recorded and on by default - -- A qualification (recording) request now runs a pipeline's speculative rounds (`pipeline_mtp_v1`) as served, and its decoding rank records the accepted timeline: one step per selected token (its row's digest and highest candidates), so the near-tie rule reads every accepted token. Drafts never change the accepted output. -- A qualification record may carry the decode speed timed runs of its own placement and request measured, in its mode and as the plain pipeline (`darkbloom-cluster-pair-check record --timing-mode/--timing-plain`). A passing `pipeline_mtp_v1` record grants the pipeline-with-speculative-rounds family, and the planner credits the rounds with its measured speed-up until the pair has served the same placement both with and without the rounds and its own speed-up replaces it: the rounds are planned by default where lossless and measured faster. The onboarding line reads "pipeline with speculative decoding". -- Records on an M3 Ultra + M5 Ultra pair at the planner's sharded shapes: Qwen3.8 27B at cut 8 (tokens equal to both single-Mac references and to the plain pipeline; 57.7 against 35.6 tok/s), Qwen3.5 9B at cut 4 (near tie at a true tie; 130.9 against 75.1 tok/s) and MiMo V2.6 Flash at cut 47 (tokens equal at 1,024 and 4,096 prompt tokens; 59.2 against 43.1 tok/s). Output matches a single Mac's up to near ties, as the pipeline's does: the verify window's arithmetic differs in its last bits from one-token decode. -- A member's roster plan may name `pipeline_mtp_v1`; a role-aware coordinator must list it too before it accepts such a plan. diff --git a/changelog.d/cluster-planner-pricing-fixes.md b/changelog.d/cluster-planner-pricing-fixes.md deleted file mode 100644 index 6bc24ba908..0000000000 --- a/changelog.d/cluster-planner-pricing-fixes.md +++ /dev/null @@ -1,6 +0,0 @@ -### Cluster planner pricing fixes - -- GLM-5.3 Flash tensor parallel: the plan now counts the NextN (MTP) layer every Mac holds beside its share (4.2 GB), the request memory its speculative rounds add, and the decode speed-up the rounds measured, so it no longer admits a pair the load gate then refuses or predicts decode too slow. Two M5 Ultra 256 GB still plan it as tensor parallel on equal shares with eight concurrent requests, on a new pair and after the first load measured the link. -- A pipeline's prompt hop across the cable is priced by the bytes it carries (a GLM chunk is 64 MiB), from the link probe's two record sizes, instead of as one 4 MiB record. -- Requests that answer fewer than 64 tokens (the warm-up canary, the setup's test answer, readiness probes, a quick "Say hi") are no longer speed records, so they no longer choose the mode or the request a plan is made for. -- A Mac with a model loaded no longer runs the GPU speed benchmark when the other Mac checks for updates every minute or plans: it uses the speed index it last measured while idle. diff --git a/changelog.d/cluster-prefix-tenant-scope.md b/changelog.d/cluster-prefix-tenant-scope.md deleted file mode 100644 index 71c6a1fe1a..0000000000 --- a/changelog.d/cluster-prefix-tenant-scope.md +++ /dev/null @@ -1,3 +0,0 @@ -### Two-Mac cluster prompt prefixes per tenant - -Both Macs of a cluster now keep and reuse prompt prefixes, in memory and in their encrypted SSD tiers, only for the request's own tenant, as one Mac does: the leader gives both ranks each request's cache switch and a SHA-256 digest of its cache scope (never the scope itself), every prefix key and SSD record scope carries that digest, and a request whose prefix cache is off (a remote request without a cache scope, or a GLM or Qwen request with images or video) reuses and keeps nothing on either Mac. Before, every request on the pair shared one prefix cache. Requests from the local endpoint carry no partition and keep the earlier behavior and bytes. Both ranks bind the partition into the request fingerprint they compare, so ranks given different partitions fail the request. `darkbloom-cluster-pair-check request --request-prefix-cache off|tenant:SALT` writes a qualification request with a partition. diff --git a/changelog.d/cluster-qmv-batch-invariant.md b/changelog.d/cluster-qmv-batch-invariant.md deleted file mode 100644 index ebd2c65b38..0000000000 --- a/changelog.d/cluster-qmv-batch-invariant.md +++ /dev/null @@ -1,3 +0,0 @@ -### A request's tokens do not depend on what it is batched with on the new MLX core - -- Cluster workers, the single-Mac reference and the tensor-parallel check now set `MLX_QMV_BATCH_INVARIANT=1` before MLX starts, unless their launcher set it. The cluster's MLX core then keeps quantized products of a few rows (speculative verify windows, rows of several requests in one launch) on its per-vector kernels, as before it took MLX main's new kernels for 6 to 16 NVFP4 rows and 8 or more affine rows, whose results change with the row count. A request served beside others keeps the bytes it gets alone. Each process logs `darkbloom-qmv-batch-invariant-v1` with the value and who set it. Single-Mac serving is unchanged. diff --git a/changelog.d/cluster-qwen-m5-ultra-window-layout.md b/changelog.d/cluster-qwen-m5-ultra-window-layout.md deleted file mode 100644 index 9ded5678e0..0000000000 --- a/changelog.d/cluster-qwen-m5-ultra-window-layout.md +++ /dev/null @@ -1,3 +0,0 @@ -### Faster Qwen tensor-parallel decode on two M5 Ultra - -- Qwen3.8 27B tensor parallel on two M5 Ultra decodes about 6% faster for one request (75.8 to 80.5 tok/s at 256 tokens, 62.7 to 66.8 at 1,024). The exact decode projections take a layout measured on the M5 Ultra for a verify window's vectors (rows in registers). Outputs are unchanged byte for byte, and other chips keep their layouts. diff --git a/changelog.d/cluster-qwen-moe-packed-collective.md b/changelog.d/cluster-qwen-moe-packed-collective.md deleted file mode 100644 index 041037b5c3..0000000000 --- a/changelog.d/cluster-qwen-moe-packed-collective.md +++ /dev/null @@ -1,10 +0,0 @@ -### Pack Qwen MoE tensor-parallel expert and shared reductions - -Qwen routed-expert tensor parallelism now carries the shared expert's float32 -partial in the routed experts' collective: two collectives per layer instead of -three, with every summed and rounded value unchanged. The load agreement -(`qwen-moe-down-projections-f32-sum-before-weighting-packed-v3`) and the -tensor-parallel check's launch version refuse mixed builds. Placement now -charges the top-K expert rows once per layer instead of the largest payload on -every collective, and the request ledger charges the packed payload's source -partials. Full-model hardware qualification on the pair is still required. diff --git a/changelog.d/cluster-qwen-tensor-lanes-every-row.md b/changelog.d/cluster-qwen-tensor-lanes-every-row.md deleted file mode 100644 index 94f0b0cd9a..0000000000 --- a/changelog.d/cluster-qwen-tensor-lanes-every-row.md +++ /dev/null @@ -1,10 +0,0 @@ -### Request-owned tensor-parallel lanes for every Qwen row - -- Every Qwen tensor-parallel row (Qwen3.5 9B, Qwen3.8 27B, Qwen3.5 and Qwen3.6 35B A3B) now serves through the request-owned batch path the 27B used: main's paged KV host, independent lanes at capacities 1 to 8, the resident and SSD prompt-prefix tiers, committed-token logprobs, and automatic widening that keeps the running shares. Each row's LOAD reservation, placement quote and widening quote are priced by its own geometry (its per-rank KV heads and recurrent state, and a routed-expert row's packed MoE partials). Capacity one is the same path one lane wide. A row that can also run the pipeline keeps the pipeline as a planning candidate while tensor parallel is priced by its quote. -- A routed-expert cohort runs each row's router, shared expert and selected experts with that row's own arithmetic and sends every row's packed expert and shared partials in one collective, so a wider cohort still issues two collectives a layer and every row's tokens equal its solo bytes (`moe-rows-one-collective-v1` in the load agreement). -- The Qwen3.5 9B's inline head now runs as the tensor-parallel speculative assistant beside the 27B's (the assistant inventory and quote follow each row's configuration). The A3B rows' heads are routed-expert layers the tensor assistant does not load, so they serve without speculation. -- Each rank's cut of a row-parallel projection, expert bank or expert input column is copied once into a row-major buffer at LOAD. The interior-axis gather left a transposed view, which every quantized matmul and expert gather copied whole at each call: a routed-expert decode step copied the rank's gate/up and down expert banks for every layer, and every row copied each dense row-parallel weight. Values are unchanged. -- A tensor-parallel decode step is submitted to the GPU layer by layer while it is built (`Qwen35LayerSubmission`), and decode steps, assistant rounds and their selection encode into command buffers of up to 100 operations instead of the worker's 16, as GLM's TP decode does. Tokens are unchanged. -- Batched decode rows take each row-parallel projection's cached FP32 scales and biases, the ones its single-row forward reuses (`QuantizedLinear.independentRowsForward`), instead of widening the BF16 constants inside every quantized matmul, where MLX made that widening on the thread's default GPU stream rather than the caller's. A widened step no longer spans two GPU streams there, and two kernels a projection a step go away. Values are unchanged. -- The single-lane tensor-parallel owner is retired with its own page pool, its prefix cache and `DARKBLOOM_CLUSTER_QWEN_TP_PAGED_KV`; Qwen tensor parallel now requires the authenticated sealed data plane, and each lane reserves its full context at LOAD instead of growing by granules. -- Full-artifact qualification on the pair is still required. diff --git a/changelog.d/cluster-qwen-tensor-prefix-ssd.md b/changelog.d/cluster-qwen-tensor-prefix-ssd.md deleted file mode 100644 index 7ea897783f..0000000000 --- a/changelog.d/cluster-qwen-tensor-prefix-ssd.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel prefix SSD tier - -Keep the Qwen27 TP batch owner's prompt prefixes in the encrypted SSD tier as well as in memory, so a repeated long prompt restores its prefix after both Macs restart. Each rank writes its own shard (and the assistant's trusted history) behind serving after bilateral clean retirement. The sealed vote now counts SSD records, and a second exchange confirms that both ranks restored, or both prefill from zero. Records are scoped by plan, shares, artifact, storage, both builds and assistant policy, never by membership epoch. The prefix agreement field becomes `qwen-tensor-parallel-prefix-v2`. diff --git a/changelog.d/cluster-qwen-tensor-rank-ledger.md b/changelog.d/cluster-qwen-tensor-rank-ledger.md deleted file mode 100644 index 2f563b5195..0000000000 --- a/changelog.d/cluster-qwen-tensor-rank-ledger.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel ranks reserve only their own heads - -Each tensor-parallel rank now reserves the request state it actually holds: its own KV heads, linear-attention heads, and its own rows and columns of the fused projections and projection constants under the chosen split. The replicated assistant, hidden-width buffers and gathered logits stay whole on both ranks. Setup quotes both ranks of every supported split. Placement charges each Mac its own figure. It keeps a split for later widening only when, on each Mac, the serving owner's weights and request plus the widened load fit, because widening is previewed before the old owner is released. On a busy second Mac, onboarding can therefore pick a split that widens to two speculating requests instead of one that never can. The whole-model figure remains the bound either rank stays under. diff --git a/changelog.d/cluster-qwen-tensor-speculation.md b/changelog.d/cluster-qwen-tensor-speculation.md deleted file mode 100644 index 606c05b54b..0000000000 --- a/changelog.d/cluster-qwen-tensor-speculation.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel resident assistant - -Discover and fully quote the catalog Qwen27 embedded assistant during normal cluster setup, retaining the native inventory policy through bilateral launch and READY. Eligible concurrent requests keep independent histories and accepted-token credits while sharing captured target verification; ordinary media, logprob and history-filter paths retain their capabilities. Price surviving cohort backing, the next verification window and assistant prefix ownership through checked retirement. Explicit MTP off retains the fully quoted ordinary target. Full-artifact correctness and release qualification remain separate from component fixtures. Bound the assistant's trusted-history flush to evaluated 512-row blocks (first draft and ordinary decode), and price a verify window by what it writes: partial-page replacements and segment slack, not a second history. At the 64K profile the whole-model bound for one speculating request fell from about 66 GiB to 22 GiB, and for two from 96 GiB to 36 GiB; installed qualification is separate. The saved setup's status binding carries the speculation the session derives, so a pair serving the resident assistant reads as ready instead of stale and automatic setup finishes; capacity-one refusals keep their capacity or deadline reason. The resident owner's memory gate measures compression and swap-out from the start of each served scope instead of the owner's whole life (limits unchanged), so ordinary background compression on a busy Mac no longer refuses later requests. Concurrent speculative requests verify each request's draft window with that request's own single-window arithmetic inside one collective per row-parallel projection, so they emit exactly the tokens they emit alone. One batched product changed kernel at four three-column windows and altered near-tie tokens. diff --git a/changelog.d/cluster-qwen-tp-exact-vectors.md b/changelog.d/cluster-qwen-tp-exact-vectors.md deleted file mode 100644 index f3d7f771a8..0000000000 --- a/changelog.d/cluster-qwen-tp-exact-vectors.md +++ /dev/null @@ -1,19 +0,0 @@ -### Qwen tensor-parallel decode with batch-invariant projections - -Every Qwen tensor-parallel plain decode step, verify window and batched row -(the 9B, the 27B and the dense projections of both 35B A3B rows) now projects -through the SDK's batch-invariant affine kernel. Each position of a speculative -verify window therefore has the bits of the plain decode step that computes the -same token, and each concurrent row the bits it has alone, at any cohort width. -This changes the rounding of every decode projection relative to MLX's own -kernels, so recorded tensor-parallel references must be regenerated once. - -A row-parallel projection reads its bf16 activation directly and writes its -FP32 partial (no separate widening launch and no FP32 copy of its scales), and -its rounded all-sum feeds the fused residual step, so a step runs far fewer GPU -launches. Each rank logs the arithmetic it resolved once per load -(`darkbloom-aqv-kernel-v1`: exact vectors, the kernel's arithmetic and words -per lane on that GPU family, its layouts), and the pair binds whether exact -vectors are on into its load agreement, so two ranks that resolved it -differently refuse to load. `DARKBLOOM_QWEN_TP_EXACT_VECTORS=0` (diagnostic -only, never forwarded to an installed rank) keeps MLX's kernels. diff --git a/changelog.d/cluster-qwen-tp-fenced-sums.md b/changelog.d/cluster-qwen-tp-fenced-sums.md deleted file mode 100644 index 5ee109ff4b..0000000000 --- a/changelog.d/cluster-qwen-tp-fenced-sums.md +++ /dev/null @@ -1,13 +0,0 @@ -### Qwen tensor-parallel ranks wait for each all-sum in the kernel that reads it - -The Qwen 3.5 residual step (`ResidualRMSNorm`) now reads its FP32 tensor-parallel -all-sum as a fenced input, as GLM's hyper-connection sites already did, and a -worker turns `MLX_METAL_FENCED_INPUTS` on for every tensor-parallel family whose -kernels read their sums that way (`ClusterResidentModelCatalog.Family -.tensorParallelSumsAreFencedInputs`; a launcher's own value is kept). The kernel -that reads a sum then waits for the CPU itself instead of MLX's separate -fence-wait launch, about 128 of them per verify window of the 27B. MLX consults -the setting only for inputs a kernel declares fenced, so every other launch is -unchanged, and only where the GPU waits changes, never a value. The fused fence -update stays a launcher's choice. Each rank logs the choice (`fenced_sums=` in -`darkbloom-aqv-kernel-v1`) and binds it into the load agreement. diff --git a/changelog.d/cluster-qwen-tp-pipelined-draft.md b/changelog.d/cluster-qwen-tp-pipelined-draft.md deleted file mode 100644 index 0835796e1b..0000000000 --- a/changelog.d/cluster-qwen-tp-pipelined-draft.md +++ /dev/null @@ -1,12 +0,0 @@ -### Qwen tensor-parallel speculative rounds keep the GPU busy - -A single-request speculative round no longer waits for each assistant draft -step before building the next one, and no longer waits for the drafts before -building the verify window: the draft chain and the window are submitted back -to back, and the window itself is submitted layer by layer as a decode step -already was. The drafted tokens' vocabulary check is evaluated with the window -and read when the window is confirmed. Every rank still runs the same -collectives in the same order, the emitted tokens are unchanged, and a failure -on either rank fails the round on both. Batched rounds keep their draft -schedule. `DARKBLOOM_QWEN_TP_MTP_PIPELINED_DRAFT=0` (diagnostic only) waits for -each draft step. diff --git a/changelog.d/cluster-qwen-tp-window-submission-switch.md b/changelog.d/cluster-qwen-tp-window-submission-switch.md deleted file mode 100644 index 400a0037ae..0000000000 --- a/changelog.d/cluster-qwen-tp-window-submission-switch.md +++ /dev/null @@ -1,9 +0,0 @@ -### Faster Qwen tensor-parallel verification: windows evaluated whole - -Qwen tensor-parallel speculative verify windows are evaluated whole instead of -being submitted to the GPU one decoder layer at a time. On two M5 Ultra Macs -serving Qwen3.8 27B this makes a single request about 18 % faster (60 against -51 tokens per second) and four concurrent requests about 5 % faster, with -identical outputs. `DARKBLOOM_QWEN_TP_WINDOW_LAYER_SUBMISSION=1` (diagnostic, -never forwarded to an installed rank) submits windows by layer again; both -ranks bind the choice into their load agreement. diff --git a/changelog.d/cluster-qwen27-native-context.md b/changelog.d/cluster-qwen27-native-context.md deleted file mode 100644 index 3a66dcc032..0000000000 --- a/changelog.d/cluster-qwen27-native-context.md +++ /dev/null @@ -1,5 +0,0 @@ -### Qwen3.8 27B at its native context on a tensor-parallel pair - -- A Qwen3.8 27B pair serving in tensor parallel accepts the context a single Mac serves: prompts up to 262,143 tokens and up to 32,768 output tokens within 262,144 (previously 32,768 + 32,768 within 65,536). LOAD and the planner still size the pair for the 32,768 + 32,768 request at every width (one to eight lanes), so no lane reserves KV for the whole context in advance. Each longer request is charged at its own context when a rank reserves it, and each rank's live memory gate admits it or refuses it alone (HTTP 503 with the context the pair serves now) while other requests keep running. Readiness and keep-warm answers carry that serving context. The 27B's pipeline modes and every other Qwen row keep their limits. -- Qwen tensor-parallel paged lanes reserve their prompt and a 1,024-token granule when they open and grow between steps, instead of reserving every page of the prompt and output at once. Outputs are unchanged byte for byte. -- The 27B's worker profile, load agreement and installed setup fingerprints change. Existing 27B setups re-plan after the update, and 27B pair qualification records are recorded again. diff --git a/changelog.d/cluster-rdma-system-settings.md b/changelog.d/cluster-rdma-system-settings.md deleted file mode 100644 index efe4fe0268..0000000000 --- a/changelog.d/cluster-rdma-system-settings.md +++ /dev/null @@ -1,3 +0,0 @@ -### RDMA setup guidance for macOS 27 - -When RDMA over Thunderbolt is turned off, `darkbloom cluster` and its setup screens now point a Mac on macOS 27 or later to Apple's switch in System Settings (Privacy & Security, RDMA over Thunderbolt, then restart) instead of macOS Recovery. Macs on macOS 26 keep the Recovery steps with `rdma_ctl enable`. Darkbloom still never changes the setting itself. diff --git a/changelog.d/cluster-served-speed-build-scope.md b/changelog.d/cluster-served-speed-build-scope.md deleted file mode 100644 index eaa8d9c7b3..0000000000 --- a/changelog.d/cluster-served-speed-build-scope.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster served speeds count only for the build that served them - -- A two-Mac pair's planner and request router now use a served request's speed only for the worker build that served it. Each speed record in `~/.darkbloom/cluster/served-speed.json` names every rank's worker build; records from another build, including every record written before this release, give no speed and age out of the file, so a new build plans from the share probes and link measurements until it has served. Speeds served by older, slower builds no longer hold a tensor-parallel split where the current build's own probes balance it. The plan is still made for the prompt and answer lengths the pair's clients send. -- The plan says how many records it left out (`N record(s) from other worker builds ignored`). `darkbloom-cluster-plan plan --served` and `route --served` use records only for the build named with `--served-build SHA256`. diff --git a/changelog.d/cluster-service-after-reboot.md b/changelog.d/cluster-service-after-reboot.md deleted file mode 100644 index 2918761099..0000000000 --- a/changelog.d/cluster-service-after-reboot.md +++ /dev/null @@ -1,5 +0,0 @@ -### The cluster comes back after a reboot - -- After a restart each Mac serves again once it is logged in (by itself with automatic login on); `darkbloom cluster` says which applies to each Mac. -- `darkbloom cluster` (leader and members) installs this Mac's cluster service as a per-user LaunchAgent (`io.darkbloom.cluster-service.`): launchd starts it at login and runs it under the cluster supervisor (`darkbloom cluster service --supervise`), which restarts it after 15 s doubling to 300 s and parks it after three quick failures; launchd restarts only a supervisor that crashed. Running `darkbloom cluster` again keeps an unchanged agent, replaces a changed one, restarts a parked one, and takes over from a service an earlier version started in a terminal. Nothing is asked beyond the cluster link's one approval. -- `darkbloom cluster stop` stops this Mac's cluster service and removes its login agent (on the leader the cluster stops serving first); unpairing the last pairing (`darkbloom cluster pair --forget`) removes it too. `darkbloom status` shows whether the cluster service starts at login, whether it runs, and its supervisor's phase. diff --git a/changelog.d/cluster-service-network-identity.md b/changelog.d/cluster-service-network-identity.md deleted file mode 100644 index 6170edb0d2..0000000000 --- a/changelog.d/cluster-service-network-identity.md +++ /dev/null @@ -1,5 +0,0 @@ -### Cluster background network identity - -- Associate the cluster login service with its enclosing app so macOS can retain Local Network approval when the setup terminal exits. -- Replace older unassociated jobs through the normal cluster command; preserve idempotent startup and stop behavior. -- Keep socket failure details in lease diagnostics and explain the session lifetime of an ad-hoc development service. diff --git a/changelog.d/cluster-session-rank-lease-keep-warm.md b/changelog.d/cluster-session-rank-lease-keep-warm.md deleted file mode 100644 index 37780be89e..0000000000 --- a/changelog.d/cluster-session-rank-lease-keep-warm.md +++ /dev/null @@ -1,10 +0,0 @@ -### Cluster sessions without a fixed lifetime; rank lease and keep-warm - -- A model served by two Macs stays loaded and serving until you stop it, and a Mac that disappears is reported at once instead of stalling. -- A two-Mac cluster session has no fixed lifetime and no request count any more. The 300-second session (1,800 for MiMo), the sixteen-request cap, the installed session's teardown at its deadline, the rotation to a new session after sixteen requests and the member session's 900-second cap are removed; a loaded model stays resident and serving until it is stopped (`darkbloom stop`, an operator unload, an autopilot model switch) or a real failure is detected. The capability record drops `maxLifetimeSeconds` and `maxRequests`. -- Each worker holds a renewable rank lease instead (S03): armed before its weights load at most one grant away, renewed every 5 s for 30 s by its owner with an `extendDeadline` line on the worker's control pipe, which the worker reads from launch, through the load. An owner that stops renewing (it stopped, died or lost its link) leaves the worker to end by itself within the time to live, through the forced exit that releases MLX's wired memory first. The leader renews each remote owner's lease the same way (`renew` frames), and each owner renews its own worker's. -- A cluster member honors the coordinator's grant lease (S15): `native_pair_lease` frames move its deadline (a grant may leave at most 120 s plus 5 s of clock allowance); an established session survives a dropped control connection for the 90-second grace, and the member claims it again with `resume` in its registration. -- Keep-warm, on by default (S27): a GPU pulse on each worker's own executor every half second while idle once the first request has run (back-off for a minute after a slow submission), and a 1x16 data-plane exchange both ranks run about once a second while idle, sequenced by the leader; a failed exchange ends the session cleanly. `darkbloom-cluster-pair-check --keep-warm off` and the worker's `--keep-warm off` turn it off for comparison. -- `darkbloom-cluster-pair-check` takes any number of repetitions, idle gaps between them (`--idle-seconds`) and a qualification switch that stops renewing both leases (`--stop-renewals-after-seconds`). -- A Mac that vanishes from a cluster is a stated failure, not a stall: when the other member's link control connection closes or goes silent and does not come back within the link's own re-dial time (5 s for a closed connection, 10 s for a silent one with the default link timing, never past the 30 s rank lease), the leader fails the request in flight at once with the reason (`link edge: follower lost: ...`), stops waiting for cleanup proofs that can no longer arrive (the session is quarantined, rank 1 stays unproven, the other Mac's own lease and device journal still end its rank), and exits instead of lingering for minutes; the follower likewise fences a vanished leader's session at once instead of at the end of its lease. A follower that releases a session without a cleanup proof (its owner ended at launch) ends the leader's wait the same way. The follower now says why its rank ended (its worker's last word, e.g. the stage-load memory gate's refusal) and the leader's incident carries it, so such a start is classified `memory_gate_refused` with the follower's own numbers instead of an unexplained `peer_lost`. A cluster member whose coordinator control connection ends or loses trust says why (`Distributed serving stops: .`) and exits with a failure status. The stale bootstrap-directory check no longer connects to a listener's socket (a connect could fail a live launch); it reads the descriptor tables instead. -- Nothing of a dead cluster session is left behind (orphan eradication, ported from the owner's oMLX and ThunderMLX lifecycle work). An orphan sweep runs at every member's start and end and before every supervised restart, and on demand as `darkbloom cluster reap [--json] [--no-wait]`: a worker or owner whose parent process is gone is given its own contract (the rank lease, the owner's longest signal allowance and the forced exit's dead-man) to end, then SIGTERM, and SIGKILL only after the kill margin, and only while its process number still holds the same process (same start time; a reused number is never signalled); a device journal whose owner died is cleared through `cluster recover`'s proof; bootstrap directories whose socket no process holds any more are removed. `darkbloom cluster verify-teardown [--json] [--baseline-wired-bytes N] [--samples N]` reports, after a stop, whether any cluster process, wired memory above the baseline (tolerance: the larger of 1 GiB and 1/128 of physical memory), stranded journal or bootstrap directory is left (`darkbloom_cluster_teardown_verification_v1`, exit 1 when not clean). `darkbloom cluster cancel-all` force-cancels every request served on this Mac on its own: SIGUSR1 makes an owner fence its worker (the protocol's own drain) and a worker end its requests through the forced exit. A forced exit whose release keeps completing durable writes (`ProcessForcedExit.noteProgress`) gets its 20 s dead-man extended exactly once, to 40 s, and never otherwise. Every rank is started with MLX's command-buffer bounds (`MLX_MAX_OPS_PER_BUFFER=16`, `MLX_MAX_MB_PER_BUFFER=512`) unless the operator pinned them. diff --git a/changelog.d/cluster-setup-reasoning-probe.md b/changelog.d/cluster-setup-reasoning-probe.md deleted file mode 100644 index e245dee258..0000000000 --- a/changelog.d/cluster-setup-reasoning-probe.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster setup respects model reasoning defaults - -- Cluster setup tests a response using each model's default reasoning controls, so GLM-5.3 Flash no longer rejects the generic probe because it sends a binary thinking override. Reasoning-only output remains visible when the test token budget expires. diff --git a/changelog.d/cluster-sharded-deployments.md b/changelog.d/cluster-sharded-deployments.md deleted file mode 100644 index f95092b978..0000000000 --- a/changelog.d/cluster-sharded-deployments.md +++ /dev/null @@ -1,6 +0,0 @@ -### Cluster pairs serve sharded deployments by default - -- The planner chooses tensor parallel or a pipeline for the Macs it detects; phase split, phase split with MTP, the pipeline-prefill/tensor-decode hybrid and the per-request "alone" route are kept but off by default, reachable only behind `DARKBLOOM_CLUSTER_HANDOFF_MODES=1`, and a setup saved with one of them is refused at start without it. The onboarding's deployment line names the sharded mode. -- Qwen models with an MTP head and MiMo V2.6 Flash can decode as speculative rounds across the pipeline (`pipeline_mtp_v1`): the last Mac holds the head and a copy of the token embedding, drafts, and both Macs verify the drafts in one window. The planner credits the rounds only from what the same placement served with and without them, and a pair serves them only where its own qualification records pass. -- MiMo V2.6 Flash keeps prompt prefixes on both Macs, in memory and in the encrypted SSD tier, restored on both or neither. -- The pair's SSD prompt-cache tier carries its daily write cap across restarts, keeps other plans' records within one byte budget instead of wiping them, stores speculative history once per record, reads records page-aligned without a copy, and hashes model files in parallel. diff --git a/changelog.d/cluster-ssd-prefix-quantized-records.md b/changelog.d/cluster-ssd-prefix-quantized-records.md deleted file mode 100644 index 380fe69bfe..0000000000 --- a/changelog.d/cluster-ssd-prefix-quantized-records.md +++ /dev/null @@ -1,6 +0,0 @@ -### Quantized SSD prompt-prefix records on the two-Mac cluster - -- The pair's encrypted SSD prompt-prefix records now store attention rows at the single-Mac checkpoint precision, `balanced` by default, like every other model's checkpoints: older rows in 4-bit keys and values (affine groups of 64, FP32 scale and offset, keys Hadamard-rotated) and each record's newest 128 rows exact. Recurrent, convolution and speculative-head state stays exact. A Qwen 3.8 27B tensor-parallel rank's attention rows at 32,768 tokens take about 3.2 times fewer bytes; GLM-5.3-Flash DSA layers about 1.8 times fewer, in pipeline and tensor parallel (BF16 latents; its index keys, pool gates and MTP history stay exact). Live KV stays native. -- A prefix restored from a quantized record is close to, not identical with, computing it again. `engine_v2_kv_checkpoint_quantization = "native"` (or `DARKBLOOM_CBV2_CHECKPOINT_QUANTIZATION=native`, per model with `engine_v2_kv_checkpoint_quantization_by_model`) keeps the pair's records byte-exact. Both Macs must resolve the same precision: the leader does not sync it, and the ranks bind it into their load agreement and refuse to load otherwise. Records of one precision are never restored under another. -- Quantizing a decoded row again does not give it back (the codec is not idempotent on its own output), so a record written from a request that was itself restored from a record keeps the restored rows' first encoding instead of quantizing them again: through repeated restore-and-extend cycles, such as a long conversation, each restored row stays as it was first stored. -- `darkbloom-cluster-tp-check run --prefix-records native|balanced|k8v4|k8v8` measures a record on real weights: per-layer errors, bytes against a native record, the prompt tail scored from the captured and the restored state, and the output after the restore. `darkbloom-cluster-pair-check --prefix-ssd-quantization` selects the workers' record precision. diff --git a/changelog.d/cluster-stage-kv-quantization.md b/changelog.d/cluster-stage-kv-quantization.md deleted file mode 100644 index 0dbf1978c8..0000000000 --- a/changelog.d/cluster-stage-kv-quantization.md +++ /dev/null @@ -1,17 +0,0 @@ -### Two-Mac clusters follow the provider's KV quantization - -- A pair's stage KV now uses the same live precision a single Mac uses for the - model: `engine_v2_kv_quantization` (global or per model) and - `DARKBLOOM_CBV2_KV_QUANTIZATION`, resolved on each Mac and passed to its - worker. The default stays native; pairs whose Macs keep it are unchanged. -- With `balanced`, `k8v4` or `k8v8`, the Qwen 3.5 family (Bonsai included), - Gemma 4 and Nemotron 3.5 stages and every Qwen tensor-parallel row's - request-owned lanes (9B, 27B, Qwen3.5/3.6 35B A3B, any capacity) store packed KV on the provider's own pool, after the same kernel check, - and their memory planning counts packed rows. Both Macs must resolve the same - precision; otherwise their load agreements differ and the pair refuses to - load. Set the pair's model to `native` per model to keep a packed global - setting off the pair. -- Packed stages keep no prompt prefixes, as on one Mac for packed KV. Phase - split, GPT-OSS and GLM refuse a packed precision; MiMo stays native. The pair's SSD prefix records stay exact native states. -- `DARKBLOOM_CLUSTER_KV_BACKEND=contiguous` is removed: cluster stage KV is - paged only. diff --git a/changelog.d/cluster-steady-visible-tensor-parallel.md b/changelog.d/cluster-steady-visible-tensor-parallel.md deleted file mode 100644 index 175f6f5a82..0000000000 --- a/changelog.d/cluster-steady-visible-tensor-parallel.md +++ /dev/null @@ -1,13 +0,0 @@ -### Steadier, visible tensor-parallel choice in two-Mac clusters - -- Keep each pair's last eight link measurements from the last 30 days and plan - on their median, so one fast or slow load no longer switches a model between - tensor parallel and a pipeline. Link files from earlier releases still read. -- End a model's line in the setup's model list with a short reason when the - model supports tensor parallel but is split otherwise, such as "tensor - parallel: slower here"; models without tensor parallel show nothing extra. -- Explain that Qwen3.8 27B leaves out the pipeline because only tensor parallel - keeps images, video and logprobs, instead of saying no pipeline fits. -- Read the saved link measurements in `darkbloom-cluster-plan plan` when - `--link` is not given (or `--link-probes FILE`), say so, and print reduction - costs in ms or µs. diff --git a/changelog.d/cluster-stop-leader-drain.md b/changelog.d/cluster-stop-leader-drain.md deleted file mode 100644 index 23c1be8823..0000000000 --- a/changelog.d/cluster-stop-leader-drain.md +++ /dev/null @@ -1,7 +0,0 @@ -### Cluster stop ordering - -- A paired leader now retires its owned part before asking its follower to stop, preserving the native shutdown channel. Failed retirement or missing peer acknowledgement keeps the login service available for recovery and returns an error. - -Require a fresh local supervision acknowledgement before stopping the peer so stale idle status cannot bypass a child start already in flight. - -Keep follower lease intent alive through local planned drain; serialize background serve/stop reconciliation and wait for outstanding running leases before publishing stop acknowledgement. A stop the pair could not finish exits with status 1 and the pair's reason, without usage text. diff --git a/changelog.d/cluster-stop-local-only.md b/changelog.d/cluster-stop-local-only.md deleted file mode 100644 index ed2b565fa1..0000000000 --- a/changelog.d/cluster-stop-local-only.md +++ /dev/null @@ -1,3 +0,0 @@ -### Stop a cluster Mac whose peer is gone - -`darkbloom cluster stop --local-only` stops only this Mac's cluster service and removes its login agent. It never asks the other Mac, for when that Mac is gone for good. Without the flag, a leader still drains the pair first and keeps its service when the member cannot acknowledge. The output says that the other Mac was not asked to stop. diff --git a/changelog.d/cluster-tensor-parallel-first.md b/changelog.d/cluster-tensor-parallel-first.md deleted file mode 100644 index 9a8e3f13c1..0000000000 --- a/changelog.d/cluster-tensor-parallel-first.md +++ /dev/null @@ -1,6 +0,0 @@ -### Two-Mac clusters place tensor parallel first wherever it fits - -- A model whose tensor-parallel layout fits both Macs is now set up in tensor parallel even where the speed estimate favored a pipeline; the setup says so ("the model fits, so both Macs share every layer of every token") instead of claiming a gain it does not predict. A setup that loads now still goes ahead of tensor parallel that would not, and predictions are still shown. -- A new pair's first setup is tensor parallel too: before any load has measured the cable, it plans on the same assumed sealed reduction a forced plan uses, labelled as assumed. -- Automatic widening never assumes a link cost: it plans only on the pair's own recent sealed link measurement, and without one it keeps the running setup. -- `darkbloom-cluster-plan plan --tensor-parallel-first` plans the same way; without the flag the plan tool keeps the speed comparison. diff --git a/changelog.d/cluster-tensor-parallel-roster-plans.md b/changelog.d/cluster-tensor-parallel-roster-plans.md deleted file mode 100644 index 9e6ac732e4..0000000000 --- a/changelog.d/cluster-tensor-parallel-roster-plans.md +++ /dev/null @@ -1,5 +0,0 @@ -### A tensor-parallel cluster registers with the coordinator - -- A pair that serves a model in tensor parallel (GLM-5.3-Flash, Qwen3.8-27B) now registers its roster plan with the coordinator. The plan names `tensor_parallel_v1` and no layer cut, as the coordinator requires; before, the member registered the stage end as a cut, refused its own plan, and the pair served only its local API. A setup with unequal tensor-parallel shares is refused at registration until the plan carries its shares. -- The onboarding's start line for a cluster that serves through Darkbloom no longer says public serving is off in this build: it serves its owner's requests, and public requests where Darkbloom has qualified the model and split. -- A plan in `pipeline_prefill_tensor_decode_v1` (pipeline prefill, tensor-parallel decode) also registers: the coordinator lists the mode, and the member no longer refuses its own plan. diff --git a/changelog.d/cluster-tensor-share-probes.md b/changelog.d/cluster-tensor-share-probes.md deleted file mode 100644 index e0b39d92f9..0000000000 --- a/changelog.d/cluster-tensor-share-probes.md +++ /dev/null @@ -1,15 +0,0 @@ -### Tensor-parallel shares balanced by each Mac's measured speed - -- Time each Mac's own share of a dense Qwen model when it loads in tensor - parallel (at most about a second and a half, alone, nothing crossing the - cable), and keep each Mac's newest timing per share and model for 30 days on - the leading Mac. The next plan balances the shares by those timings: with the - timings an M3 Ultra and an M5 Max measured, Qwen3.8 27B is planned 1:1 - instead of 2:1 after one load. A Mac short of memory skips the timing, and it - never fails a load. -- Stop predicting a larger tensor-parallel share faster than a smaller one: a - Mac's measured shares are no longer drawn toward its whole-model speed, and - what the pair served corrects all of a Mac's measured shares alike. -- Read the saved share timings in `darkbloom-cluster-plan plan` (or - `--share-probes FILE`) and name the shares used, as the setup plans. -- A load that serves the speculative head balances its shares on each Mac's measured verify window rather than its single-token step, because its rounds run windows: on the Qwen3.8 27B pair that moves the split from 3:2 to about even. diff --git a/changelog.d/cluster-tp-feasibility.md b/changelog.d/cluster-tp-feasibility.md deleted file mode 100644 index 86d6d2d1e4..0000000000 --- a/changelog.d/cluster-tp-feasibility.md +++ /dev/null @@ -1,7 +0,0 @@ -### Fixed - -- Automatic cluster planning considers tensor-parallel placements independently - of pipeline layer cuts and counts enumerated candidates instead of unused - pipeline-cut combinations against its search limit. Unsupported runtime modes and rank counts now explain the pipeline - fallback before requesting a link measurement, without claiming an unmeasured - speedup. This does not enable tensor parallelism for GLM. diff --git a/changelog.d/cluster-validation-and-tensor-batching.md b/changelog.d/cluster-validation-and-tensor-batching.md deleted file mode 100644 index df1c35ace2..0000000000 --- a/changelog.d/cluster-validation-and-tensor-batching.md +++ /dev/null @@ -1,47 +0,0 @@ -### Cluster validation, tensor batching and media ownership - -- Repair local two-Mac setup, installed lane propagation, encrypted peer agreement, - request-scoped placement and delayed automatic batch replacement without - weakening native teardown, memory or failed-qualification gates. -- Preserve measured shard rates and independently price native batch capacity; - exact Qwen3.8 27B retains feature-preserving TP selection with the complete - native request reservation coexisting with LOAD scratch and allocator demand. -- Preview Qwen27 widths 8, 4 and 2 against current bilateral memory before - replacing the serving owner, then recheck the exact proposed width after release. -- Pass the indexed devices, recorded keyed pair-link costs and filtered served - history into automatic replacement, allowing its tensor candidates to be - considered instead of silently using an unmeasured link. -- Add Qwen27 independent TP histories, grouped collectives, per-request sampling - and captured logprobs, with checked bilateral cancellation and retirement. -- Coalesce nearby Qwen27 TP token acknowledgments within the existing bounded - scheduling window so ready rows can decode together; joining, prefill, - cancellation and retirement continue without waiting for a silent client. -- Reuse mutually held original-grid Qwen27 TP prefixes with bounded resident - snapshots, fresh per-request histories, separately priced capture/cache banks - and publication only after bilateral clean retirement. -- Route exact Qwen27 images and video through bounded provider preparation and - the native vision owner, retaining encoded data and host/native allowances - until their respective completion fences. Unsupported controls refuse explicitly. -- Bind streamed logprobs to committed content events and repair local HTTP - reasoning, sampling, usage and tool/constraint parity handling. -- Repair Qwen expert reductions and mixed-router accounting; add Bonsai packed-row - arithmetic and qualification coverage; preserve Gemma prompt arithmetic, - catalog aliases and prefix restore/chunk semantics. -- Repair GPT-OSS, MiMo and Nemotron native independent-history batching, paging, - cancellation and prefix behavior, including existing MiMo speculative/phase - state accounting. Historical phase support is not TP release qualification. -- Order fast Metal fence waits after current-pass GPU producers through the - matching native core pin; installed clustered-concurrency validation remains required. -- Retain explicit full-model hardware gates. Component tests and source support - do not establish universal TP, media parity or release readiness; Qwen27 TP - text speculation remains unfinished; full-artifact prefix/media qualification - and final automatic-planner validation remain separate gates. - -- Preserve an explicit local fast-synchronization diagnostic choice through both installed TP owner and native worker launches. Only canonical `0` or `1` is forwarded; normal defaults and placement remain unchanged. - -Every tensor-parallel worker, widened Qwen rows included, keeps fast synchronization; explicit local synchronization choices still take precedence. Native batching and model capabilities remain enabled. - -Authenticated Qwen3.8 27B TP owners now use the same fully priced request-owned execution at one lane and wider capacities. Automatic capacity changes preserve the tensor split, preventing capacity changes from switching the attention path or repartitioning arithmetic. The original exact-output acceptance gate remains required. - -- Forward an explicit local eager-fence-commit diagnostic through the installed tensor owner and native worker, reporting its canonical value at startup while preserving the default. -- Report completed decode steps by actual batch width once per retired or failed scope, without request content or extra memory samples. diff --git a/changelog.d/cluster-worker-protocol-2.md b/changelog.d/cluster-worker-protocol-2.md deleted file mode 100644 index 909797a2af..0000000000 --- a/changelog.d/cluster-worker-protocol-2.md +++ /dev/null @@ -1,3 +0,0 @@ -### Cluster worker protocol 2: prompts cross as packed token IDs - -- A cluster reservation carries its prompt as packed little-endian token IDs (base64) with an explicit count instead of a JSON number array, and the leader builds a relayed command's link wire once. A 31.5K-token reservation decodes in about 1 ms per hop instead of about 12 ms, which shortens time to first token on long prompts. Both Macs must run the same release: a Mac on the previous protocol is refused at setup or pairing ("Install the same Darkbloom release on both Macs, then run `darkbloom cluster` again"), never in the middle of a request. diff --git a/changelog.d/collected-reasoning-truncation.md b/changelog.d/collected-reasoning-truncation.md deleted file mode 100644 index 8dd3382c77..0000000000 --- a/changelog.d/collected-reasoning-truncation.md +++ /dev/null @@ -1,3 +0,0 @@ -### Preserve truncated reasoning in collected responses - -- Keep unfinished prompt-side thinking in reasoning fields for collected Chat and Responses, retrieval and continued history. Preserve explicit parser overrides, native parsed channels and token usage. diff --git a/changelog.d/distributed-start-signal-restoration.md b/changelog.d/distributed-start-signal-restoration.md deleted file mode 100644 index c57f1cfb13..0000000000 --- a/changelog.d/distributed-start-signal-restoration.md +++ /dev/null @@ -1,5 +0,0 @@ -### Distributed startup signal restoration - -Distributed startup restores both SIGTERM and SIGINT dispositions, including -handler flags and blocked signals, even when one signal was already ignored. -A termination request received before serving starts remains latched. diff --git a/changelog.d/glm-automatic-finite-placement.md b/changelog.d/glm-automatic-finite-placement.md deleted file mode 100644 index 98f8bc77d9..0000000000 --- a/changelog.d/glm-automatic-finite-placement.md +++ /dev/null @@ -1,7 +0,0 @@ -### GLM cluster prefill and finite-calibration placement - -- Scan all structural cuts against current local device bounds and choose a common feasible cut through the existing performance-aware planner. -- Run the selected cut through the installed signed quotation and finite owner path; preserve explicit diagnostic cuts. -- Keep predicted speed, measured-best throughput and calibrated serving eligibility distinct. Public GLM endpoint eligibility is unchanged. -- Raise the registered GLM NVFP4 cluster candidate's prefill chunk cap to 2048 while retaining bounded authenticated logical arrays, raw frames and records. Keep the workspace conservative pending scope-matched native/host peak qualification; other models' default caps and public qualification records remain unchanged. -- Allow finite calibration up to 2048 prompt/chunk tokens with the existing 16-output cap and at most 2064 context. Automatic chunk hints ignore prompts shorter than their configured chunk and match artifact identity when available; fallback uses the current model/worker caps without creating a qualification grant. diff --git a/changelog.d/glm-cluster-still-images.md b/changelog.d/glm-cluster-still-images.md deleted file mode 100644 index 499cee9629..0000000000 --- a/changelog.d/glm-cluster-still-images.md +++ /dev/null @@ -1,5 +0,0 @@ -### Bounded GLM cluster still-image candidate - -- Add bounded encoded PNG ingress, rank-0 native GLM vision loading and causal feature splicing to the private two-rank pipeline, with additive memory charges and cold media prefix isolation. -- Require the explicit local image qualification profile through `darkbloom cluster local glm-5.3-flash --private-glm-image-qualification`; ordinary text serving rejects images before reservation and excludes the vision tower from planning and LOAD. -- Keep video unqualified and audio refused. Full-model image correctness, memory, cancellation and real CLI/HTTP qualification remain required before a serving modality can be advertised. diff --git a/changelog.d/glm-single-mac-speed-shared.md b/changelog.d/glm-single-mac-speed-shared.md deleted file mode 100644 index 80729b4b13..0000000000 --- a/changelog.d/glm-single-mac-speed-shared.md +++ /dev/null @@ -1,7 +0,0 @@ -### GLM-5.3-Flash SDK speedups shared with the single-Mac release - -- The SDK's pipelined KDA prefill recurrence now also covers 64 heads on an 80-core M5 Ultra (two - value-row ranges per GPU core): one Mac and each GLM pipeline stage prefill faster with bit-identical - outputs; a tensor-parallel rank's 32 heads keep their cut, so tensor-parallel GLM is unchanged. -- The CBv2 MTP loop can submit every draft step as soon as it is built (on for the single-Mac GLM - profile); the two-Mac GLM path runs its own speculation loop and is unchanged. diff --git a/changelog.d/glm-tensor-parallel-decode-command-buffers.md b/changelog.d/glm-tensor-parallel-decode-command-buffers.md deleted file mode 100644 index 4271676539..0000000000 --- a/changelog.d/glm-tensor-parallel-decode-command-buffers.md +++ /dev/null @@ -1,4 +0,0 @@ -### GLM tensor-parallel decode command buffers and sum fences - -- GLM tensor-parallel decode steps, MTP rounds and lane rounds encode up to 100 operations a Metal command buffer instead of the rank guard's 16, which prefill keeps; each further buffer cost about 10 µs of GPU time (13.24 to 12.56 ms a decode step on two M5 Ultra, tokens identical). -- GLM tensor-parallel workers let the hyper-connection site wait for each all-sum in-kernel (`MLX_METAL_FENCED_INPUTS`; a launcher value is kept). The fused fence update (`MLX_METAL_FUSED_FENCE_UPDATE`) stays a launcher's choice: its multi-threadgroup path (partials above 32 KB) never signals the CPU, which stalled batched lanes about 0.7 s a round. diff --git a/changelog.d/glm-tensor-parallel-mtp-early-proposals.md b/changelog.d/glm-tensor-parallel-mtp-early-proposals.md deleted file mode 100644 index 08aed4b3db..0000000000 --- a/changelog.d/glm-tensor-parallel-mtp-early-proposals.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel MTP rounds submit their proposals early - -- A GLM tensor-parallel MTP round (solo or batched lanes) submits its NextN priming and proposals as soon as they are built, so the GPU computes them while the host builds the verification forward instead of idling through the whole round's build: a depth-2 round 23.06 to 21.64 ms (95.9 to 102.7 tok/s) and two lanes 115.2 to 121.6 tok/s on two M5 Ultra, tokens and top logits identical. `darkbloom-cluster-tp-check glm --mtp-early none|proposals|layers` compares the modes. diff --git a/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md b/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md deleted file mode 100644 index c335241dba..0000000000 --- a/changelog.d/glm-tensor-parallel-mtp-vocabulary-split.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM tensor-parallel greedy MTP rounds split the head's vocabulary - -- A greedy GLM tensor-parallel MTP round (solo or batched lanes) reads out only its half of the head's vocabulary rows on each rank and agrees on every window token through the round's existing agreement sum (each rank's half maximum and argmax; rank 0's lower index wins a tie, as MLX's argmax does): a depth-2 round 21.32 to 21.05 ms on two M5 Ultra, tokens and top logits identical. Sampled rounds keep the whole head. `darkbloom-cluster-tp-check glm --mtp-vocab-split yes|no` compares them. diff --git a/changelog.d/glm-tensor-parallel.md b/changelog.d/glm-tensor-parallel.md deleted file mode 100644 index 5f2eb5fe06..0000000000 --- a/changelog.d/glm-tensor-parallel.md +++ /dev/null @@ -1,13 +0,0 @@ -### GLM-5.3-Flash runs tensor parallel across two Macs - -- `darkbloom cluster` can now serve GLM-5.3-Flash text requests with both Macs working on every layer (tensor parallel) instead of each Mac holding half the layers. On two M5 Ultra 256 GB it chooses this by itself once the cable has been measured: the setup's test answered at 51 tokens/s against 42 for the layer split, and long prompts prefill at about 3,300 tokens/s against 1,450 (one Mac alone: about 1,800), and decode runs at 53 tokens/s. Every byte between the Macs stays encrypted. A repeated prompt prefix (a chat's history) is reused on both Macs instead of prefilled again. Image requests still use the layer split. -- The cable measurement that decides between the two modes now times the encrypted sum as a running model pays it, not cold: it had read three times slower and kept tensor parallel from being chosen. -- The Macs exchange GLM's per-layer sums at half the size: the model's own 16-bit values instead of the same values widened to 32 bits, with an identical result. Prompts prefill about 14% faster. -- Tensor-parallel decode is faster: the worker lets each GPU command buffer take whole expert banks instead of committing one at every expert layer (about 88 commits a token instead of 22), and MLX spends less host time per kernel launch. On two M5 Ultra, decode went from 53 to about 57 tokens/s through the API (62 in the bench). -- Fixed a hang where the GPU could wait forever on an encrypted sum between two GPU steps. -- What a tensor-parallel setup served no longer resets the speeds the planner learned from a pipeline the same Macs served: it corrects only the tensor-parallel figures. Before, after serving in tensor parallel the planner priced the layer split as fast as one Mac alone and switched back to it. This applies to every model the cluster plans. -- The hardware speed prior no longer counts every routed expert of a mixture-of-experts model as read on each decode step. It counts only the experts a token is routed to, and it does not count replicated weights as divided by a tensor-parallel share. -- Greedy GLM-5.3-Flash requests in tensor parallel now decode speculatively with the model's own next-token-prediction layer, which each Mac now also loads (about 4.2 GB more per Mac): each step checks the layer's guess together with the next token and keeps both when the guess is right, so greedy decode produces more tokens per step (two guesses a step: about 76 tokens/s against 63 in the bench on two M5 Ultra). Sampled requests decode as before. -- Tensor-parallel prefill is faster: each encrypted sum between the Macs is now sealed, sent, opened and added in 256 KiB pieces as they become ready instead of as one block, so the encryption overlaps the transfer (a 15.7K-token prompt prefilled at 3,812 tokens/s against 3,554 in the bench). Every piece is still authenticated, and a piece that does not open fails the request. -- Tensor-parallel decode no longer waits between steps for the serving process's answer to each token (whether to go on). The token is handed over at once and the answer is read once the next step is running, so its round trip overlaps the GPU work (two M5 Ultra through the API: about 73.5 to 77 tokens/s). A stop request still ends the output exactly where it was asked for; one extra step may be computed and is never sent. -- GLM-5.3-Flash decodes and prefills faster on Apple silicon, on one Mac and across two: fewer and faster GPU launches for the hyper-connection, mixture-of-experts and sparse-attention steps, and less CPU time per launch. Outputs are unchanged bit for bit. On two M5 Ultra through the API, decode went from about 78 to 90 tokens/s and long-prompt prefill from about 3,470 to 3,540 tokens/s. diff --git a/changelog.d/glm53-native-prerequisites.md b/changelog.d/glm53-native-prerequisites.md deleted file mode 100644 index 23b01b2874..0000000000 --- a/changelog.d/glm53-native-prerequisites.md +++ /dev/null @@ -1,3 +0,0 @@ -### GLM-5.3-Flash native prerequisites - -- Use one peer-status observation for each finite GLM terminal-context decision, avoiding a false transport-loss rejection across an expected peer close while preserving exact acknowledgment consumption, frozen connection identity and durable owner/fence retirement. Encrypted loopback CPU coverage does not qualify model, GPU, RDMA or serving behavior. diff --git a/changelog.d/local-responses-previous-response-id.md b/changelog.d/local-responses-previous-response-id.md deleted file mode 100644 index 3454d2ce8a..0000000000 --- a/changelog.d/local-responses-previous-response-id.md +++ /dev/null @@ -1,4 +0,0 @@ -### The local Responses API continues a conversation from `previous_response_id` - -- `/v1/responses` on a single Mac and on a cluster now honours `previous_response_id`: the request continues the earlier input and that response's output, as with OpenAI. A follow-up that sends only a `function_call_output` item resolves its tool call instead of failing with 400, and a later turn remembers earlier ones. -- An ID this process does not hold (never served, sent with `"store": false`, dropped from the bounded in-memory store, or from before a restart) returns 400 with code `previous_response_not_found`. diff --git a/changelog.d/media-processor-refusals-400.md b/changelog.d/media-processor-refusals-400.md deleted file mode 100644 index 6fa2b41053..0000000000 --- a/changelog.d/media-processor-refusals-400.md +++ /dev/null @@ -1,3 +0,0 @@ -### Media the model's processor refuses answers 400 on one Mac and on a pair - -- An image or video the model's processor refuses now returns HTTP 400 `Invalid media input.` (`invalid_media`) on one Mac and on a two-Mac pair: for Qwen 3.5 and 3.8 a side below 32 pixels (a 16×16 PNG, for one; the processor does not upscale it) or an aspect ratio above 200:1, a video without a decodable track, or more media than a processor takes. It returned the retryable 503 capacity answer, so the coordinator tried other providers that refuse it the same way. diff --git a/changelog.d/mlx-fast-fence-gpu-queue-starvation.md b/changelog.d/mlx-fast-fence-gpu-queue-starvation.md deleted file mode 100644 index 6acb490979..0000000000 --- a/changelog.d/mlx-fast-fence-gpu-queue-starvation.md +++ /dev/null @@ -1,16 +0,0 @@ -### One GPU stream per decode graph, and no GPU-on-GPU fence spins - -With MLX fast fences (`MLX_METAL_FAST_SYNCH=1`) a widened Qwen 3.8 27B -tensor-parallel owner could stop at its first multi-row plain decode (the c14, -c17 and c39 stalls). MLX cast each batched 4-bit projection's bfloat16 scales -and biases to float32 on the thread's default GPU stream instead of the stream -the caller passed, and mlx-swift runs everything else on its own process-wide -stream, so that decode graph ran on two GPU streams. A fast GPU fence wait is a -kernel that spins on its queue until the other queue's timestamp arrives, and -Metal does not promise that the other queue runs meanwhile, so both queues -stopped. The casts (and MLX's other helper ops that dropped the caller's -stream) now stay on the caller's stream, and a GPU stream never spins on -another GPU stream: it waits on a shared event, while the CPU <-> GPU -collective waits keep the spinning fast path. Synchronization only: tokens are -unchanged. Widened Qwen 3.8 27B owners stay on the event path until a two-Mac -acceptance with fast fences passes on this fix. diff --git a/changelog.d/pair-check-reservation-fields.md b/changelog.d/pair-check-reservation-fields.md deleted file mode 100644 index e84ba46281..0000000000 --- a/changelog.d/pair-check-reservation-fields.md +++ /dev/null @@ -1,3 +0,0 @@ -### Pair-check reservations keep their media - -- `darkbloom-cluster-pair-check` hands each worker the whole reservation when it moves the deadline to that worker's clock. It dropped still images and Qwen image/video input, so those qualification requests reached the workers without their media. The owner and peer-link hops re-time reservations with the same field-preserving copy. diff --git a/changelog.d/qwen-prefill-steel-tiles.md b/changelog.d/qwen-prefill-steel-tiles.md deleted file mode 100644 index bfe0771e00..0000000000 --- a/changelog.d/qwen-prefill-steel-tiles.md +++ /dev/null @@ -1,17 +0,0 @@ -### Faster prompts on Macs without neural accelerators - -- MLX's steel affine quantized matmul computes prompt-sized products (256 rows - or more, 64-aligned outputs) in 64-row x 32-column tiles for 16-bit inputs and - 32 x 64 for FP32 partials instead of 32 x 32 on GPUs without neural - accelerators (M1-M4, and the M3 Ultra rank of a pair). On the M3 Ultra alone a - 4,096-token prompt took 2.5% less time (27B 12.37 -> 12.06 s, 9B 3.55 -> 3.46 s) - with the same tokens. `MLX_QMM_STEEL_TILE=32` restores the previous tile. -- Qwen tensor-parallel prompt frames are submitted to the GPU every four layers - while they are built (`DARKBLOOM_QWEN_TP_PREFILL_STRIDE=0` restores whole-frame - evaluation). With both changes the 27B pair at 1:1 reached its first token - 1.4-3.1% sooner (4K 8.22 -> 8.08 s, 16K 36.7 -> 35.5 s, 32K 81.8 -> 80.0 s) and - the 9B pair 1.1-2.3% sooner (4K 2.63 -> 2.60 s, 32K 27.5 -> 26.9 s), with the - same tokens. -- Diagnostics: `darkbloom-cluster-tp-check qwen-prefill` (one rank's prompt - frames, layers and projections), `DARKBLOOM_QWEN_TP_PREFILL_FRAME_TIMING=1` - and `pair-check --worker-environment`. diff --git a/changelog.d/qwen-tp-batched-cohort-drafts.md b/changelog.d/qwen-tp-batched-cohort-drafts.md deleted file mode 100644 index b4f1ffbff4..0000000000 --- a/changelog.d/qwen-tp-batched-cohort-drafts.md +++ /dev/null @@ -1,3 +0,0 @@ -### Concurrent tensor-parallel requests draft together - -- When several speculative requests on a two-Mac tensor-parallel pair draft in the same round, their assistant steps now run as one batch: one head call and one pair of sealed exchanges per draft step for every row, instead of one per row. Six concurrent requests need about a third of the reductions they needed before, and every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen-tp-cohort-synchronization.md b/changelog.d/qwen-tp-cohort-synchronization.md deleted file mode 100644 index 718e459b0b..0000000000 --- a/changelog.d/qwen-tp-cohort-synchronization.md +++ /dev/null @@ -1,3 +0,0 @@ -### Concurrent tensor-parallel requests verify together - -- Concurrent speculative requests on a two-Mac tensor-parallel pair now stay in one verify cohort. A request that still has up to one round of accepted tokens waiting joins the next round from its own settled position instead of waiting for its queue to drain, so requests that started a step apart no longer take turns verifying alone. Every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen-tp-exact-batched-drafts.md b/changelog.d/qwen-tp-exact-batched-drafts.md deleted file mode 100644 index db5790ab94..0000000000 --- a/changelog.d/qwen-tp-exact-batched-drafts.md +++ /dev/null @@ -1,5 +0,0 @@ -### Concurrent tensor-parallel requests share each draft step's weight reads - -- On a two-Mac tensor-parallel pair, speculative drafts now use the same batch-invariant kernel as decoding. When several requests draft in the same round, every draft step after the first runs all of them through one assistant pass, and every head call serves all of them, so each weight is read once per step for the whole batch instead of once per request. With eight concurrent Qwen3.8 27B requests, a round's draft work on one Mac fell from about 38 to 24 ms. -- A request proposes the same tokens alone and in a batch of any size, and every request still produces exactly the tokens the model produces without speculation. Proposals can differ from the previous kernels at near-ties, so the share of accepted proposals can shift slightly; the output never does. -- Both Macs must use the same draft kernel or the pair refuses to load. `DARKBLOOM_QWEN_TP_MTP_EXACT_DRAFTS=0` (diagnostic only, never forwarded to an installed rank) keeps the previous kernels. Single-Mac speculative decoding is unchanged. diff --git a/changelog.d/qwen-tp-six-lane-batches.md b/changelog.d/qwen-tp-six-lane-batches.md deleted file mode 100644 index ebf886a234..0000000000 --- a/changelog.d/qwen-tp-six-lane-batches.md +++ /dev/null @@ -1,3 +0,0 @@ -### Six-request tensor-parallel batches - -- Automatic batching on a two-Mac tensor-parallel pair can now choose six concurrent requests, between four and eight, when eight do not fit. Pipeline batching keeps its widths of two, four and eight. diff --git a/changelog.d/qwen-tp-vector-tiles-measured.md b/changelog.d/qwen-tp-vector-tiles-measured.md deleted file mode 100644 index 5c94abcf3d..0000000000 --- a/changelog.d/qwen-tp-vector-tiles-measured.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen tensor-parallel verification keeps its measured weight-read tiles - -- Two-Mac tensor-parallel Qwen pairs verify concurrent requests with tiles of at most five vectors per weight read again (tiles of four past five), instead of whole-cohort tiles of eight or sixteen. On two M5 Ultra Macs serving Qwen3.8 27B, four concurrent requests reach about 90 tokens per second together instead of 73, with identical outputs. diff --git a/changelog.d/qwen-tp-widened-fast-fences.md b/changelog.d/qwen-tp-widened-fast-fences.md deleted file mode 100644 index 024b0eb0cd..0000000000 --- a/changelog.d/qwen-tp-widened-fast-fences.md +++ /dev/null @@ -1,3 +0,0 @@ -### Widened Qwen tensor-parallel owners keep fast fences - -Qwen tensor-parallel owners with more than one lane (Qwen3.8 27B, and the Qwen3.5 9B and both 35B A3B rows) keep MLX's fast fence waits instead of the slower event path. The stall that once stopped a widened pair right after a request finished is fixed at its cause: MLX kept a batched step on one GPU stream, and batched rows no longer convert their scales each step. diff --git a/changelog.d/qwen-tp-wider-automatic-batching.md b/changelog.d/qwen-tp-wider-automatic-batching.md deleted file mode 100644 index 300a8f1b49..0000000000 --- a/changelog.d/qwen-tp-wider-automatic-batching.md +++ /dev/null @@ -1,6 +0,0 @@ -### Wider automatic batching on two-Mac pairs - -- A two-Mac tensor-parallel owner now reserves much less memory per request, so automatic batching can widen past two concurrent requests when the Macs have room. A request no longer reserves its own full-history attention gather (decode and verification read pages in place, and one shared gather serves the single prompt frame a step runs). After a speculative round, a request keeps only its own recurrent rows instead of the whole round's. A long prompt's draft history moves into the assistant's cache as the prompt is read instead of waiting whole for the first draft. For Qwen3.8 27B with 32K-token prompts and 32K-token outputs, two, four and eight requests reserve 16.1, 25.7 and 45.5 GiB per Mac at an equal split, down from 21.4, 40.5 and 86.0 GiB. Qwen3.5 9B and the 35B A3B rows shrink the same way. -- Before replacing a running owner with a wider one, the preview now counts that owner's loaded weights on each Mac as free, because they are released before the wider owner loads. It does so only for a replacement that keeps the same split. The owner's unused request reservation is never counted, and the memory check after release is unchanged. A width that fails that check is not credited again for 10 minutes. -- Every width that automatic batching refuses is logged as one line, `cluster.batch_replan refused lanes=N`. It gives the phase (preview or after release), the reason, and each Mac's need, admissible memory, shortfall, weights and fit, in bytes. -- Every request still produces exactly the tokens it produces alone. diff --git a/changelog.d/qwen27-feature-preserving-modes.md b/changelog.d/qwen27-feature-preserving-modes.md deleted file mode 100644 index cb48e56b54..0000000000 --- a/changelog.d/qwen27-feature-preserving-modes.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 feature-preserving cluster modes - -Keep images, video and committed-token logprobs in the registered Qwen3.8 27B cluster route by admitting tensor parallel before unchanged speed ranking. Replan old pipeline setups instead of silently serving fewer features, retain native link/shape/memory gates, and require matching actual media READY and logprob support before creating the bridge. Other model and GLM mode policies remain unchanged. diff --git a/changelog.d/qwen27-media-response-format.md b/changelog.d/qwen27-media-response-format.md deleted file mode 100644 index e62632ca6d..0000000000 --- a/changelog.d/qwen27-media-response-format.md +++ /dev/null @@ -1,8 +0,0 @@ -### Qwen27 media response formats - -- Accept image/video `response_format` requests through the cluster's existing - Qwen27 media path, using the same JSON prompt preparation and nonstream - JSON/schema post-validation as standalone serving. -- Preserve forced-media-tool refusals and default processor policy. Streaming - remains prompt-guided; this does not add token-level grammar enforcement or - establish full-model media/schema accuracy. diff --git a/changelog.d/qwen27-tp-greedy-exchange.md b/changelog.d/qwen27-tp-greedy-exchange.md deleted file mode 100644 index 5528876c68..0000000000 --- a/changelog.d/qwen27-tp-greedy-exchange.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel greedy choices without full-vocabulary gathers - -Qwen27 tensor-parallel speculative decoding no longer moves complete vocabulary rows between the Macs for greedy work. Each draft step and each greedy verification column reduces a rank's vocabulary shard to its maximum and first index (plus a non-finite count when verifying), and one small exchange gives both Macs the same choice: the complete row's first maximum, with the lower index winning ties. Greedy verification also drops its separate choice broadcast. Sampled requests and logprobs still gather complete rows. diff --git a/changelog.d/qwen27-tp-media-preparation-refusal.md b/changelog.d/qwen27-tp-media-preparation-refusal.md deleted file mode 100644 index 3a677aacf0..0000000000 --- a/changelog.d/qwen27-tp-media-preparation-refusal.md +++ /dev/null @@ -1,12 +0,0 @@ -### Qwen 3.8 27B pair media: preparation on its own stream, refused alone - -- A Qwen 3.8 27B tensor-parallel pair no longer ends both workers when rank 0's - media preparation fails. Rank 0 prepares a request's image or video patches at - admission, on a CPU stream of its own while its executor waits, so another - thread's failed CPU work can no longer fail the preparation (after the main - merge, MLX overlaps evaluations across threads and hands a stream's stored - error to whichever caller synchronizes it next; the pair's media requests - failed this way after a dozen had passed). A preparation that does not - reproduce the leader's patches refuses that request alone with a retryable - error and its reason in the worker log, and the pair keeps serving. A vision - tower failure still ends the workers. diff --git a/changelog.d/qwen27-tp-mtp-depth3.md b/changelog.d/qwen27-tp-mtp-depth3.md deleted file mode 100644 index ec2c9e8443..0000000000 --- a/changelog.d/qwen27-tp-mtp-depth3.md +++ /dev/null @@ -1,3 +0,0 @@ -### Qwen27 tensor-parallel speculative depth 3 - -Automatic Qwen27 tensor-parallel setup now drafts three tokens a round instead of two. On the installed pair the assistant's first and second drafts were accepted 87% and 84% of the time, so a third proposal adds about 0.6 tokens a round for one more draft step; the verify window stays bound by one weight pass. Every emitted token is still the target's own choice. diff --git a/changelog.d/qwen27-tp-shared-verify-windows.md b/changelog.d/qwen27-tp-shared-verify-windows.md deleted file mode 100644 index 6cb72d2b1d..0000000000 --- a/changelog.d/qwen27-tp-shared-verify-windows.md +++ /dev/null @@ -1,3 +0,0 @@ -### Faster concurrent Qwen27 tensor-parallel verification - -Concurrent Qwen27 tensor-parallel requests now share each quantized projection's call when verifying their speculative windows, as long as the combined rows stay below MLX's vector-kernel limit for the device. Every request keeps the arithmetic it has alone. Draft proposals no longer need their own broadcast: both Macs read them from the same small exchange. A new `darkbloom-tp-mtp-profile-v1` worker line splits each round's time into draft, build, verify, gather, choose and settle. diff --git a/changelog.d/qwen27-tp-wide-verify-kernel.md b/changelog.d/qwen27-tp-wide-verify-kernel.md deleted file mode 100644 index cd1095bc62..0000000000 --- a/changelog.d/qwen27-tp-wide-verify-kernel.md +++ /dev/null @@ -1,3 +0,0 @@ -### Fewer weight reads for concurrent Qwen27 verification - -Concurrent Qwen27 tensor-parallel speculative windows now go through an exact four-bit projection kernel where it is faster than MLX's own calls: it reads each projection's weights once for up to eight verify rows (two four-column windows), where MLX's vector kernel reads them once for every five. On the M5 Max it keeps one output row per thread (up to 20% faster); on the M3 Ultra the row-parallel FP32 partials use two rows per thread (1.5-2.1x faster) and other projections keep MLX's calls. Each row keeps MLX's own `qmv_wide` reduction, so every request still gets byte-identical results to running alone; other GPU families keep MLX's calls. diff --git a/docs/developer/build.md b/docs/developer/build.md index 29da22cb9d..93efb015ee 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build The Provider And Landing -> Last updated: 2026-10-29 +> Last updated: 2026-10-31 Build the provider, its source-matched native resources, and the independent landing site from this repository. Backend, sidecar, console and admin builds @@ -177,23 +177,30 @@ importing its certificate. See [release qualification](test.md#sdk-27-release-qu ## The `dev` branch -The `dev` branch is master plus one commit. On it, a plain `swift build` is a -DevNet build: `DARKBLOOM_RELEASE_ENVIRONMENT` defaults to `dev`, so the -provider talks to `https://api.dev.darkbloom.dev` and nothing else. On master -the default is `prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a -production binary from the `dev` branch. +On the `dev` branch a plain `swift build` is a DevNet build: +`DARKBLOOM_RELEASE_ENVIRONMENT` defaults to `dev`, so the provider talks to +`https://api.dev.darkbloom.dev` and nothing else. On master the default is +`prod`. Set `DARKBLOOM_RELEASE_ENVIRONMENT=prod` to build a production binary +from the `dev` branch. Use the `dev` branch to run a provider from source against the DevNet -coordinator. Published dev providers do not come from this branch: a master -push that changes the provider publishes one through `release-swift.yml` +coordinator. A push to `dev` that changes the provider publishes the DevNet +release through `.github/workflows/release-dev-branch.yml` (see `docs/operations/provider-release.md`). Rules for the branch: -- Merge master into `dev` to update it. Never merge `dev` into master. -- Never tag a commit on `dev`. Tags publish production. -- Code changes go to master through a pull request, then reach `dev` by - merging master. Only the default-environment commit lives on `dev` alone. +- Changes reach `dev` through pull requests into `dev`, which land as merge + commits, and through merges of master into `dev`. +- `dev`'s changes reach master through pull requests into master. + [#1688](https://github.com/Layr-Labs/d-inference/pull/1688) merged a snapshot + branch of `dev` with a merge commit, for which an admin briefly allowed merge + commits on the squash-only master ruleset; 0.10.6's cluster changes reached + master as a squash-merged pull request of `dev` with master merged in. +- Master keeps one commit of its own, `e9babca4`, which sets plain builds back + to `prod`. A merge of master into `dev` reverts that commit on its sync + branch, so `dev` keeps its DevNet default. +- Never tag a commit on `dev`. Tags publish production, from master. `scripts/provider-release-cache.py` separates optimized and qualification Swift caches by compiler/SDK, architecture, absolute checkout/toolchain paths, diff --git a/docs/operations/provider-release.md b/docs/operations/provider-release.md index 191b53d3f4..1a6b517c7e 100644 --- a/docs/operations/provider-release.md +++ b/docs/operations/provider-release.md @@ -27,45 +27,135 @@ runs the resolve, build, qualification, signing, R2 staging and publication chain for one environment. To find the newest dev release, read `https://api.dev.darkbloom.dev/v1/releases/latest`. -`ProviderCore.version` is prepared as `0.10.5`, a patch release over `v0.10.4`. -`darkbloom sandbox` sets up, checks, pauses, resumes and removes the Darkbloom -Sandbox add-on from the provider CLI. GPT-OSS client stop sequences match only -the Harmony final message, which ends its reasoning-only empty answers, and Qwen -3.5 and 3.6 no longer loop to `max_tokens` when sampling is omitted. A dense Qwen -follow-up restores its checkpoint from just below the previous prompt end. SSD -checkpoint restores, eviction, maintenance, reads and donations are faster, -expired checkpoints no longer count as corrupt and cache sweeps no longer stall -lookups. The provider reconnects faster after a long session or a 1012 close, -keeps prompt-cache hits across batch promotion, drops response chunks processed -while disconnected and keeps a model download's completion. The MLX pins move to -their forks' `main`. See the [`v0.10.5` changelog entry](../../CHANGELOG.md) for the full -scope. - -Before tagging `v0.10.5`: +`ProviderCore.version` is prepared as `0.10.6`, a patch release over `v0.10.5` +and the first production release with two-Mac clusters. `darkbloom cluster` +sets up two Macs joined by one Thunderbolt 5 cable (macOS 26.2 or later, RDMA +over Thunderbolt) to serve one model together, GLM-5.3-Flash and Qwen3.8-27B in +tensor parallel, and `darkbloom cluster local` serves a pair without a +coordinator. Every release lane computes the build's +[cluster runtime facts](#cluster-runtime-facts), from which a coordinator with +darkbloom-platform#643 derives the build's cluster approvals, pair-serving +grants and public qualifications. A registered pair's cluster service is no +longer restarted by its own part's heartbeats (#1690), pair members register the +models their pair-serving grant admits (#1686), a single Qwen3.8-27B request in +tensor parallel decodes about 6% faster on two M5 Ultra (#1680) and model +downloads show one progress line (#1683). Single-Mac serving needs no +coordinator change and no provider-version floor, though three answers to +coordinator requests and the local API change. See the +[`v0.10.6` changelog entry](../../CHANGELOG.md) for the full scope. + +Before tagging `v0.10.6`: - Confirm that the tagged commit pins `libs/mlx` and the nested `mlx` to - `72dffa2d`, `libs/mlx-swift` to `c633d221` and `libs/mlx-swift-lm` to - `2beb401f`, all on their forks' `main`. The 0.10.2 hotfix branches are no - longer pinned; the NAX head-dim split fix they carried (`mlx` `31f550af`) is - in `72dffa2d`'s `jit_kernels.cpp`. -- The tag build's `metallib_hash` differs from v0.10.4's - `6ccc62966bb452b767fbd7261175b06c7653259a25f657524f1c1ef71f556d45`: twelve - Metal backend files change between the `mlx` pins, including - `kernels/fence.metal`. Record the new hash. Complete SSD checkpoints that 0.10.4 - wrote are not restored by 0.10.5, because their namespace binds the binary and - loaded-metallib hashes. + `72dffa2d` and `libs/mlx-swift` to `c633d221`, as v0.10.5 did, and + `libs/mlx-swift-lm` to `7933a0fa`, its fork's `main`. Only the SDK pin moves + (from `2beb401f`, through #1680 and #1684): SDK #373 changes + `AffineQuantizedVectors.swift` alone. +- The tag build's `metallib_hash` should equal v0.10.5's + `98bab9d77dc5078ad8dd8f1fd17e8f3581415193506e4791a3c4f1ebaab614be`: the MLX + core is unchanged, and the dev-branch release of this preparation's base, + `0.10.5-dev.branch.18` from `a0413a8a`, registered that hash on DevNet. A + different hash needs an explanation, such as a changed Metal toolchain. +- The tag is the first production run of the release steps that came with the + cluster: the build and signing of the [cluster helpers](#cluster-helpers) and + the cluster runtime facts. The dev-branch lane runs the same reusable + workflow; its run + [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) + passed both, and DevNet's coordinator accepted its block. That proves neither + the derived approvals nor pairing; step 5 below checks both in production. +- Before step 3 below, check that the production catalog lists `glm-5.3-flash` + and `EigenLabs/Qwen3.8-27B-4bit-mtp`, because the facts step leaves out a + model the environment's catalog lacks. Check that the coordinator's catalog + has room within its bounds of 64 approvals, 64 pair-serving grants and 256 + parity qualifications, which newer releases fill first, each release whole: + 0.10.6 adds at most 24 approvals and 24 grants (`s1` and `s2` for each of at + most 12 models) and 8 parity qualifications (4 each for GLM-5.3-Flash and + Qwen3.8-27B). See [cluster runtime facts](#cluster-runtime-facts). +- The tagged commit is this preparation's squash commit on `master`, and + `changelog.d/` must hold only its `README.md` there. On the `master` checkout + you tag: + + ```bash + git log -1 --format=%s # must print: Prepare provider 0.10.6 (#) + make changelog-check # must print: changelog: 0 valid fragment(s) + ``` + + A fragment at the tag reached `master` without an entry in this release's + changelog. Roll out in this order; each step is a separate approval: -1. Tag `v0.10.5` ([step 4](#4-tag-and-push-production-source)). No coordinator - deployment is needed first, and no provider-version floor applies. -2. The platform snapshots its provider contracts from the tagged commit +1. No DevNet proof: this release goes to production without one. DevNet's + coordinator accepted the block of `0.10.5-dev.branch.18` but derived no + approvals, so production is the first coordinator to derive them, and step 5 + checks them. +2. Production platform: deploy a `darkbloom-platform` coordinator with + [darkbloom-platform#643](https://github.com/Layr-Labs/darkbloom-platform/pull/643). + #643's code reaches the platform's `master` only with its `dev` to `master` + merge; its twin, + [darkbloom-platform#644](https://github.com/Layr-Labs/darkbloom-platform/pull/644), + carries only migration 58 (the `releases.cluster_runtime` column), which no + code on `master` reads. Production runs one combined coordinator, not + DevNet's split Provider Edge and Conductor. Apply migration 58 and set, in + the same deploy: + - `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` (approvals + derived from releases, the only approval source: + `EIGENINFERENCE_CLUSTER_PAIRS`, the operator's approval table, stays + unset); + - `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` (the + production coordinator listens on plain HTTP behind Caddy on the same + host, which reaches it over loopback, so without this setting no member + connection attaches to pair control); + - `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` (public traffic for qualified + clusters). + + App Attest serving must be on for every account: + `EIGENINFERENCE_APP_ATTEST_SERVING=true`, + `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT=production` and + `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT=100`. A member holds either the + legacy MDM path or an App Attest serving authorization, so a member on + macOS 27 without MDM pairs only through App Attest. +3. Confirm from production's `/health` `build_commit` that it runs the platform + revision of step 2. Check the catalog as above, and re-run the release's + facts step read-only against it: + `scripts/provider-cluster-runtime-facts.sh darkbloom prod `, + with an unsigned app staged from this preparation's source the way the build + job stages it (`scripts/provider-signing-validation.py stage`). It reads the + catalog and the CDN, sends nothing, and must exit 0: a catalog row that the + worker cannot describe stops the release after signing once the variable is + set. Then set the repository variable `PROD_CLUSTER_RUNTIME_ENABLED=true`. + Never before step 2: a coordinator without #643 refuses a registration that + carries `cluster_runtime`, and the release then fails after signing. Set it + before the tag: a release registered without the block never gains one, + because a re-registration must repeat the stored block (409 + `cluster_runtime_conflict`). +4. Merge into `master`, each squash-merged after its approval: first the + two-Mac clustering pull request, then this preparation. The clustering pull + request carries #1690 and #1692 from `dev`, with `master` merged in so plain + builds keep `master`'s `prod` default, and the fixes found while preparing + this release, such as the release facts fix (a catalog model ID that the + worker describes as another registered model is left out). After its squash, + restack this preparation with `scripts/restack-after-squash.py` + ([pull-request stacks](../developer/pull-requests.md)). Let SDK 27 release + preparation pass on `master`. This step does not depend on steps 1 to 3 and + may come first. +5. Tag `v0.10.6` on this preparation's squash commit once the checks above pass + ([step 4](#4-tag-and-push-production-source)). After registration, check the + coordinator log for `release cluster approvals omitted` and + `GET /v1/cluster/approvals` for the derived `release/0.10.6//s<1|2>` + approvals. Then a production pair, the owner's two Macs with App Attest, + must form a session under one of them. Record the run and the session. +6. The platform snapshots its provider contracts from the tagged commit (`python3 scripts/provider-contracts.py snapshot `), sets - `LatestProviderVersion` to `0.10.5` in the coordinator's `server.go` in the + `LatestProviderVersion` to `0.10.6` in the coordinator's `server.go` in the same change and adds the revision row to its provider-contract reference. Of - the 34 snapshotted inputs, pinned at v0.10.4's `8effff7f`, only - `contracts/provider/ProviderCore.swift` should change. `LatestProviderVersion` - is a fallback and does not gate publication. + the 34 snapshotted inputs, only `contracts/provider/ProviderCore.swift` + changes from v0.10.5. `LatestProviderVersion` is a fallback and does not gate + publication. + +Without steps 2 and 3 the tag still publishes with an unchanged registration, +but 0.10.6 then never derives cluster approvals, and a production pair serves +only on its leading Mac's local API. 0.10.2's remaining enablement steps do not wait for this tag and still apply; each is a separate approval: @@ -79,24 +169,35 @@ each is a separate approval: tuple to the allowlist and list `logprobs` in Super's catalog row. Catalog changes, allowlist changes and model registration are separate -approvals. This preparation does not tag, register, upload, deploy or enable -anything. +approvals. This preparation tags, deploys and enables nothing; merging it into +`master` publishes nothing, because the staging lane runs only while +`STAGING_ENABLED` is `true`. -Platform evidence, inspected on 2026-10-30 (recheck before tagging): +Platform evidence, inspected on 2026-10-31 (recheck before tagging): | Claim | Source | |---|---| -| The provider-contract snapshot pins d-inference `8effff7f` (v0.10.4), and its 34 inputs equal this preparation's except `ProviderCore.swift` | [`contracts/provider/manifest.json` at `cb31f6b4`](https://github.com/Layr-Labs/darkbloom-platform/blob/cb31f6b44af25500eab72fa0adb01eb6c69864d6/contracts/provider/manifest.json) (`source_revision`) | +| Platform `master` (`2847f27d`) pins the provider contracts at d-inference `8effff7f` (v0.10.4) and keeps `LatestProviderVersion` at `0.10.4`; darkbloom-platform#639 (open) pins v0.10.5's `d3bbcd06`. The 34 inputs equal this preparation's except `ProviderCore.swift` | [`contracts/provider/manifest.json` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/contracts/provider/manifest.json) and [at #639's `422ca1d4`](https://github.com/Layr-Labs/darkbloom-platform/blob/422ca1d428849c775daa950691a185154f117c18/contracts/provider/manifest.json) (`source_revision`) | | `LatestProviderVersion` must equal the snapshotted `ProviderCore.version` | [`provider_version_sync_test.go` at `5ba280d8`](https://github.com/Layr-Labs/darkbloom-platform/blob/5ba280d89aa5e9bd4fbf05e0dfa848059cd3b585/coordinator/tests/api/provider_version_sync_test.go) (`TestLatestProviderVersionMatchesProviderCore`) | - -`v0.10.4` was [published on 2026-10-28](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.4) +| #643 is merged into platform `dev` (`df61dd6f`), not `master`; #644 (open) carries only its migration to `master`. Only `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true` derives entries from releases, and public routing needs an approval source | [`cluster_pair_config.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/api/cluster_pair_config.go) (`ClusterPairConfig`) | +| Migration 58 adds `releases.cluster_runtime`, and a re-registration must repeat the stored block (409 `cluster_runtime_conflict`) | [`00058_release_cluster_runtime.sql` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/schema/migrations/00058_release_cluster_runtime.sql); [`releases.go` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/store/postgres/releases.go) (`SetRelease`) | +| A coordinator without #643 refuses a registration body that carries `cluster_runtime` | [`release_handlers.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/api/releases/release_handlers.go) (`DisallowUnknownFields`) | +| Of the platform's deploy configuration, only DevNet's overlay sets `EIGENINFERENCE_CLUSTER_PAIRS`, `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES` and `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING`, and it also sets `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1` | [`env-overrides` (DevNet) at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/deploy/gcp/dev/env-overrides) | +| A member connection attaches to pair control only after its own TLS handshake or through a listed TLS proxy. The production coordinator listens on plain HTTP behind Caddy, and in the split deployment only the trusted-proxy path attaches a member | [`configuration.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/configuration.md) ("Trusted TLS proxy trade-off") | +| A pair member holds the legacy MDM path or an App Attest serving authorization; App Attest serving reads `EIGENINFERENCE_APP_ATTEST_SERVING`, `EIGENINFERENCE_APP_ATTEST_ENVIRONMENT` and `EIGENINFERENCE_APP_ATTEST_ROLLOUT_PERCENT` | [`cluster-control-protocol.md` at `df61dd6f`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/docs/reference/cluster-control-protocol.md) ("Member trust"); [`config.go` at `2847f27d`](https://github.com/Layr-Labs/darkbloom-platform/blob/2847f27dda8e4caf9e2441d554067f42a88c9e1f/coordinator/appattest/service/config.go) (`ConfigFromEnvironment`) | +| DevNet runs `df61dd6f` and accepted the block of `0.10.5-dev.branch.18` (registered 04:33Z), yet its `GET /v1/cluster/approvals` listed only 26 operator approvals, with no `release/` entry, at 04:44Z, 04:57Z, 05:04Z and 05:09Z | DevNet `/health` and `/v1/cluster/approvals`; run [41167361754](https://github.com/Layr-Labs/d-inference/actions/runs/41167361754) (`CLUSTER_RUNTIME_SEND: true`) | + +The production coordinator was not inspected for this preparation; step 3 +checks its `/health`. + +`v0.10.5` was [published on 2026-10-30](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.5) +from `d3bbcd064ea290fbeb500e5c51c7870e3695741c`, `v0.10.4` was +[published on 2026-10-28](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.4) from `8effff7f7067fec70b2e3b58de0a4ba47ea3986c`, `v0.10.3` was [published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.3) from `3ddd11ce8d7204cc5aadefd2050376c583da4ff8`, `v0.10.2` was [published on 2026-10-26](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.2) -from `f9d1af3d0d3e1838974a5cfdff0a08142977b45e`, `v0.10.1` was -[published on 2026-10-24](https://github.com/Layr-Labs/d-inference/releases/tag/v0.10.1) -from `9034a5a0f3526dec83ab6384e5264db595cb7549`. Publication does not establish +from `f9d1af3d0d3e1838974a5cfdff0a08142977b45e`. Publication does not establish that every optional feature or environment has been activated. ## Prerequisites @@ -507,7 +608,7 @@ requirement of `scripts/install.sh` and the self-updater's | Item | Dev-branch lane | |---|---| | Version | `X.Y.Z-dev.branch.`, stamped by `scripts/resolve-provider-release.sh` and accepted by `scripts/check-release-version.sh` | -| Source gate | Job `resolve-env` runs master's copy of `scripts/provider-release-resume.py verify-source`. The gate must accept a `refs/heads/dev` push for environment `dev`; until master carries that change, the lane fails at the gate. | +| Source gate | Job `resolve-env` runs master's copy of `scripts/provider-release-resume.py verify-source`, which accepts a `refs/heads/dev` push for environment `dev` only. | | Signing and notarization secrets | `APPLE_CERTIFICATE_P12`, `APPLE_CERTIFICATE_PASSWORD`, `PROVISIONING_PROFILE_BASE64`, `APPLE_ID`, `APPLE_APP_PASSWORD`, read only in job `build-and-release` | | Publication secrets | `DEV_R2_*`, `DEV_COORDINATOR_URL`, `DEV_RELEASE_KEY` | | GitHub environment | None. All of these are repository secrets. | @@ -524,11 +625,11 @@ re-run failed jobs only after the signing job passed, and push a new commit to rebuild. The `release-dev-branch` group does not cancel a running run, but a newer dev push cancels a run that is still pending in the group. -Review is not enforced on `dev` today. Its rules are required signatures and the -"Darkbloom PR access control" ruleset, which lets only the accounts on that -ruleset's bypass list create or update a ref. Because a dev push gets the -Developer ID signature, `dev` needs a pull_request rule before the lane runs. A -repository administrator adds that rule. +Because a dev push gets the Developer ID signature, pull requests into `dev` +need one approving review and land as merge commits (ruleset "Dev pull +requests"). `dev` also requires signed commits, and the "Darkbloom PR access +control" ruleset lets only the accounts on its bypass list create or update a +ref. The dev coordinator can still hold `X.Y.Z-dev.` releases from the master dev lane; `0.10.4-dev.224` is the latest dev release on 2026-10-28. @@ -747,10 +848,12 @@ again with [Resume Signing From A Retained Unsigned Build](#resume-signing-from-a-retained-unsigned-build). Turn a variable on only after the coordinator of that environment accepts the -block (`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES`, darkbloom-platform); -a coordinator that does not accept it yet must never receive it. Public cluster +block (darkbloom-platform#643); a coordinator that does not accept it yet must +never receive it. It derives approvals from the block only with +`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`. Public cluster routing also needs `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` on that -coordinator. +coordinator, and a coordinator behind a TLS-terminating proxy attaches members +only through `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES`. Before a release with the block registers, make sure the coordinator's catalog has room. It holds at most 64 approvals (the operator's per-build and per-model @@ -779,9 +882,34 @@ Rollout order: 3. This change merges to `dev`. The next dev-branch release registers with the block; check the coordinator log for an omitted release. A pair registers by itself after it updates. -4. Both repositories go `dev` to `master`. The production coordinator deploys - with its switch on, a person checks its catalog's room and sets - `PROD_CLUSTER_RUNTIME_ENABLED=true`, and the release tag follows. +4. Production follows in this order, without waiting for a DevNet proof; each + step is a separate approval: + 1. The production coordinator deploys with darkbloom-platform#643 and + migration 58, and with `EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`, + `EIGENINFERENCE_CLUSTER_PAIR_TRUSTED_TLS_PROXIES=127.0.0.1,::1` and + `EIGENINFERENCE_CLUSTER_PUBLIC_ROUTING=true` in its settings. + `EIGENINFERENCE_CLUSTER_PAIRS` stays unset, so approvals derived from + releases are the only source. Its `/health` `build_commit` must be that + revision. + 2. A person checks the production catalog's room and sets + `PROD_CLUSTER_RUNTIME_ENABLED=true`. + 3. The release tag follows. + 4. After the registration, `GET /v1/cluster/approvals` lists the release's + derived approvals, `release/0.10.6//s<1|2>` for 0.10.6, and the + coordinator log has no `release cluster approvals omitted` for it. The + pair-serving grants (`/grant`) and parity qualifications + (`/q`) derived beside them are not on that list: a pair + that forms under a derived approval shows its qualification as + `qualification_id` in its owner's + [`GET /v1/me/cluster-pairs`](https://github.com/Layr-Labs/darkbloom-platform/blob/master/docs/reference/api-contracts.md#owner-cluster-views). + + Keep the order. A coordinator without #643 refuses a registration that + carries the block, so the release fails after signing. A version whose + first registration carries no block never gains one: a re-registration must + repeat the stored block, and the coordinator answers any other with 409 + `cluster_runtime_conflict`. So if 0.10.6 registers while + `PROD_CLUSTER_RUNTIME_ENABLED` is not `true`, it derives no approvals at + all, and only a later version can carry the block. To compute the facts of an installed or downloaded app by hand, give the models explicitly. Run that app's own CLI, so the public declaration and the records diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 28ca6d7b72..d8688b78b8 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -138,15 +138,23 @@ clusters. A coordinator that refuses this pair is not treated this way; the start fails and says why. To serve without any coordinator, use [`darkbloom cluster local`](#serving-locally-only). -## Registered with the coordinator as a cluster member (DevNet) - -When the coordinator's operator approval file holds a cluster approval for this -pair's model (DevNet only), the pair registers with the coordinator by itself. -Nothing is typed and no file is copied. Production and staging serve no -approvals, and the pair serves as described above. The pair -serves its owner's own requests, and public requests too once the coordinator's -operator has turned public cluster routing on and qualified the pair's model and -split ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). +## Registered with the coordinator as a cluster member + +When the coordinator serves a cluster approval for this pair's model, the pair +registers with the coordinator by itself. Nothing is typed and no file is +copied. DevNet's coordinator serves the approvals its operator posts. +Production's derives them from each release's +[cluster runtime facts](../operations/provider-release.md#cluster-runtime-facts), +from 0.10.6 on, once it runs darkbloom-platform#643 with +`EIGENINFERENCE_CLUSTER_PAIR_APPROVALS_FROM_RELEASES=true`; such an approval +names one release's build, so a pair registers with it only on that release. +Before that deploy production serves no approvals (`GET /v1/cluster/approvals` +answers 404), staging serves none, and the pair serves as described above. The +pair serves its owner's own requests, and public requests too once the +coordinator has public cluster routing on and a parity qualification for the +pair's model and split; a release's cluster runtime facts carry them for +GLM-5.3-Flash and Qwen3.8-27B +([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair)). A tensor-parallel pair registers like a pipeline one; its plan names no cut. 1. Run `darkbloom cluster` and choose a model, as in [the steps](#the-steps-once). @@ -167,7 +175,9 @@ A tensor-parallel pair registers like a pipeline one; its plan names no cut. There is no local API in this mode. `darkbloom cluster` status shows the same line. -An approval ends at its `not_after`, which the operator sets. The +An approval ends at its `not_after`, which the operator sets; one derived from +a release ends 90 days after that release registered +([`releaseApprovalExpiry`](https://github.com/Layr-Labs/darkbloom-platform/blob/df61dd6f93714b4458d0eef3125c377087c08b52/coordinator/registry/cluster_release_approvals.go)). The leader asks again at each start of its cluster service, after each Darkbloom update and every minute while the pair is registered, and takes a later matching approval when the saved one ends within a day. A Mac whose approval @@ -199,7 +209,7 @@ What `darkbloom cluster` status says in each mode: | Approval no longer listed | The API line, then `The coordinator no longer lists cluster approval : the pair serves on the leader's local API until it lists a matching one again.` | | Parts kept ending | The API line, then `The coordinator-paired parts ended 3 times in a row right after starting with cluster approval : the pair serves on the leader's local API for 60 minutes, then it is offered again with it, or sooner with a later one the coordinator lists.` | | Approval ended | The API line, then one line that says the cluster approval `` expired and the pair serves on the leader's local API | -| No approval (production, staging, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | +| No approval (staging, production before its coordinator derives approvals from releases, no matching entry) | The API line, then (only after a refusal) `Not offered for pairing: .` | Approval sources, checks and saved fields: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f3cc785efd..0aa1e29379 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1093,7 +1093,7 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Step | Rule | Source | |---|---|---| -| Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: production, staging) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | +| Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: staging, and production until its coordinator derives approvals from releases) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | | Match | The entry whose `model` is the setup's `publicModelID`, whose `schedule` is its prefill schedule (`1` serial, `2` one-chunk lookahead), and that is still current. A model approval matches when its `artifact_sha256` is the saved setup's `capability.artifactSHA256`; no runtime facts are computed for it. A build-pinned entry matches when its eight digests all equal this Mac's own cluster runtime facts (computed at most once per check from the helpers beside the setup's worker and the setup's model folder). Latest `not_after` first, across both shapes. An entry for another build or another copy of the model does not match | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift` (`select`) | | Check | On each Mac, against its own files: every digest of a build-pinned entry (`ClusterApprovalAttachment.mismatches`), or the artifact of a model approval (refusal: "the approval's artifact_sha256 differs from this Mac's setup"); the member's own start refusals (`requireLocalRankGranted`); the roster of this Mac's pairing (S17); `validate` below | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift` (`attachment`) | | Save | Both parts stop. The leader checks the entry, sends it to the other Mac over the cable (service command `approval`), and saves it only after the other Mac checked and saved it. A refusal on either Mac saves it on neither. Both parts then start as cluster members | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift` (`run`, `receive`) | diff --git a/provider-swift/Sources/ProviderCore/ProviderCore.swift b/provider-swift/Sources/ProviderCore/ProviderCore.swift index 523fde57ff..37319a171c 100644 --- a/provider-swift/Sources/ProviderCore/ProviderCore.swift +++ b/provider-swift/Sources/ProviderCore/ProviderCore.swift @@ -5,5 +5,5 @@ public enum ProviderCore { /// Release identity consumed by CLI output, registration and packaging. /// scripts/check-release-version.sh verifies this provider-owned identity /// against the requested release tag and reported binary version. - public static let version = "0.10.5" + public static let version = "0.10.6" } From 66e144bfa65402d08522cf475209a89de62b3e08 Mon Sep 17 00:00:00 2001 From: David Tai Date: Sat, 31 Oct 2026 11:01:29 -0500 Subject: [PATCH 4/6] Remove the changelog fragments that the 0.10.6 render already holds PR 1695 rendered these eight fragments into CHANGELOG.md v0.10.6 and deleted them. Its merge of the PR 1694 squash added them again, so master has them. Each line of each fragment is in the v0.10.6 section, and the next render would add them a second time. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-pair-coordinator-ends-not-failing.md | 5 ----- changelog.d/cluster-pair-update-by-hand.md | 3 --- changelog.d/cluster-qwen-pair-public-without-assistant.md | 7 ------- changelog.d/cluster-release-runtime-facts.md | 7 ------- .../cluster-runtime-facts-another-models-catalog-id.md | 4 ---- changelog.d/cluster-service-part-heartbeat.md | 3 --- changelog.d/kv-reslice-slot-floors.md | 4 ---- changelog.d/min-p-single-mac.md | 3 --- 8 files changed, 36 deletions(-) delete mode 100644 changelog.d/cluster-pair-coordinator-ends-not-failing.md delete mode 100644 changelog.d/cluster-pair-update-by-hand.md delete mode 100644 changelog.d/cluster-qwen-pair-public-without-assistant.md delete mode 100644 changelog.d/cluster-release-runtime-facts.md delete mode 100644 changelog.d/cluster-runtime-facts-another-models-catalog-id.md delete mode 100644 changelog.d/cluster-service-part-heartbeat.md delete mode 100644 changelog.d/kv-reslice-slot-floors.md delete mode 100644 changelog.d/min-p-single-mac.md diff --git a/changelog.d/cluster-pair-coordinator-ends-not-failing.md b/changelog.d/cluster-pair-coordinator-ends-not-failing.md deleted file mode 100644 index 85f55ed611..0000000000 --- a/changelog.d/cluster-pair-coordinator-ends-not-failing.md +++ /dev/null @@ -1,5 +0,0 @@ -### A coordinator deploy no longer takes a cluster pair off public traffic - -- A pair registered with the coordinator serves on the leader's local API instead when its coordinator-paired parts end three times in a row right after starting. A part that ended because the coordinator did not accept its registration within the 10-second window counted too, although the coordinator decided that end: it happens during a coordinator deploy, right after a restart, or while the coordinator is slow. Such an end no longer counts. Ends with a local cause, such as a changed input or a crash, still count. -- This complements a coordinator that ends each pair session before it shuts down, which makes a deploy's ends cleaner: the provider rule still covers coordinators without that change, coordinator crashes and slow registrations. -- A pair set aside this way is offered to the coordinator again with the same approval an hour later, or at once with a later approval. Before, only a later approval, the approval's end or a Darkbloom update brought it back, so it could serve only the leader's local API for the rest of the release. diff --git a/changelog.d/cluster-pair-update-by-hand.md b/changelog.d/cluster-pair-update-by-hand.md deleted file mode 100644 index e4760b3177..0000000000 --- a/changelog.d/cluster-pair-update-by-hand.md +++ /dev/null @@ -1,3 +0,0 @@ -### Pair Macs set up with `darkbloom cluster` do not update themselves yet - -- Darkbloom on a Mac set up with `darkbloom cluster` does not update itself yet. To update a pair, run `darkbloom update` on both Macs, then log out and back in, so that the cluster service runs the new release. If `darkbloom cluster` status then says that Qwen's speculative assistant is not offered for public traffic, press `m` once in `darkbloom cluster` to plan the model again. diff --git a/changelog.d/cluster-qwen-pair-public-without-assistant.md b/changelog.d/cluster-qwen-pair-public-without-assistant.md deleted file mode 100644 index 8d98f3fa68..0000000000 --- a/changelog.d/cluster-qwen-pair-public-without-assistant.md +++ /dev/null @@ -1,7 +0,0 @@ -### Qwen3.8 27B pairs register with the coordinator by default - -- A Qwen3.8 27B pair set up with `darkbloom cluster` now registers with the coordinator and can serve public traffic. With the default `[backend] mtp_mode = "auto"`, the setup used to carry the model's embedded speculative assistant, which a setup saved for coordinator pairing may not carry. The other Mac therefore refused every cluster approval ("A tensor assistant requires Qwen TP on a row with an inline head, serial prefill and a local cluster setup"), and the pair served on the leader's local API only, although the setup said it was qualified for public traffic. -- The assistant's speculative decoding has no parity qualification, so it stays on local clusters. Under `auto`, a cluster served through Darkbloom is planned without it, as are the re-plans after an update or a memory refusal. `darkbloom cluster local` keeps it. The cost is speed: on two M5 Ultras, one request decodes at about 40 tokens/s without the assistant and about 93 tokens/s with it. -- `mtp_mode = "on"` keeps the assistant in either case. A cluster served through Darkbloom is then not offered to the coordinator, and the setup says so in its public-traffic line instead of claiming qualification. -- The leader now checks a coordinator's approval with every rule the save applies, the assistant rule included, before it stops either Mac's part or sends anything over the cable. The pair is not offered, with the reason in one line: `Not offered for pairing: this Mac's check refused it: Qwen's speculative assistant serves local clusters only …`. -- Public speculative decoding for Qwen pairs needs qualification evidence of its own and is a follow-up. diff --git a/changelog.d/cluster-release-runtime-facts.md b/changelog.d/cluster-release-runtime-facts.md deleted file mode 100644 index f61e8f7068..0000000000 --- a/changelog.d/cluster-release-runtime-facts.md +++ /dev/null @@ -1,7 +0,0 @@ -### Releases carry their cluster runtime facts - -- Every release lane (dev branch, staging, prod) now computes the cluster runtime facts of its final signed app with that app's own CLI and worker: the digests of the cluster worker, placement tool, Metal library and paged-attention source, and for each model the build qualifies on a cluster and the environment's catalog has, the digests of its capability and its pair-serving grant. The job summary and a run artifact show them in every release. -- Each model's pair-serving grant lets a coordinator form its two-Mac pairs: a pair member reports only hardware capabilities, so without a grant no pair of GLM-5.3-Flash or Qwen3.8-27B forms. A declared public model's grant names its declared mode families; any other model's is the grant of the build's own qualification records, or none. -- GLM-5.3-Flash and Qwen3.8-27B are declared for public cluster traffic in pipeline and tensor parallel (owner decisions, 2026-10-31): their entries carry parity qualifications from which a coordinator derives their public qualifications, and it applies them to each declared mode family on any Apple silicon pair, with sampling and tools, and in tensor parallel images and video as the environment's catalog lists them. The qualifications name the evidence placement (two Apple M5 Ultras; a pipeline cut at half the model's layers), not a limit; no pipeline ran on two M5 Ultras and GLM-5.3-Flash has no tensor-parallel cross-cable record, so both rest on the owner's decision and the DevNet serving results. GLM-5.3-Flash runs the serial prefill schedule only, so its schedule 2 entries are inert. Every other model's clusters serve their owner only. The setup says a declared model is qualified for public traffic in pipeline and tensor parallel. -- The release registration carries the facts as `cluster_runtime` only when that environment's repository variable (`DEV_CLUSTER_RUNTIME_ENABLED`, `STAGING_CLUSTER_RUNTIME_ENABLED`, `PROD_CLUSTER_RUNTIME_ENABLED`) is `true`; a coordinator that accepts the block then approves the build's two-Mac clusters automatically. Unset, the registration is unchanged and a failure to compute the facts only warns. -- `darkbloom cluster runtime-facts` (hidden) prints schema `darkbloom_cluster_runtime_v2`: the same digests as before plus each model's `pair_serving_grant` and `parity_qualifications`. diff --git a/changelog.d/cluster-runtime-facts-another-models-catalog-id.md b/changelog.d/cluster-runtime-facts-another-models-catalog-id.md deleted file mode 100644 index 4d7163168a..0000000000 --- a/changelog.d/cluster-runtime-facts-another-models-catalog-id.md +++ /dev/null @@ -1,4 +0,0 @@ -### Cluster runtime facts leave out another model's catalog ID of a shared artifact - -- A release's cluster runtime facts no longer fail when one artifact is listed under the catalog IDs of two registered models. Production lists `gemma-4-26b` and `gemma-4-26b-8bit` for the same Gemma 4 26B artifact, and the build registers them as two runtime models that only the manifest tells apart. Only the 8-bit one is qualified on a pair, so `darkbloom cluster runtime-facts --release-candidates` stopped with "Qualified cluster models the release cannot describe: gemma-4-26b", and a production release with `PROD_CLUSTER_RUNTIME_ENABLED=true` would have stopped after signing. -- A catalog model ID whose candidates the build's worker describes only as another registered model is now that model's: it is left out of the facts and named on standard error (`note: left out, the catalog model ID of another registered model: …`). A catalog model ID of which the worker describes no candidate at all still fails the step. diff --git a/changelog.d/cluster-service-part-heartbeat.md b/changelog.d/cluster-service-part-heartbeat.md deleted file mode 100644 index 031989696d..0000000000 --- a/changelog.d/cluster-service-part-heartbeat.md +++ /dev/null @@ -1,3 +0,0 @@ -### The cluster service is no longer restarted while its pair is registered - -A pair registered with the coordinator could restart the cluster service of a Mac many times a day (about every 15 minutes on one DevNet leader: "heartbeat missing for 75 s while its process is alive"), and each restart dropped the pair for a short time. The Mac's part inherited the service's heartbeat file and wrote its own heartbeats into it, and the supervisor does not count a heartbeat from another process. The part now writes its heartbeats to a file of its own (`~/.darkbloom/cluster-setup/part-health.json`). diff --git a/changelog.d/kv-reslice-slot-floors.md b/changelog.d/kv-reslice-slot-floors.md deleted file mode 100644 index 228e32f74a..0000000000 --- a/changelog.d/kv-reslice-slot-floors.md +++ /dev/null @@ -1,4 +0,0 @@ -### Models load when every model's minimum KV fits - -- Loading a model beside others no longer fails with "would leave a model without its fixed request workspace, admission watermark and 1.0 GB minimum KV allowance" while the KV budget still covers every model's minimum. The split gave each model a share in proportion to its per-token KV cost alone. A resident model with a small per-token cost and a fixed per-request workspace, such as Nemotron 3.5 Lightning with its assistant on, could get less than its own minimum and block every further load. Now, when that would happen, each model gets its minimum first and the rest of the budget is split as before; the message now appears only when the minimums together exceed the budget. The model being loaded counts only the 1 GB base minimum until it is built, so Lightning itself can still fail to load, with no KV headroom, when it joins several high-rate models. -- A split that already gives every model its minimum is unchanged. Unloading a model, or a change to the activation reserve, no longer shrinks another model below its minimum. diff --git a/changelog.d/min-p-single-mac.md b/changelog.d/min-p-single-mac.md deleted file mode 100644 index 9e574f2b24..0000000000 --- a/changelog.d/min-p-single-mac.md +++ /dev/null @@ -1,3 +0,0 @@ -### A request's `min_p` now applies on one Mac too - -- A request's `min_p` now applies on one Mac too, as it already did on a cluster pair: tokens less likely than `min_p` times the most likely token are dropped before sampling (values above 1 count as 1). Requests without `min_p`, or with 0, are unchanged. From 2d4c604a438b5789754f942f32717839f6e9d9b8 Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:59:09 -0800 Subject: [PATCH 5/6] fix(cluster): GPT-OSS sliding pages follow the SDK's seven-value ring metadata GPTOSSPagedKVTests failed on master with 815 issues, all metaState comparisons. GPTOSSPagedKVCache stands in for the SDK caches, and its sliding metaState still wrote and required the five values the SDK ring wrote when the cache landed (pin 11df0f19). The pinned mlx-swift-lm (7933a0fa, since #1596) writes seven for RotatingKVCache(maxSize: window): keep, window, step, offset, write index, capacity origin and wrapped flag. Rows, masks, offsets and SDPA already matched the SDK. No serving path reads or restores this metadata. GPT-OSS pairs run only pipeline and compact decode, with no prompt-prefix snapshots, phase-split hand-offs, images or prompt-cache files, and the batch view carries none. Nothing user-visible changes. - GPTOSSPagedKVLayout keeps the SDK's wrapped flag: a one-token write that rotates sets it; a chunk or trim clears it. Row order is unchanged. - GPTOSSSlidingRing names the ring layout once, from a fresh RotatingKVCache(maxSize: window), and is nil for any other layout. - The setter restores only that exact layout for the cache's window, and only with the rows that ring holds: its first index rows, or the whole window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a kept prefix and another step, window or capacity origin. New test: slidingPagesRestoreOnlyTheSDKRingsMetadataForTheirRows takes the SDK ring's own metadata at five states, from short to wrapped back to its end, and checks each refusal. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 19 ++++++++-- docs/developer/test.md | 9 +++-- .../Generation/GPTOSSPagedKVCache.swift | 25 ++++++++----- .../GPTOSS/Generation/GPTOSSSlidingRing.swift | 37 +++++++++++++++++++ .../GPTOSS/Metadata/GPTOSSPagedKVLayout.swift | 13 ++++--- .../GPTOSSPagedKVTests.swift | 35 ++++++++++++++++++ 6 files changed, 116 insertions(+), 22 deletions(-) create mode 100644 libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c61afb03fe..9ab612aeb0 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -1,6 +1,6 @@ # Provider inference engine -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 How a chat-completion request is served inside the `darkbloom` provider process: one in-process engine (`mlx-swift-lm` @@ -4431,18 +4431,29 @@ synchronizes before dropping request caches on completion or failure. Copies share immutable old pages; a later write replaces the affected page handle. Sliding histories release old pages when they repack or enter the fixed ring. +Sliding pages also keep the ring's wrapped flag: a one-token write that rotates +sets it, and a chunk or trim clears it. Their `metaState` is the seven values the +pinned SDK writes for `RotatingKVCache(maxSize: window)` in the same state: keep, +window, step, offset, write index, capacity origin and wrapped flag +(`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, +and only with the rows that ring holds: its first `index` rows, or the whole +window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a +kept prefix, and any other step, window or capacity origin. GPT-OSS serving never +reads or restores this metadata. + `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's allocator bound separately, the gathered attention view, and partial-page copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. -CPU parity against the actual SDK caches covers ring/page/chunk boundaries and -sinks. Real two-Mac numerical acceptance, resource release and performance +CPU parity against the actual SDK caches covers ring/page/chunk boundaries, +metadata and sinks. Real two-Mac numerical acceptance, resource release and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` -(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, +(`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` +(`GPTOSSSlidingRing`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift`, `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSRequestStateBudget.swift`, and `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Resident/GPTOSSResidentAdmission.swift` (`loadAgreementFingerprint`). See [focused cache checks](../developer/test.md#gpt-oss-cluster-paged-kv-checks). diff --git a/docs/developer/test.md b/docs/developer/test.md index 0df04c2b0e..22eaf15aaa 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-10-31 +> Last updated: 2026-11-01 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1823,9 +1823,10 @@ swift test --package-path libs/darkbloom-cluster -c release \ --filter GPTOSSPagedKVTests ``` -`GPTOSSPagedKVTests` compares exact rows, masks, offsets and learned-sink SDPA -results with `StandardKVCache` and `RotatingKVCache`. It also checks demand -allocation, bounded sliding retention, copy/trim isolation and owner release. +`GPTOSSPagedKVTests` compares exact rows, masks, offsets, ring metadata and +learned-sink SDPA results with `StandardKVCache` and `RotatingKVCache`. It also +checks demand allocation, bounded sliding retention, copy/trim isolation, owner +release, and that sliding pages restore only the ring's own metadata. `GPTOSSStageChecks` checks each page's allocator overhead and sliding repack charge. These are CPU correctness checks, not native transport, MXFP4 model parity or performance evidence. Retain the existing two-Mac reference comparator diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift index 5758b05c08..f09a2678b7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift @@ -94,32 +94,39 @@ final class GPTOSSPagedKVCache: KVCache { get { gathered() } set { precondition(newValue.count == 2 && newValue[0].dim(2) > 0) - let previousOffset = offset - let previousIndex = layout.index + let previous = layout let window = maxSize pages = []; shape = nil; layout = .init(window: window) _ = update(keys: newValue[0], values: newValue[1]) if window != nil { // Like RotatingKVCache, metadata restoration supplies position // separately. Preserve the old position until it is restored. - layout.restore(count: newValue[0].dim(2), offset: max(previousOffset, newValue[0].dim(2)), - index: min(previousIndex, newValue[0].dim(2))) + layout.restore(count: newValue[0].dim(2), offset: max(previous.offset, newValue[0].dim(2)), + index: min(previous.index, newValue[0].dim(2)), wrapped: previous.wrapped) } } } + /// Sliding pages write and restore exactly the metadata the pinned SDK's + /// ring writes in the same state (`GPTOSSSlidingRing`). var metaState: [String] { get { - if let window = maxSize { return ["0", String(window), "256", String(offset), String(layout.index)] } - return [""] + guard let window = maxSize else { return [""] } + guard let metadata = GPTOSSSlidingRing.metadata(window: window, + at: .init(offset: offset, index: layout.index, wrapped: layout.wrapped)) else { + preconditionFailure("The pinned SDK writes another sliding-ring metadata layout") + } + return metadata } set { guard let window = maxSize else { precondition(newValue == [""]); return } - precondition(newValue.count == 5 && newValue[0] == "0" && Int(newValue[1]) == window - && Int(newValue[2]) == 256) - layout.restore(count: layout.count, offset: Int(newValue[3])!, index: Int(newValue[4])!) + guard let position = GPTOSSSlidingRing.position(of: newValue, window: window, rows: layout.count) else { + preconditionFailure("GPT-OSS sliding pages restore only the SDK ring's metadata for their rows") + } + layout.restore(count: layout.count, offset: position.offset, index: position.index, + wrapped: position.wrapped) } } diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift new file mode 100644 index 0000000000..4832c4be3f --- /dev/null +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift @@ -0,0 +1,37 @@ +import MLXLMCommon + +/// The metadata (`RotatingKVCache.metaState`) of GPT-OSS's sliding-window +/// ring, `RotatingKVCache(maxSize: window)` (`makeSlidingWindowKVCache`), in +/// the layout the pinned SDK writes: keep, window, step, offset, write index, +/// capacity origin and whether the ring has wrapped. Writes move only the +/// offset, the index and the flag. The ring's state holds its first `index` +/// rows, or the whole window once wrapped. +enum GPTOSSSlidingRing { + struct Position: Equatable { + let offset: Int, index: Int, wrapped: Bool + } + + private static let offsetField = 3, indexField = 4, wrappedField = 6 + + /// The metadata of a ring of `window` positions at `position`; nil when a + /// fresh ring writes another layout. + static func metadata(window: Int, at position: Position) -> [String]? { + var fields = RotatingKVCache(maxSize: window).metaState + guard fields.count == 7, fields[offsetField] == "0", fields[indexField] == "0", + fields[wrappedField] == "false" else { return nil } + fields[offsetField] = String(position.offset); fields[indexField] = String(position.index) + fields[wrappedField] = String(position.wrapped) + return fields + } + + /// The position `metadata` gives a ring of `window` positions holding + /// `rows` rows; nil unless that ring writes exactly this metadata. + static func position(of metadata: [String], window: Int, rows: Int) -> Position? { + guard metadata.count > wrappedField, let offset = Int(metadata[offsetField]), + let index = Int(metadata[indexField]), let wrapped = Bool(metadata[wrappedField]) else { return nil } + let position = Position(offset: offset, index: index, wrapped: wrapped) + guard metadata == Self.metadata(window: window, at: position), offset >= rows, + wrapped ? rows == window && index >= 0 && index <= rows : index == rows else { return nil } + return position + } +} diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift index 85968beff6..c514e925e7 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Metadata/GPTOSSPagedKVLayout.swift @@ -10,6 +10,9 @@ struct GPTOSSPagedKVLayout: Equatable { private(set) var offset = 0 private(set) var count = 0 private(set) var index = 0 + /// RotatingKVCache's wrapped flag: a one-token write that rotates sets it; + /// a chunk or a trim clears it. + private(set) var wrapped = false struct Update: Equatable { /// Nil keeps the existing pages. Otherwise these old physical rows @@ -45,7 +48,7 @@ struct GPTOSSPagedKVLayout: Equatable { return kept.isEmpty ? nil : kept } let kept = ranges.reduce(0) { $0 + $1.count } - count = kept + n; index = count + count = kept + n; index = count; wrapped = false return .init(retained: ranges, writeOffset: kept, count: count) } var retained: [Range]? @@ -53,7 +56,7 @@ struct GPTOSSPagedKVLayout: Equatable { retained = [(count - window).. Int { guard isTrimmable else { return 0 } let removed = min(offset, max(0, n)) - offset -= removed; count = offset; index = offset + offset -= removed; count = offset; index = offset; wrapped = false return removed } - mutating func restore(count: Int, offset: Int, index: Int) { + mutating func restore(count: Int, offset: Int, index: Int, wrapped: Bool) { precondition(count >= 0 && offset >= count && index >= 0 && index <= count) - self.count = count; self.offset = offset; self.index = index + self.count = count; self.offset = offset; self.index = index; self.wrapped = wrapped } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift index 5d5d7a9ba2..5bac3e4a08 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift @@ -129,6 +129,41 @@ struct GPTOSSPagedKVTests { } } + @Test func slidingPagesRestoreOnlyTheSDKRingsMetadataForTheirRows() { + Device.withDefaultDevice(.cpu) { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + var checked = 0 + // Short, chunked past the window, wrapped, wrapped back to its end, chunked again. + for (step, count) in ([3, 1, 512] + Array(repeating: 1, count: 128) + [2]).enumerated() { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + guard [0, 2, 3, 130, 131].contains(step) else { continue } + let metadata = ring.metaState, held = ring.state[0].dim(2) + guard let position = GPTOSSSlidingRing.position(of: metadata, window: 128, rows: held) else { + Issue.record("The SDK ring's own metadata \(metadata) was refused"); continue + } + checked += 1 + #expect(GPTOSSSlidingRing.metadata(window: 128, at: position) == metadata) + #expect(GPTOSSSlidingRing.position(of: metadata, window: 128, rows: held - 1) == nil) + #expect(GPTOSSSlidingRing.position(of: metadata, window: 64, rows: held) == nil) + func replacing(_ field: Int, _ value: String) -> [String] { + var fields = metadata; fields[field] = value; return fields + } + // Legacy, rewind reserve, kept prefix, other step, requested origin, non-canonical offset. + for refused in [Array(metadata.prefix(5)), metadata + ["2"], replacing(0, "1"), replacing(2, "64"), + replacing(5, "requested"), replacing(3, "+\(position.offset)")] { + #expect(GPTOSSSlidingRing.position(of: refused, window: 128, rows: held) == nil) + } + // A flipped flag claims other rows, except at a full window's end. + if position.index != held || held != 128 { + #expect(GPTOSSSlidingRing.position(of: replacing(6, String(!position.wrapped)), + window: 128, rows: held) == nil) + } + } + #expect(checked == 5) + } + } + @Test func slidingPagesStayBoundedAndRequestRetirementDropsEveryOwner() { Device.withDefaultDevice(.cpu) { weak var released: GPTOSSPagedKVCache? From 6df66892ef1c602d0378fcd97256fab76cd72bfa Mon Sep 17 00:00:00 2001 From: jonathan308 <5055076+jonathan308@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:42:09 -0800 Subject: [PATCH 6/6] fix(cluster): GPT-OSS sliding pages restore only rings they can continue Review pass on the seven-value ring metadata fix. GPTOSSSlidingRing's restore check accepted any unwrapped ring whose write index equals its rows. The SDK's RotatingKVCache.trim after eviction leaves such a ring with fewer than window - 1 rows behind a larger offset. Pages cap masks and trims by the offset, while the SDK caps them by the rows it holds, so pages restored from that ring diverged from it: - wrapped, then trimmed to 48 rows behind offset 50: the pages called themselves trimmable, built a 52-wide array mask where the SDK's is 50 wide, and trimming one row left 49 rows, one of them stale, where the SDK holds 47; - chunked past the window, then trimmed to 29 rows behind offset 202: the pages built a 129-wide array mask where the SDK uses a causal one, and refused a one-row trim the SDK performs. The check now also requires an unwrapped ring that has evicted rows to hold at least window - 1 rows, where both caps agree. No serving path restores this metadata, so nothing user-visible changes. Tests: - aRingTrimmedAfterEvictionRestoresOnlyWithWindowMinusOneRows restores the 127-row boundary and continues in lockstep with the ring, and refuses 126, 29 and 48 rows behind their offsets. - slidingPagesRestoredFromTheSDKRingContinueAsThatRing restores pages from the SDK ring's own state and metadata at six frontiers (short, full, wrapped, chunked past the window, wrapped back to its end, chunked again) and continues each in lockstep with a copy of the ring. It is the only test that restores a full, unwrapped window, where both flags hold the same rows and the pages must keep the ring's. - The metadata refusal test also refuses an offset below the rows held. Co-Authored-By: Claude Opus 5.5 --- docs/architecture/inference.md | 11 ++-- docs/developer/test.md | 3 +- .../GPTOSS/Generation/GPTOSSSlidingRing.swift | 8 ++- .../GPTOSSPagedKVTests.swift | 66 ++++++++++++++++++- 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 9ab612aeb0..d62304aa35 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -4438,8 +4438,11 @@ window, step, offset, write index, capacity origin and wrapped flag (`GPTOSSSlidingRing`). Restoring accepts only that layout for the cache's window, and only with the rows that ring holds: its first `index` rows, or the whole window once wrapped. It refuses the five-value legacy layout, a rewind reserve, a -kept prefix, and any other step, window or capacity origin. GPT-OSS serving never -reads or restores this metadata. +kept prefix, and any other step, window or capacity origin. It also refuses an +unwrapped ring that has evicted rows but holds fewer than `window - 1`, which the +SDK's `trim` after eviction can leave: pages cap masks and trims by the offset, +the SDK by the rows it holds. GPT-OSS serving never reads or restores this +metadata. `GPTOSSRequestStateBudget` keeps the existing full-request admission scope and never lowers its previous contiguous allowance. It also charges each page's @@ -4448,8 +4451,8 @@ copies; sliding repacking includes old and new page versions. Physical allocation is demand-grown even though the request is admitted conservatively for its whole declared scope. LOAD and live-memory gates remain authoritative. CPU parity against the actual SDK caches covers ring/page/chunk boundaries, -metadata and sinks. Real two-Mac numerical acceptance, resource release and performance -remain separate qualification gates. +metadata, restores and sinks. Real two-Mac numerical acceptance, resource release +and performance remain separate qualification gates. Code: `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSPagedKVCache.swift` (`GPTOSSPagedKVCache`), `libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift` diff --git a/docs/developer/test.md b/docs/developer/test.md index 22eaf15aaa..3c10bfbbc9 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1826,7 +1826,8 @@ swift test --package-path libs/darkbloom-cluster -c release \ `GPTOSSPagedKVTests` compares exact rows, masks, offsets, ring metadata and learned-sink SDPA results with `StandardKVCache` and `RotatingKVCache`. It also checks demand allocation, bounded sliding retention, copy/trim isolation, owner -release, and that sliding pages restore only the ring's own metadata. +release, and that sliding pages restore only ring metadata they can continue, +then continue exactly as that ring. `GPTOSSStageChecks` checks each page's allocator overhead and sliding repack charge. These are CPU correctness checks, not native transport, MXFP4 model parity or performance evidence. Retain the existing two-Mac reference comparator diff --git a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift index 4832c4be3f..9b9ccc3250 100644 --- a/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift +++ b/libs/darkbloom-cluster/Sources/DarkbloomClusterRuntime/Models/GPTOSS/Generation/GPTOSSSlidingRing.swift @@ -25,13 +25,17 @@ enum GPTOSSSlidingRing { } /// The position `metadata` gives a ring of `window` positions holding - /// `rows` rows; nil unless that ring writes exactly this metadata. + /// `rows` rows; nil unless that ring writes exactly this metadata and + /// pages can continue it. Pages cap masks and trims by the offset, so an + /// unwrapped ring that has evicted rows must still hold at least + /// window - 1 rows; the SDK's trim after eviction can leave fewer. static func position(of metadata: [String], window: Int, rows: Int) -> Position? { guard metadata.count > wrappedField, let offset = Int(metadata[offsetField]), let index = Int(metadata[indexField]), let wrapped = Bool(metadata[wrappedField]) else { return nil } let position = Position(offset: offset, index: index, wrapped: wrapped) guard metadata == Self.metadata(window: window, at: position), offset >= rows, - wrapped ? rows == window && index >= 0 && index <= rows : index == rows else { return nil } + wrapped ? rows == window && index >= 0 && index <= rows + : index == rows && (offset == rows || rows >= window - 1) else { return nil } return position } } diff --git a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift index 5bac3e4a08..86b8ac821f 100644 --- a/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift +++ b/libs/darkbloom-cluster/Tests/DarkbloomClusterRuntimeTests/GPTOSSPagedKVTests.swift @@ -149,9 +149,11 @@ struct GPTOSSPagedKVTests { func replacing(_ field: Int, _ value: String) -> [String] { var fields = metadata; fields[field] = value; return fields } - // Legacy, rewind reserve, kept prefix, other step, requested origin, non-canonical offset. + // Legacy, rewind reserve, kept prefix, other step, requested origin, non-canonical offset, + // fewer positions than rows. for refused in [Array(metadata.prefix(5)), metadata + ["2"], replacing(0, "1"), replacing(2, "64"), - replacing(5, "requested"), replacing(3, "+\(position.offset)")] { + replacing(5, "requested"), replacing(3, "+\(position.offset)"), + replacing(3, String(held - 1))] { #expect(GPTOSSSlidingRing.position(of: refused, window: 128, rows: held) == nil) } // A flipped flag claims other rows, except at a full window's end. @@ -164,6 +166,66 @@ struct GPTOSSPagedKVTests { } } + /// Restores pages from the SDK ring's own state and metadata, then checks + /// they continue exactly as a copy of that ring. + private func expectRestoredPagesContinue(_ ring: RotatingKVCache) { + guard GPTOSSSlidingRing.position(of: ring.metaState, window: 128, rows: ring.state[0].dim(2)) != nil else { + Issue.record("Pages refused the SDK ring's metadata \(ring.metaState)"); return + } + let pages = GPTOSSPagedKVCache(window: 128), expected = ring.copy() + pages.state = ring.state; pages.metaState = ring.metaState + #expect(pages.metaState == ring.metaState) + for n in [1, 2, 1] { + for returnArray in [false, true] { + equalMask(pages.makeMask(n: n, windowSize: 128, returnArray: returnArray), + expected.makeMask(n: n, windowSize: 128, returnArray: returnArray)) + } + let next = rows(n, start: expected.offset) + let a = pages.update(keys: next.0, values: next.1) + let b = expected.update(keys: next.0, values: next.1) + equal(a.0, b.0); equal(a.1, b.1) + #expect(pages.offset == expected.offset && pages.isTrimmable == expected.isTrimmable + && pages.metaState == expected.metaState) + } + } + + @Test func slidingPagesRestoredFromTheSDKRingContinueAsThatRing() { + Device.withDefaultDevice(.cpu) { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + var restored = 0 + // Short, full, wrapped, chunked past the window, wrapped back to its end, chunked again. + for (step, count) in ([3, 1, 124, 1, 512] + Array(repeating: 1, count: 128) + [2]).enumerated() { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + guard [0, 2, 3, 4, 132, 133].contains(step) else { continue } + expectRestoredPagesContinue(ring) + restored += 1 + } + #expect(restored == 6) + } + } + + @Test func aRingTrimmedAfterEvictionRestoresOnlyWithWindowMinusOneRows() { + Device.withDefaultDevice(.cpu) { + func ring(_ counts: [Int]) -> RotatingKVCache { + let ring = RotatingKVCache(maxSize: 128, keep: 0) + for count in counts { + let input = rows(count, start: ring.offset) + _ = ring.update(keys: input.0, values: input.1) + } + return ring + } + // Pages cap masks and trims by the offset; the ring caps them by the rows it holds. + let evicted = ring([300, 2]), wrapped = ring([129, 1]) + #expect(evicted.trim(2) == 2 && evicted.state[0].dim(2) == 127 && evicted.offset == 300) + expectRestoredPagesContinue(evicted) + for (trimmed, count, held) in [(evicted, 1, 126), (evicted, 97, 29), (wrapped, 80, 48)] { + #expect(trimmed.trim(count) == count && trimmed.state[0].dim(2) == held) + #expect(GPTOSSSlidingRing.position(of: trimmed.metaState, window: 128, rows: held) == nil) + } + } + } + @Test func slidingPagesStayBoundedAndRequestRetirementDropsEveryOwner() { Device.withDefaultDevice(.cpu) { weak var released: GPTOSSPagedKVCache?