From 6ec793cf5d79cef52b7248b3726b6a334cb70569 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 15:40:59 -0500 Subject: [PATCH 1/7] Approve DevNet cluster pairs by model, not by build A cluster approval may now name no build (a model approval): the 14 fields of the model and its serving terms, without the placement digest and the six runtime digests. Build-pinned entries keep every rule they had. - ClusterRuntimeApproval reads and saves either shape (all seven runtime digests or none, never null) and encodes a model approval under darkbloom/coordinator-cluster-model-approval/v1. - NativePairMemberPolicy reads the new domain and names its digests (artifact, pinnedPlan, runtime) instead of indexing them. - Under a model approval the member registers its plan with its own runtime block (ClusterPlan.runtime), requires a start to carry it, and hashes its worker against its setup's pin and its metallib and resource library against digests it took at registration. - Selection takes a model approval by model, schedule and the saved artifact, with no build facts; the facts run at most once, only for build-pinned entries. Each Mac's save check compares the artifact. - Docs and a changelog fragment. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-model-approvals.md | 5 + docs/architecture/inference.md | 12 +- docs/reference/configuration.md | 49 ++++-- docs/reference/protocol-messages.md | 4 +- .../ClusterNativeMemberAttachment.swift | 20 ++- .../Config/ClusterRuntimeApproval.swift | 91 ++++++++-- .../NativePairMemberInstallation.swift | 62 +++++-- .../NativePairMemberPolicy+NativeStart.swift | 16 +- .../Coordinator/NativePairMemberPolicy.swift | 67 +++++++- .../Coordinator/NativePairMemberRoster.swift | 13 +- .../DistributedInstalledNativeStart.swift | 10 ++ .../Installed/DistributedInstalledOwner.swift | 14 +- .../ClusterApprovalAttachment.swift | 36 ++-- .../ClusterApprovalFetch.swift | 11 +- .../ClusterApprovalLifetime.swift | 36 ++-- .../ClusterApproval/ClusterApprovalSync.swift | 6 +- .../Membership/ClusterMemberPreparation.swift | 21 ++- .../Protocol/ClusterRosterRegistration.swift | 38 ++++- .../Config/ClusterModelApprovalTests.swift | 160 ++++++++++++++++++ .../Config/ClusterPairApprovalTests.swift | 6 +- .../ClusterRosterMemberTests.swift | 140 ++++++++++++++- .../ClusterApprovalFetchTests.swift | 15 +- .../ClusterApprovalFixture.swift | 85 ++++++++-- .../ClusterApprovalLifetimeTests.swift | 40 ++++- .../ClusterApprovalSyncTests.swift | 74 ++++++++ 25 files changed, 887 insertions(+), 144 deletions(-) create mode 100644 changelog.d/cluster-model-approvals.md create mode 100644 provider-swift/Tests/ProviderCoreTests/Config/ClusterModelApprovalTests.swift diff --git a/changelog.d/cluster-model-approvals.md b/changelog.d/cluster-model-approvals.md new file mode 100644 index 0000000000..4f16ca9eeb --- /dev/null +++ b/changelog.d/cluster-model-approvals.md @@ -0,0 +1,5 @@ +### 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. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index eaef716349..45d8607a6e 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2886,7 +2886,13 @@ a share of every layer, and one fewer than the members otherwise, as the coordinator requires. A setup with unequal tensor-parallel shares is refused at registration, because the provider does not encode the plan's `tensor_parallel_shares` yet: a plan without them is an equal split to the -coordinator. For a cluster that serves through Darkbloom, the onboarding's start +coordinator. Under a model approval, which names no build, the plan also carries +the member's own runtime block (`ClusterPlan.runtime`: worker, capability, +resource policy and profile from its saved setup, +`DistributedInstalledNativeStart.runtimeBlock`), so both members must run the +same runtime to register the same plan; the start must carry that block +([model approvals](../reference/configuration.md#model-approvals)). For a +cluster that serves through Darkbloom, the onboarding's start line says it serves its owner's requests, and public requests where Darkbloom has qualified the model and split (`provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift`); @@ -5213,6 +5219,10 @@ that no person types them value, which the member and its owner compare with the installed approval (`NativePairMemberPolicy.require`). +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`), `provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledFiles.swift`, diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 169e6eb50b..5d82922a82 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -> Last updated: 2026-10-29 +> Last updated: 2026-10-30 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. @@ -927,7 +927,9 @@ checks it against its own installed files with the same computation. One type co `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. +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)). | Field | Value | |---|---| @@ -1008,9 +1010,11 @@ selector matches the two registrations itself (see **Automatic (guided setup).** The coordinator operator adds a cluster approval by hand to the operator approval file -([`EIGENINFERENCE_CLUSTER_PAIR_CATALOG`](#experimental-cluster-pairs)), with the -digests that `darkbloom cluster runtime-facts --app --model -=,` prints ([cluster runtime facts](#cluster-runtime-facts)). +([`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 +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 saves it on both Macs. The cluster service then runs each Mac's part as @@ -1022,11 +1026,11 @@ 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`; 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`) | -| Match | The entry whose `model` is the setup's `publicModelID`, whose `schedule` is its prefill schedule (`1` serial, `2` one-chunk lookahead), that is still current, and whose eight digests all equal this Mac's own cluster runtime facts (computed from the helpers beside the setup's worker and the setup's model folder); latest `not_after` first. 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 (`ClusterApprovalAttachment.mismatches`); 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`) | +| 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`) | +| 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`) | -| 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, 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 | +| 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 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 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 and the reason in its setup record (`approvalSetAside`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, only a later entry | `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` | @@ -1063,8 +1067,8 @@ coordinator operator keeps: The automatic path saves `schema` `darkbloom_cluster_native_member_v2` (the roster registration) instead: `ownerSHA256`, `metallibPath` and `resourceLibraryPath` as above (the setup worker's `mlx.metallib` and -`pagedattention.metal`), `clusterApproval` (one `cluster_approvals` entry, -field for field), `roster` (the roster both Macs countersigned when they +`pagedattention.metal`), `clusterApproval` (one `cluster_approvals` entry of +either shape, field for field), `roster` (the roster both Macs countersigned when they paired), `memberPins` (the members' pins in rank order) and `edges` (the link the serving leader last measured, as `rdma`; omitted when none was measured). @@ -1073,7 +1077,9 @@ loaded (`provider-swift/Sources/ProviderCore/Config/ClusterNativeMemberAttachmen `validate`): the approval's `model`, `plan_sha256`, `artifact_sha256`, `native_runtime_sha256`, `capability_sha256`, `profile_sha256` and `schedule` must equal the saved setup's own model, selected Plan, capability pins and -prefill schedule (`1` serial, `2` one-chunk lookahead). The member derives the +prefill schedule (`1` serial, `2` one-chunk lookahead). A cluster approval +names no plan; a model approval names no runtime, so only its `model`, +`artifact_sha256` and `schedule` are compared. The member derives the canonical policy bytes from the entry exactly as the coordinator does (`provider-swift/Sources/ProviderCore/Config/ClusterPairApproval.swift`, `canonicalPolicy`, mirroring `darkbloom-platform:coordinator/registry/native_pair_approval.go`, @@ -1085,7 +1091,8 @@ then `Z` or `±HH:MM`); any other spelling is refused when the setup is saved. At start (`provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift`, `nativeMemberInstallation`) the approval must be unexpired and list this Mac's chip, and the owner, native executable, metallib and resource library must -hash to their pins; otherwise the command stops before registering. A member +hash to their pins; otherwise the command stops before registering. Under a +model approval the pins are this Mac's own (below). A member whose setup has no `nativeMember` registers no membership and is never paired. A setup with `nativeMember` cannot run `darkbloom start --local --distributed` @@ -1099,6 +1106,22 @@ pair's slot, the follower dials it. A member without `linkControl` declines the coordinator's preparation; see [provider member control](cluster-control-protocol.md#provider-member-control). +### Model approvals + +A model approval is a `cluster_approvals` entry that names no build. A new +build of the provider needs no new entry: after an update, the re-adopted +setups find the same entry at the next check. The coordinator accepts one only +in its development deployment (DevNet); see the coordinator's documentation in +`Layr-Labs/darkbloom-platform`. Build-pinned entries keep every rule above. + +| Item | Rule | Source | +|---|---|---| +| Shape | Exactly 14 fields: `id`, `model`, `generation`, `artifact_sha256`, `schedule`, `maximum_transport_frame`, `maximum_plaintext`, `maximum_records`, `maximum_cumulative_plaintext`, `allowed_numerics_classes`, `minimum_members`, `maximum_members`, `minimum_member_usable_bytes`, `not_after`. The build-pinned shape adds `placement_policy_sha256`, `native_runtime_sha256`, `metallib_sha256`, `resource_library_sha256`, `capability_sha256`, `resource_policy_sha256` and `profile_sha256`. An entry with some but not all of these seven, or with a null one, is refused | `provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift` (`ClusterRuntimeApproval`, `isEntry`, `init(from:)`) | +| Canonical bytes | Domain `darkbloom/coordinator-cluster-model-approval/v1` and a zero byte, then the cluster approval's layout without the placement digest and the six runtime digests: `id`, `model`, `generation`, `artifact_sha256`, bytes `1, 1, schedule`, frame, plaintext, records, cumulative, `not_after` (nanoseconds), member bounds, usable bytes, grant lease terms, numerics classes. Their SHA-256 is the `policy_sha256` the member registers. Two golden vectors are pinned in `ClusterModelApprovalTests` and in the coordinator's tests | `ClusterRuntimeApproval.canonicalPolicy`; `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift` (`modelDomain`) | +| Plan runtime block | The member's plan for a model approval carries `runtime`: `native_runtime_sha256` (the saved setup's `capability.runtimeBinarySHA256`), `capability_sha256` (the setup's `capabilitySHA256`), `resource_policy_sha256` (`DistributedInstalledNativeStart.resourcePolicySHA256` of the capability) and `profile_sha256` (`capability.profileFingerprint`). A plan for a build-pinned entry has none. The block is part of the plan, so both members must register the same one | `DistributedInstalledNativeStart.runtimeBlock`; `provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift` (`ClusterPlan.runtime`) | +| Metallib and resource library | Hashed once when the member builds its registration. The metallib digest also gives the device profile's numerics class | `ClusterMemberPreparation.nativeMemberInstallation` | +| Start | The start's worker, capability, resource-policy and profile digests must equal the member's own block; the artifact, schedule and limits must equal the entry's. At prepare, the worker hashes to the setup's pin and the metallib and resource library to the digests taken at registration. The owner admits the start against the same block from its own setup | `NativePairMemberPolicy.require`, `NativePairMemberInstallation` (`requireStart`, `verifyInstalledFiles`), `DistributedInstalledOwner.memberAuthorizer` | + ### Guided link setup `darkbloom cluster` (and `darkbloom cluster setup`) on a terminal runs the diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index 5c0f8ed62d..0b8029434f 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -1,6 +1,6 @@ # Provider ↔ coordinator protocol messages -> Last updated: 2026-10-29 +> Last updated: 2026-10-30 Every JSON frame on the provider WebSocket (`GET /ws/provider`), with the Go type, the Swift type, and the presence rule for each field. Go is the canon in @@ -296,7 +296,7 @@ connection, first. | `execution_role` | `ExecutionRole` | `ProviderExecutionRole` | opt | omitted/`""` keeps ordinary solo; `"cluster_member"` is the control-only member role (empty ordinary `models`, separate `cluster_models`, fresh `member_registration_nonce`) — grants no trust or model capability | | `member_registration_nonce` | `string` | `String?` | opt | 64 lowercase hex chars, this connection's member negotiation nonce; invalid without the member role | | `cluster_models` | `[]ModelInfo` | `[ModelInfo]?` | opt | separate cluster inventory for the member role; invalid on a solo registration; old coordinators ignore it and see no routable model | -| `cluster_membership` | `*ClusterMembership` | `ClusterMembership?` | opt | member role only (a solo registration carrying it is refused, and the provider never encodes it for one). `cluster_id`: the saved cluster label, 1–128 of `A–Z a–z 0–9 - . _`, not starting with `-`; `rank`: `0` leader or `1` follower; `policy_sha256`: 64 lowercase hex, SHA-256 of the canonical coordinator runtime policy the member installed. A claim the pair selector matches against a second member of the same account and the operator's approval catalog; it grants nothing. A member that omits it is acknowledged and never paired (`darkbloom-platform:coordinator/protocol/execution_role.go`, `ClusterMembership.Validate`; [pair formation](cluster-control-protocol.md#pair-formation)). The provider sends it only when its saved setup carries a pair approval, and derives it from the installed member control, so `policy_sha256` is the digest of exactly the policy bytes that control requires in a prepare frame (`provider-swift/Sources/ProviderCore/Protocol/ClusterMembership.swift`, `ClusterMembership`; `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift`, `membership`). Each plan of a roster registration's `plans[]` names its generation `mode` (omitted is `pipeline_v1`) and that mode's `cuts`: none for `tensor_parallel_v1`, one fewer than `members` for every other mode (`provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift`, `ClusterPlan.cutCount`; `darkbloom-platform:coordinator/protocol/cluster_generation_mode.go`, `ClusterPlanModeCutCount`). The provider does not encode `tensor_parallel_shares` yet, so a setup with unequal tensor-parallel shares is refused at registration (`provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift`, `NativePairMemberRoster`) | +| `cluster_membership` | `*ClusterMembership` | `ClusterMembership?` | opt | member role only (a solo registration carrying it is refused, and the provider never encodes it for one). `cluster_id`: the saved cluster label, 1–128 of `A–Z a–z 0–9 - . _`, not starting with `-`; `rank`: `0` leader or `1` follower; `policy_sha256`: 64 lowercase hex, SHA-256 of the canonical coordinator runtime policy the member installed. A claim the pair selector matches against a second member of the same account and the operator's approval catalog; it grants nothing. A member that omits it is acknowledged and never paired (`darkbloom-platform:coordinator/protocol/execution_role.go`, `ClusterMembership.Validate`; [pair formation](cluster-control-protocol.md#pair-formation)). The provider sends it only when its saved setup carries a pair approval, and derives it from the installed member control, so `policy_sha256` is the digest of exactly the policy bytes that control requires in a prepare frame (`provider-swift/Sources/ProviderCore/Protocol/ClusterMembership.swift`, `ClusterMembership`; `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift`, `membership`). Each plan of a roster registration's `plans[]` names its generation `mode` (omitted is `pipeline_v1`) and that mode's `cuts`: none for `tensor_parallel_v1`, one fewer than `members` for every other mode (`provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift`, `ClusterPlan.cutCount`; `darkbloom-platform:coordinator/protocol/cluster_generation_mode.go`, `ClusterPlanModeCutCount`). The provider does not encode `tensor_parallel_shares` yet, so a setup with unequal tensor-parallel shares is refused at registration (`provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift`, `NativePairMemberRoster`). A plan for a model approval also carries `runtime`, exactly `native_runtime_sha256`, `capability_sha256`, `resource_policy_sha256` and `profile_sha256` (64 lowercase hex, nonzero), from the member's own saved setup; it is left out of a plan for a build-pinned approval and is part of the plan both members must register byte for byte (`ClusterPlan.runtime`, `samePlacement`; [model approvals](configuration.md#model-approvals)) | | `busy_reason`, `busy_since_ms`, `busy_addon` | — | `ProviderBusy?` | opt | Present only while an add-on holds the provider; [add-on hold busy fields](#add-on-hold-busy-fields) | An attested registration is encoded by the raw-attestation encoder, not the diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterNativeMemberAttachment.swift b/provider-swift/Sources/ProviderCore/Config/ClusterNativeMemberAttachment.swift index d8ba25fc23..f9f71d676a 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterNativeMemberAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterNativeMemberAttachment.swift @@ -19,7 +19,8 @@ public struct ClusterNativeMemberAttachment: Codable, Sendable, Equatable { public let resourceLibraryPath: String /// v1: the pair approval. public let approval: ClusterPairApproval? - /// v2: the cluster approval this member derives its plan for. + /// v2: the cluster approval this member derives its plan for: build-pinned, + /// or a model approval, under which the member's plan carries its own runtime. public let clusterApproval: ClusterRuntimeApproval? /// v2: every member's pin, Secure Enclave key and signature over the /// roster's canonical bytes. The coordinator forms a cluster only from @@ -71,18 +72,21 @@ public struct ClusterNativeMemberAttachment: Codable, Sendable, Equatable { throw ClusterConfigurationError.invalid("Saved native member attachment has unsupported or ambiguous inputs") } let policy = try NativePairMemberPolicy(policyBytes) - let hashes = policy.hashes.map { $0.map { String(format: "%02x", $0) }.joined() } + let hex = NativePairMemberPolicy.hex // Plan, artifact, native runtime, capability and profile are the saved // setup's own pins; the metallib, resource library and resource policy // digests exist only in the approval and are checked against the // installed files when the member starts. A cluster approval fixes no // plan: its first digest is the placement policy, and the plan is the - // one this member derives (`selectedPlanSHA256`) and registers. + // one this member derives (`selectedPlanSHA256`) and registers. A model + // approval pins no runtime: the member takes it from this setup. + let runtimeIsTheSetups = policy.runtime.map { + hex($0.nativeRuntime) == capability.runtimeBinarySHA256 && hex($0.capability) == configuration.capabilitySHA256 + && hex($0.profile) == capability.profileFingerprint + } ?? true guard policy.model == configuration.publicModelID, - policy.cluster != nil || hashes[0] == configuration.selectedPlanSHA256, - hashes[1] == capability.artifactSHA256, - hashes[2] == capability.runtimeBinarySHA256, hashes[5] == configuration.capabilitySHA256, - hashes[7] == capability.profileFingerprint, + policy.cluster != nil || policy.pinnedPlan.map(hex) == configuration.selectedPlanSHA256, + hex(policy.artifact) == capability.artifactSHA256, runtimeIsTheSetups, policy.schedule == (configuration.selectedPrefillSchedule == .serial ? 1 : 2) else { throw ClusterConfigurationError.invalid("Saved pair approval differs from the model, runtime, Plan, profile or schedule") } @@ -107,7 +111,7 @@ public struct ClusterNativeMemberAttachment: Codable, Sendable, Equatable { guard Set(object.keys).isSubset(of: rosterFields), Set(object.keys).isSuperset(of: rosterFields.subtracting(["edges"])), let approval = object["clusterApproval"] as? [String: Any], - Set(approval.keys) == ClusterRuntimeApproval.fields else { + ClusterRuntimeApproval.isEntry(approval.keys) else { throw ClusterConfigurationError.invalid("Unknown or missing native member attachment fields") } return diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift index 19aa89dc1b..488246110c 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift @@ -6,18 +6,24 @@ import Foundation /// `clusterRuntimeApprovalFile` and `canonicalClusterRuntimeApproval` /// (darkbloom-platform coordinator/registry/native_pair_catalog_file.go, /// native_pair_approval.go). Saving an entry approves nothing. +/// +/// An entry has one of two shapes, chosen by its field names. A build-pinned +/// entry names the seven runtime digests of one signed build. A model approval +/// names none of them: it names the model and its serving terms, and each +/// member takes its runtime from its own saved setup (contract M1, M3). public struct ClusterRuntimeApproval: Codable, Sendable, Equatable { public let id: String public let model: String public let generation: UInt64 - public let placementPolicySHA256: String + /// The seven runtime digests: all set (build-pinned) or all nil (a model approval). + public let placementPolicySHA256: String? public let artifactSHA256: String - public let nativeRuntimeSHA256: String - public let metallibSHA256: String - public let resourceLibrarySHA256: String - public let capabilitySHA256: String - public let resourcePolicySHA256: String - public let profileSHA256: String + public let nativeRuntimeSHA256: String? + public let metallibSHA256: String? + public let resourceLibrarySHA256: String? + public let capabilitySHA256: String? + public let resourcePolicySHA256: String? + public let profileSHA256: String? public let schedule: UInt8 public let maximumTransportFrame: UInt32 public let maximumPlaintext: UInt32 @@ -49,14 +55,39 @@ public struct ClusterRuntimeApproval: Codable, Sendable, Equatable { case minimumMemberUsableBytes = "minimum_member_usable_bytes" case notAfter = "not_after" } + /// The runtime digests a build-pinned entry names and a model approval leaves out. + static let runtimeKeys: [CodingKeys] = [.placementPolicySHA256, .nativeRuntimeSHA256, .metallibSHA256, + .resourceLibrarySHA256, .capabilitySHA256, .resourcePolicySHA256, .profileSHA256] + /// The 21 fields of a build-pinned entry. static let fields = Set(CodingKeys.allCases.map(\.rawValue)) + /// The 14 fields of a model approval. + static let modelFields = fields.subtracting(runtimeKeys.map(\.rawValue)) + + /// Whether `keys` are exactly the fields of one of the two shapes. + static func isEntry(_ keys: some Sequence) -> Bool { + let names = Set(keys) + return names == fields || names == modelFields + } + + /// The seven runtime digests in canonical order: all of them, none (a model approval), or nil when only some are + /// set, which no entry encodes. + var runtimeDigests: [String]? { + let digests = [placementPolicySHA256, nativeRuntimeSHA256, metallibSHA256, resourceLibrarySHA256, + capabilitySHA256, resourcePolicySHA256, profileSHA256].compactMap { $0 } + return digests.isEmpty || digests.count == Self.runtimeKeys.count ? digests : nil + } + + /// Whether this entry is a model approval: it pins no build. + var isModelApproval: Bool { runtimeDigests?.isEmpty == true } /// The grant lease terms every cluster approval binds (the coordinator's /// `grantlease.Default`): renewal interval, time to live, disconnect grace. static let leaseTermsNanoseconds: [UInt64] = [40_000_000_000, 120_000_000_000, 90_000_000_000] /// The exact bytes the coordinator hashes into the approval binding and - /// sends in every prepare frame of a cluster session. + /// sends in every prepare frame of a cluster session: the build-pinned + /// layout, or the model approval's (contract M2), which leaves out the + /// placement digest and the six runtime digests under its own domain. func canonicalPolicy() throws -> Data { guard let expiry = ClusterPairApproval.unixNanoseconds(rfc3339: notAfter) else { throw ClusterConfigurationError.invalid("Cluster approval not_after must be an RFC 3339 instant") @@ -65,14 +96,18 @@ public struct ClusterRuntimeApproval: Codable, Sendable, Equatable { minimumMemberUsableBytes > 0 else { throw ClusterConfigurationError.invalid("Cluster approval member bounds are outside 2...4") } - var bytes = Data("darkbloom/coordinator-cluster-runtime-approval/v1\0".utf8) + guard let runtime = runtimeDigests else { + throw ClusterConfigurationError.invalid("Cluster approval names some but not all of its runtime digests") + } + // The placement digest comes before the artifact, the six others after it. + let digests: [String] = runtime.isEmpty ? [artifactSHA256] : [runtime[0], artifactSHA256] + runtime.dropFirst() + var bytes = runtime.isEmpty ? NativePairMemberPolicy.modelDomain : NativePairMemberPolicy.clusterDomain func integer(_ value: T) { withUnsafeBytes(of: value.bigEndian) { bytes.append(contentsOf: $0) } } func text(_ value: String) { integer(UInt32(value.utf8.count)); bytes.append(contentsOf: value.utf8) } text(id); text(model); integer(generation) - for digest in [placementPolicySHA256, artifactSHA256, nativeRuntimeSHA256, metallibSHA256, - resourceLibrarySHA256, capabilitySHA256, resourcePolicySHA256, profileSHA256] { + for digest in digests { guard ClusterConfigurationSyntax.hash(digest) else { throw ClusterConfigurationError.invalid("Cluster approval digests must be 64 lowercase hex characters") } @@ -94,3 +129,37 @@ public struct ClusterRuntimeApproval: Codable, Sendable, Equatable { return bytes } } + +// In an extension, so the memberwise initializer stays. +extension ClusterRuntimeApproval { + /// Reads either shape: the seven runtime digests all present or all absent, never null. + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let present = Self.runtimeKeys.filter { c.contains($0) } + guard present.isEmpty || present.count == Self.runtimeKeys.count else { + throw DecodingError.dataCorruptedError(forKey: present[0], in: c, + debugDescription: "A cluster approval names all seven runtime digests or none") + } + func digest(_ key: CodingKeys) throws -> String? { + guard !present.isEmpty else { return nil } + return try c.decode(String.self, forKey: key) + } + try self.init(id: c.decode(String.self, forKey: .id), model: c.decode(String.self, forKey: .model), + generation: c.decode(UInt64.self, forKey: .generation), + placementPolicySHA256: digest(.placementPolicySHA256), + artifactSHA256: c.decode(String.self, forKey: .artifactSHA256), + nativeRuntimeSHA256: digest(.nativeRuntimeSHA256), metallibSHA256: digest(.metallibSHA256), + resourceLibrarySHA256: digest(.resourceLibrarySHA256), capabilitySHA256: digest(.capabilitySHA256), + resourcePolicySHA256: digest(.resourcePolicySHA256), profileSHA256: digest(.profileSHA256), + schedule: c.decode(UInt8.self, forKey: .schedule), + maximumTransportFrame: c.decode(UInt32.self, forKey: .maximumTransportFrame), + maximumPlaintext: c.decode(UInt32.self, forKey: .maximumPlaintext), + maximumRecords: c.decode(UInt64.self, forKey: .maximumRecords), + maximumCumulativePlaintext: c.decode(UInt64.self, forKey: .maximumCumulativePlaintext), + allowedNumericsClasses: c.decode([String].self, forKey: .allowedNumericsClasses), + minimumMembers: c.decode(Int.self, forKey: .minimumMembers), + maximumMembers: c.decode(Int.self, forKey: .maximumMembers), + minimumMemberUsableBytes: c.decode(UInt64.self, forKey: .minimumMemberUsableBytes), + notAfter: c.decode(String.self, forKey: .notAfter)) + } +} diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift index 1fa9da09bf..9ee5ed0827 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift @@ -34,21 +34,30 @@ public struct NativePairMemberInstallation: Sendable { /// what this member registers instead of the pair claim, the plan a /// committed start must name, and the peer key its data plane pins. let roster: NativePairMemberRoster? + /// The runtime a start must carry and the installed files must hash to: + /// the approval's own, or under a model approval this member's own (its + /// plan's runtime block and the digests it took of its installed files). + let runtime: NativePairMemberPolicy.Runtime /// `meshOverLink`: the saved setup reaches the follower over the link /// control channel, the only way a committed start can serve in this - /// build. Without it the member declines preparation. + /// build. Without it the member declines preparation. `installedDigests`: + /// under a model approval, the digests this member took of its installed + /// metallib and resource library when it built its registration (the + /// metallib's also gave its numerics class); unused otherwise. public init(expectedCoordinatorPolicy: Data, rank: Int, clusterID: String, identity: ClusterWorkerIdentity, profile: ClusterWorkerProfile, installedOwner: URL, ownerSHA256: String, nativeExecutable: URL, metallib: URL, resourceLibrary: URL, chip: String, meshOverLink: Bool = false, - roster: NativePairMemberRoster? = nil, batchLanes: Int? = nil) throws { + roster: NativePairMemberRoster? = nil, batchLanes: Int? = nil, + installedDigests: (metallib: String, resourceLibrary: String)? = nil) throws { try self.init(expectedCoordinatorPolicy: expectedCoordinatorPolicy, rank: rank, clusterID: clusterID, identity: identity, profile: profile, installedOwner: installedOwner, ownerSHA256: ownerSHA256, nativeExecutable: nativeExecutable, metallib: metallib, resourceLibrary: resourceLibrary, chip: chip, leaseDirectory: ClusterUserPaths().deviceDirectory, ownerServesCommittedStart: DistributedInstalledOwner.servesCommittedNativeStart && meshOverLink, - bootstrap: meshOverLink ? .preludeThenMesh : .nativeKeyPrelude, roster: roster, batchLanes: batchLanes) + bootstrap: meshOverLink ? .preludeThenMesh : .nativeKeyPrelude, roster: roster, batchLanes: batchLanes, + installedDigests: installedDigests) } // Same existing canonical-style private directory checks; only fixtures // select a temporary scope and their own owner. Production uses @@ -58,8 +67,21 @@ public struct NativePairMemberInstallation: Sendable { installedOwner: URL, ownerSHA256: String, nativeExecutable: URL, metallib: URL, resourceLibrary: URL, chip: String, leaseDirectory: URL, ownerServesCommittedStart: Bool = true, bootstrap: Bootstrap = .nativeKeyPrelude, - roster: NativePairMemberRoster? = nil, batchLanes: Int? = nil) throws { + roster: NativePairMemberRoster? = nil, batchLanes: Int? = nil, + installedDigests: (metallib: String, resourceLibrary: String)? = nil) throws { let policy = try NativePairMemberPolicy(expectedCoordinatorPolicy) + // A model approval pins no runtime: this member's plan names its own + // (`runtime` block), and a plan for a build-pinned approval names none. + let runtime: NativePairMemberPolicy.Runtime + if let pinned = policy.runtime { + guard roster?.plan.runtime == nil else { throw NativePairMemberError.binding } + runtime = pinned + } else { + guard let block = roster?.plan.runtime, let installedDigests, + let own = NativePairMemberPolicy.Runtime(block, metallibSHA256: installedDigests.metallib, + resourceLibrarySHA256: installedDigests.resourceLibrary) else { throw NativePairMemberError.binding } + runtime = own + } // A pair approval lists the chips it covers; a cluster approval the // numerics classes (none listed: any class) and the usable memory a // member must have, and only a roster registration is offered under it. @@ -71,21 +93,23 @@ public struct NativePairMemberInstallation: Sendable { && (device?.usableWiredBytes ?? 0) >= terms.minimumMemberUsableBytes && roster?.plan.policySHA256 == Self.hex(Data(SHA256.hash(data: expectedCoordinatorPolicy))) && roster?.plan.model == policy.model - && roster?.membership.artifact(for: policy.model) == Self.hex(policy.hashes[1]) + && roster?.membership.artifact(for: policy.model) == Self.hex(policy.artifact) } else { covered = roster == nil && policy.chips.contains(chip) } guard (0...1).contains(rank), identity.peers.count == 2, ClusterConfigurationSyntax.hash(ownerSHA256), covered, - identity.artifactSHA256 == Self.hex(policy.hashes[1]), - identity.peers[rank].buildSHA256 == Self.hex(policy.hashes[2]) else { throw NativePairMemberError.binding } + identity.artifactSHA256 == Self.hex(policy.artifact), + identity.peers[rank].buildSHA256 == Self.hex(runtime.nativeRuntime), + let executionPlanSHA256 = roster?.plan.planSHA256 ?? policy.pinnedPlan.map(Self.hex) else { + throw NativePairMemberError.binding + } _ = try ClusterOwnerBinding(clusterID: clusterID, ownerIncarnation: UUID(), leaseID: UUID(), - identity: identity, profile: profile, rank: rank, - executionPlanSHA256: roster?.plan.planSHA256 ?? Self.hex(policy.hashes[0])) + identity: identity, profile: profile, rank: rank, executionPlanSHA256: executionPlanSHA256) self.policy = policy; self.rank = rank; self.clusterID = clusterID self.identity = identity; self.profile = profile localOwner = try .init(installedDarkbloom: installedOwner, batchLanes: batchLanes); self.ownerSHA256 = ownerSHA256 artifacts = [nativeExecutable, metallib, resourceLibrary]; self.chip = chip; self.leaseDirectory = leaseDirectory self.ownerServesCommittedStart = ownerServesCommittedStart; self.bootstrap = bootstrap - self.roster = roster + self.roster = roster; self.runtime = runtime } /// The claim this member registers. Its `policySHA256` is the digest of /// exactly the policy bytes a prepare frame must carry. @@ -97,9 +121,10 @@ public struct NativePairMemberInstallation: Sendable { } } /// A committed start under this member's approval: for a cluster - /// approval, it must name the plan this member derived and registered. + /// approval, it must name the plan this member derived and registered, + /// and under a model approval the runtime this member registered with it. func requireStart(_ start: ClusterNativeAuthorizationStart) throws { - try policy.require(start, plan: roster?.planDigest) + try policy.require(start, plan: roster?.planDigest, runtime: runtime.block) if roster != nil, policy.cluster == nil { throw NativePairMemberError.binding } } func prepare(start: ClusterNativeAuthorizationStart, deadline: UInt64) throws -> [DistributedInstalledFiles.Identity] { @@ -109,12 +134,14 @@ public struct NativePairMemberInstallation: Sendable { return try withExtendedLifetime(gate) { try verifyInstalledFiles(deadline: deadline) } } /// Hashes the owner against its saved pin, and the native executable, - /// metallib and resource library against the policy's own digests. + /// metallib and resource library against the runtime's digests: the + /// policy's own, or under a model approval this member's setup's worker + /// pin and the digests it took when it built its registration. func verifyInstalledFiles(deadline: UInt64) throws -> [DistributedInstalledFiles.Identity] { var files = [try DistributedInstalledFiles.verify(localOwner.installedDarkbloom, expectedSHA256: ownerSHA256, maximumBytes: 256 * 1024 * 1024, executable: true, deadline: deadline)] - for i in 0..<3 { - files.append(try DistributedInstalledFiles.verify(artifacts[i], expectedSHA256: Self.hex(policy.hashes[i + 2]), + for (i, digest) in [runtime.nativeRuntime, runtime.metallib, runtime.resourceLibrary].enumerated() { + files.append(try DistributedInstalledFiles.verify(artifacts[i], expectedSHA256: Self.hex(digest), maximumBytes: 256 * 1024 * 1024, executable: i == 0, deadline: deadline)) } for file in files { try file.requireUnchanged() } @@ -140,6 +167,7 @@ public struct NativePairMemberInstallation: Sendable { ClusterWorkerIdentity(membershipEpoch: start.common.epoch, modelID: identity.modelID, artifactSHA256: identity.artifactSHA256, configurationSHA256: identity.configurationSHA256, peers: identity.peers) } - var executionPlanSHA256: String { roster?.plan.planSHA256 ?? Self.hex(policy.hashes[0]) } - static func hex(_ bytes: Data) -> String { bytes.map { String(format: "%02x", $0) }.joined() } + /// The registered plan, or a pair approval's fixed plan (the initializer refuses neither). + var executionPlanSHA256: String { roster?.plan.planSHA256 ?? policy.pinnedPlan.map(Self.hex) ?? "" } + static func hex(_ bytes: Data) -> String { NativePairMemberPolicy.hex(bytes) } } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy+NativeStart.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy+NativeStart.swift index 6263e9b214..dabca2771b 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy+NativeStart.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy+NativeStart.swift @@ -11,13 +11,21 @@ extension NativePairMemberPolicy { /// its placement policy). Nil skips that comparison for a cluster /// approval, whose caller then compares the plan itself; a pair approval /// always compares its own fixed plan. - func require(_ start: ClusterNativeAuthorizationStart, plan: Data? = nil) throws { + /// + /// `runtime`: the runtime block this member's own saved setup gives + /// (contract M3), read only for a model approval, which pins no runtime. + /// Nil skips that comparison for a model approval, whose caller then + /// compares the runtime itself; an approval that pins a runtime always + /// compares its own. + func require(_ start: ClusterNativeAuthorizationStart, plan: Data? = nil, runtime own: ClusterPlan.Runtime? = nil) throws { let c = start.common guard case .servingV1(let serving) = c.permission else { throw NativePairMemberError.binding } - let expectedPlan = cluster == nil ? hashes[0] : (plan ?? c.planSHA256) + let expectedPlan = cluster == nil ? pinnedPlan : (plan ?? c.planSHA256) + let started = ClusterPlan.Runtime(nativeRuntimeSHA256: Self.hex(serving.nativeRuntimeSHA256), + capabilitySHA256: Self.hex(serving.capabilitySHA256), resourcePolicySHA256: Self.hex(serving.resourcePolicySHA256), + profileSHA256: Self.hex(c.profileSHA256)) guard serving.nativePolicyGeneration == generation, serving.approvedNativeBindingSHA256 == Data(SHA256.hash(data: bytes)), - [c.planSHA256, c.artifactSHA256, serving.nativeRuntimeSHA256, serving.capabilitySHA256, - serving.resourcePolicySHA256, c.profileSHA256] == [expectedPlan, hashes[1], hashes[2], hashes[5], hashes[6], hashes[7]], + c.planSHA256 == expectedPlan, c.artifactSHA256 == artifact, (runtime?.block ?? own ?? started) == started, c.schedule.rawValue == schedule, c.maximumTransportFrameBytes == Int(maximumFrame), c.limits.maximumPlaintextBytes == Int(maximumPlaintext), c.limits.maximumRecordsPerDirection == maximumRecords, c.limits.maximumCumulativePlaintextBytesPerDirection == maximumCumulative else { throw NativePairMemberError.binding } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift index 4d8f5c2ae0..fac9a896c2 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift @@ -6,16 +6,49 @@ struct NativePairMemberPolicy: Sendable { let bytes: Data let model: String let generation: UInt64 - /// Plan (a pair approval's fixed plan, or a cluster approval's placement - /// policy), artifact, native runtime, metallib, resource library, - /// capability, resource policy and profile. - let hashes: [Data] + /// The model's artifact digest, which every approval names. + let artifact: Data + /// A pair approval's fixed plan, or a build-pinned cluster approval's + /// placement policy (no member check reads it); nil for a model approval. + let pinnedPlan: Data? + /// The runtime a pair or build-pinned cluster approval pins; nil for a + /// model approval, whose members take it from their own saved setups. + let runtime: Runtime? + /// The runtime digests a member starts with and hashes its files against. + struct Runtime: Sendable, Equatable { + let nativeRuntime, metallib, resourceLibrary, capability, resourcePolicy, profile: Data + + /// From a plan's runtime block (the member's own setup) and the + /// digests the member took of its installed metallib and resource + /// library; nil when a value is not 64 lowercase hex characters. + init?(_ block: ClusterPlan.Runtime, metallibSHA256: String, resourceLibrarySHA256: String) { + let values = [block.nativeRuntimeSHA256, metallibSHA256, resourceLibrarySHA256, block.capabilitySHA256, + block.resourcePolicySHA256, block.profileSHA256].compactMap(NativePairMemberPolicy.digest(hex:)) + guard values.count == 6 else { return nil } + self.init(values) + } + + /// The six digests in canonical order (worker, metallib, resource library, capability, resource policy, profile). + init(_ values: [Data]) { + nativeRuntime = values[0]; metallib = values[1]; resourceLibrary = values[2] + capability = values[3]; resourcePolicy = values[4]; profile = values[5] + } + + /// The four digests a start carries, as a plan's runtime block names them. + var block: ClusterPlan.Runtime { + .init(nativeRuntimeSHA256: NativePairMemberPolicy.hex(nativeRuntime), + capabilitySHA256: NativePairMemberPolicy.hex(capability), + resourcePolicySHA256: NativePairMemberPolicy.hex(resourcePolicy), + profileSHA256: NativePairMemberPolicy.hex(profile)) + } + } let schedule: UInt8 let maximumFrame, maximumPlaintext: UInt32 let maximumRecords, maximumCumulative, notAfter: UInt64 /// A pair approval's qualified chips; empty for a cluster approval. let chips: [String] - /// A cluster approval's terms (`darkbloom/coordinator-cluster-runtime-approval/v1`); + /// A cluster approval's terms (`darkbloom/coordinator-cluster-runtime-approval/v1`, + /// or a model approval's `darkbloom/coordinator-cluster-model-approval/v1`); /// nil for a pair approval. let cluster: Cluster? struct Cluster: Sendable, Equatable { @@ -34,14 +67,23 @@ struct NativePairMemberPolicy: Sendable { } static let pairDomain = Data("darkbloom/coordinator-native-runtime-approval/v1\0".utf8) static let clusterDomain = Data("darkbloom/coordinator-cluster-runtime-approval/v1\0".utf8) + /// A cluster approval that pins no build (contract M2): the cluster layout + /// without the placement digest and the six runtime digests. + static let modelDomain = Data("darkbloom/coordinator-cluster-model-approval/v1\0".utf8) init(_ bytes: Data) throws { guard bytes.count <= 8192 else { throw NativePairMemberError.binding } var r = Reader(bytes) - let isCluster = bytes.starts(with: Self.clusterDomain) - try r.literal(isCluster ? Self.clusterDomain : Self.pairDomain) + let isModel = bytes.starts(with: Self.modelDomain) + let isCluster = isModel || bytes.starts(with: Self.clusterDomain) + try r.literal(isModel ? Self.modelDomain : isCluster ? Self.clusterDomain : Self.pairDomain) _ = try r.string(maximum: 128) // Policy ID is included in the exact digest. model = try r.string(maximum: 512); generation = try r.integer(UInt64.self) - hashes = try (0..<8).map { _ in try r.read(32) } + let hashes = try (0..<(isModel ? 1 : 8)).map { _ in try r.read(32) } + if isModel { + artifact = hashes[0]; pinnedPlan = nil; runtime = nil + } else { + pinnedPlan = hashes[0]; artifact = hashes[1]; runtime = Runtime(Array(hashes[2...])) + } try r.literal(Data([1, 1])); schedule = try r.integer(UInt8.self) maximumFrame = try r.integer(UInt32.self); maximumPlaintext = try r.integer(UInt32.self) maximumRecords = try r.integer(UInt64.self); maximumCumulative = try r.integer(UInt64.self) @@ -99,6 +141,15 @@ struct NativePairMemberPolicy: Sendable { return s } } + + static func hex(_ bytes: Data) -> String { bytes.map { String(format: "%02x", $0) }.joined() } + + /// The 32 bytes of a digest given as 64 lowercase hex characters; nil for anything else. + static func digest(hex text: String) -> Data? { + guard ClusterConfigurationSyntax.hash(text) else { return nil } + let digits = Array(text.utf8).map { $0 < 58 ? $0 - 48 : $0 - 87 } + return Data(stride(from: 0, to: 64, by: 2).map { digits[$0] << 4 | digits[$0 + 1] }) + } } enum NativePairMemberError: Error { case binding, deadline, inactive, queue, unconfigured } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift index 979b959b49..3f7512f5fd 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift @@ -29,9 +29,12 @@ public struct NativePairMemberRoster: Sendable, Equatable { /// tensor-parallel plan names no cut. `tensorShares`: the setup's unequal /// tensor-parallel shares, which this registration does not carry yet, so /// such a setup is refused rather than registered as an equal split. + /// `runtime`: the runtime block of a plan for a model approval, from this + /// member's own saved setup; nil for a build-pinned approval. public init(clusterID: String, rank: Int, roster: ClusterRoster, rankPins: [String], policyBytes: Data, model: String, artifactSHA256: String, planSHA256: String, cut: Int, mode: ClusterGenerationMode, - tensorShares: [Int]? = nil, deviceProfile: ClusterRegisteredDeviceProfile, edges: [ClusterEdge]) throws { + tensorShares: [Int]? = nil, deviceProfile: ClusterRegisteredDeviceProfile, edges: [ClusterEdge], + runtime: ClusterPlan.Runtime? = nil) throws { guard rankPins.count == 2, (0...1).contains(rank), cut > 0, let key = roster.memberKey(rankPins[1 - rank]), let peer = Data(base64Encoded: key), peer.count == 65 else { throw ClusterRosterError.invalidMembership @@ -40,7 +43,7 @@ public struct NativePairMemberRoster: Sendable, Equatable { let policy = Data(SHA256.hash(data: policyBytes)).map { String(format: "%02x", $0) }.joined() plan = ClusterPlan(policySHA256: policy, model: model, planSHA256: planSHA256, members: rankPins, cuts: mode.layerCutCount(ranks: rankPins.count) == 0 ? [] : [UInt32(cut)], - mode: mode == .pipeline ? nil : mode.rawValue) + mode: mode == .pipeline ? nil : mode.rawValue, runtime: runtime) membership = try ClusterMembership(rosterClusterID: clusterID, memberPin: rankPins[rank], roster: roster, deviceProfile: deviceProfile, edges: edges, inventory: [ClusterModelArtifact(model: model, artifactSHA256: artifactSHA256)], plans: [plan]) @@ -48,10 +51,8 @@ public struct NativePairMemberRoster: Sendable, Equatable { } /// The plan digest as the start carries it. - var planDigest: Data { - let digits = Array(plan.planSHA256.utf8).map { $0 < 58 ? $0 - 48 : $0 - 87 } - return Data(stride(from: 0, to: 64, by: 2).map { digits[$0] << 4 | digits[$0 + 1] }) - } + /// (The registration checked its syntax; empty bytes never match a start.) + var planDigest: Data { NativePairMemberPolicy.digest(hex: plan.planSHA256) ?? Data() } /// This rank's data-plane credential line for one committed start (S16): /// a fresh worker key certified by this member's Secure Enclave key, this diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift index e9e6d817af..e3ae3dc016 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledNativeStart.swift @@ -29,6 +29,16 @@ enum DistributedInstalledNativeStart { capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy]) } + /// The runtime block a member registers in its plan for a model + /// approval (contract M3) and requires of a start under it: its saved + /// setup's worker pin, capability, resource policy and profile. These are + /// the values a build-pinned approval for the same build names. + static func runtimeBlock(plan: DistributedInstalledPlan) -> ClusterPlan.Runtime { + .init(nativeRuntimeSHA256: plan.capability.runtimeBinarySHA256, capabilitySHA256: plan.configuration.capabilitySHA256, + resourcePolicySHA256: NativePairMemberPolicy.hex(resourcePolicySHA256(plan.capability)), + profileSHA256: plan.capability.profileFingerprint) + } + static func common(plan: DistributedInstalledPlan, epoch: UUID) throws -> ClusterNativeAuthorizationCommon { let configuration = plan.configuration, capability = plan.capability func bytes(_ hex: String) throws -> Data { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledOwner.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledOwner.swift index 6e0cf5a363..45c3eb9008 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledOwner.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/DistributedInstalledOwner.swift @@ -21,21 +21,23 @@ public enum DistributedInstalledOwner { /// The owner's own admission of a start the coordinator committed to this /// member: its own rank, and every digest, limit and generation of the - /// approval this Mac installed (the same check the member's session made - /// before it prepared). The epoch and the owner, lease and launch + /// approval this Mac installed, or under a model approval this Mac's own + /// setup's runtime (the same check the member's session made before it + /// prepared). The epoch and the owner, lease and launch /// identifiers are the coordinator's. static func memberAuthorizer(plan: DistributedInstalledPlan, attachment: ClusterNativeMemberAttachment) throws -> @Sendable (ClusterNativeAuthorizationStart) throws -> Void { let policy = try NativePairMemberPolicy(attachment.policyBytes), rank = plan.configuration.localRank // A cluster approval fixes no plan: the start must name the one this - // Mac's setup derives (and its member registered). - let digits = Array(plan.partition.planSHA256.utf8).map { $0 < 58 ? $0 - 48 : $0 - 87 } - let derived = Data(stride(from: 0, to: 64, by: 2).map { digits[$0] << 4 | digits[$0 + 1] }) + // Mac's setup derives (and its member registered). A model approval + // fixes no runtime: the start must name this Mac's setup's own. + let derived = NativePairMemberPolicy.digest(hex: plan.partition.planSHA256) ?? Data() + let runtime = DistributedInstalledNativeStart.runtimeBlock(plan: plan) return { start in guard start.rank == rank else { throw ClusterConfigurationError.invalid("The committed native start names another rank") } - do { try policy.require(start, plan: policy.cluster == nil ? nil : derived) } + do { try policy.require(start, plan: policy.cluster == nil ? nil : derived, runtime: runtime) } catch { throw ClusterConfigurationError.invalid("The committed native start differs from this Mac's installed approval") } } } 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 ef01949209..88efe3c940 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift @@ -5,16 +5,17 @@ import DarkbloomClusterSecurity /// One Mac's own half of saving a cluster approval. The Mac builds the roster registration (`nativeMember`, v2) from /// its own installation and its own pairing, checks the approval against them, and saves it in its own setup, or -/// saves the setup without one. Nothing another Mac or a file says is taken on trust: the approval's digests must be -/// this Mac's cluster runtime facts (`ClusterRuntimeApprovalFacts`, every digest of the release's block), the roster +/// 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. enum ClusterApprovalAttachment { - /// The block digests of `approval` that are not this Mac's facts, by their contract names; `model` when the facts - /// describe no entry for the approval's model. + /// 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. static func mismatches(_ approval: ClusterRuntimeApproval, facts: ClusterRuntimeApprovalFacts) -> [String] { guard let entry = facts.models.first(where: { $0.model == approval.model }) else { return ["model"] } - let pairs = [("native_runtime_sha256", approval.nativeRuntimeSHA256, facts.nativeRuntimeSHA256), + let pairs: [(String, String?, String)] = [("native_runtime_sha256", approval.nativeRuntimeSHA256, facts.nativeRuntimeSHA256), ("metallib_sha256", approval.metallibSHA256, facts.metallibSHA256), ("resource_library_sha256", approval.resourceLibrarySHA256, facts.resourceLibrarySHA256), ("placement_policy_sha256", approval.placementPolicySHA256, facts.placementPolicySHA256), @@ -95,13 +96,20 @@ enum ClusterApprovalAttachment { guard ClusterApprovalLifetime.current(approval, now: now) else { throw ClusterConfigurationError.invalid("the approval expired at \(approval.notAfter)") } - let installed: ClusterRuntimeApprovalFacts - do { installed = try facts(configuration) } catch { - throw ClusterConfigurationError.invalid("this Mac's cluster runtime could not be described: \(error)") - } - let differing = mismatches(approval, facts: installed) - guard differing.isEmpty else { - throw ClusterConfigurationError.invalid("the approval's \(differing.joined(separator: ", ")) differ from this Mac's installation") + if approval.isModelApproval { + // No build facts: the member's runtime is its own saved setup's, and a new build keeps the approval. + guard approval.artifactSHA256 == saved.capability.artifactSHA256 else { + throw ClusterConfigurationError.invalid("the approval's artifact_sha256 differs from this Mac's setup") + } + } else { + let installed: ClusterRuntimeApprovalFacts + do { installed = try facts(configuration) } catch { + throw ClusterConfigurationError.invalid("this Mac's cluster runtime could not be described: \(error)") + } + let differing = mismatches(approval, facts: installed) + guard differing.isEmpty else { + throw ClusterConfigurationError.invalid("the approval's \(differing.joined(separator: ", ")) differ from this Mac's installation") + } } // The member's own start refusals (`ClusterMemberPreparation.prepare`), from the metadata: a setup is never // saved for pairing when its member would refuse to start, which would leave the pair serving nowhere. @@ -122,8 +130,8 @@ 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, runtime, capability, - // profile and schedule, and the roster's pins are its members in rank order. + // 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) return attachment } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift index 4dccab2afb..dd13e3a81e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift @@ -2,8 +2,8 @@ import Foundation /// The cluster approvals the provider's coordinator serves (`GET /v1/cluster/approvals`): every unexpired entry of /// the coordinator operator's approval file, public build facts, so the request carries no credential. The answer -/// approves nothing by itself: the leader takes only an entry whose digests are this Mac's own cluster runtime facts, -/// and each Mac checks it against its own installed files before it saves it (`ClusterApprovalAttachment`). A +/// approves nothing by itself: the leader takes only an entry whose digests are this Mac's own cluster runtime facts +/// (or a model approval for its saved setup's model, schedule and artifact), and each Mac checks it against its own installed files before it saves it (`ClusterApprovalAttachment`). A /// coordinator without pair control answers 404, and every failure means "no approval": nothing here can stop a Mac /// from serving. public enum ClusterApprovalFetch { @@ -85,13 +85,14 @@ public enum ClusterApprovalFetch { } /// `{"schema":"darkbloom_cluster_catalog_v2","cluster_approvals":[…]}`, read as strictly as a saved setup reads - /// one entry: exact field names, nothing unknown or missing, and every entry must encode to coordinator policy - /// bytes (`ClusterRuntimeApproval.canonicalPolicy`). One bad entry refuses the whole answer. + /// one entry: the exact field names of one of the two shapes (build-pinned or a model approval, in any mix), + /// nothing unknown or missing, and every entry must encode to coordinator policy bytes + /// (`ClusterRuntimeApproval.canonicalPolicy`). One bad entry refuses the whole answer. static func decode(_ data: Data) throws -> [ClusterRuntimeApproval] { guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], Set(object.keys) == ["schema", "cluster_approvals"], object["schema"] as? String == schemaName, let entries = object["cluster_approvals"] as? [[String: Any]], entries.count <= maximumApprovals, - entries.allSatisfy({ Set($0.keys) == ClusterRuntimeApproval.fields }) else { + entries.allSatisfy({ ClusterRuntimeApproval.isEntry($0.keys) }) else { throw ClusterConfigurationError.invalid("The cluster approvals answer is not a \(schemaName) list") } struct List: Decodable { let clusterApprovals: [ClusterRuntimeApproval] diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift index f627e03ec1..1df66d958c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift @@ -32,14 +32,23 @@ public enum ClusterApprovalLifetime { /// The schedule number an approval names for a setup's prefill schedule (1 serial, 2 one-chunk lookahead). static func schedule(_ value: ClusterPrefillSchedule) -> UInt8 { value == .serial ? 1 : 2 } - /// The entry for this setup: its model and its prefill schedule, all eight digests this Mac's own cluster runtime - /// facts (`ClusterApprovalAttachment.mismatches`), still current, the latest `not_after` first. An entry for - /// another build or another copy of the model is simply not this setup's. + /// The entry for this setup: its model and its prefill schedule, still current, the latest `not_after` first, and + /// either a model approval for the saved setup's own `artifact` (`capability.artifactSHA256`), or a build-pinned + /// entry whose eight digests are this Mac's own cluster runtime facts (`ClusterApprovalAttachment.mismatches`). An + /// entry for another build or another copy of the model is simply not this setup's. `facts` runs at most once, + /// and only for a build-pinned entry of this model and schedule: a model approval needs no facts (nil: they could + /// not be computed, so no build-pinned entry is this setup's). static func select(_ approvals: [ClusterRuntimeApproval], model: String, schedule: ClusterPrefillSchedule, - facts: ClusterRuntimeApprovalFacts, now: Double) -> ClusterRuntimeApproval? { - approvals.filter { - $0.model == model && $0.schedule == Self.schedule(schedule) && current($0, now: now) - && ClusterApprovalAttachment.mismatches($0, facts: facts).isEmpty + artifact: String, facts: () -> ClusterRuntimeApprovalFacts?, now: Double) -> ClusterRuntimeApproval? { + var computed: ClusterRuntimeApprovalFacts?? + return approvals.filter { approval in + guard approval.model == model, approval.schedule == Self.schedule(schedule), current(approval, now: now) else { + return false + } + if approval.isModelApproval { return approval.artifactSHA256 == artifact } + if computed == nil { computed = .some(facts()) } + guard let installed = computed ?? nil else { return false } + return ClusterApprovalAttachment.mismatches(approval, facts: installed).isEmpty }.max { (expiry($0) ?? 0) < (expiry($1) ?? 0) } } @@ -57,11 +66,12 @@ public enum ClusterApprovalLifetime { } /// What to do with the setup's saved approval (`saved`, nil for none) after asking the coordinator (`fetched`). - /// Only a list (200) or 404 says anything about the saved approval; any other outcome keeps it. `facts` are this - /// Mac's own cluster runtime facts for the setup's model; they are computed only when an entry must be chosen - /// (nil: they could not be, so no entry is this setup's). + /// Only a list (200) or 404 says anything about the saved approval; any other outcome keeps it. `artifact` is the + /// saved setup's artifact; `facts` are this Mac's own cluster runtime facts for the setup's model, computed only + /// when a build-pinned entry must be checked (`select`). static func decide(saved: ClusterRuntimeApproval?, fetched: ClusterApprovalFetch.Outcome, model: String, - schedule: ClusterPrefillSchedule, facts: () -> ClusterRuntimeApprovalFacts?, now: Double) -> Decision { + schedule: ClusterPrefillSchedule, artifact: String, facts: () -> ClusterRuntimeApprovalFacts?, + now: Double) -> Decision { let listed: [ClusterRuntimeApproval]? switch fetched { case .approvals(let approvals): listed = approvals @@ -69,8 +79,8 @@ public enum ClusterApprovalLifetime { case .unavailable, .unreachable: listed = nil } func candidate() -> ClusterRuntimeApproval? { - guard let listed, !listed.isEmpty, let facts = facts() else { return nil } - return select(listed, model: model, schedule: schedule, facts: facts, now: now) + guard let listed, !listed.isEmpty else { return nil } + return select(listed, model: model, schedule: schedule, artifact: artifact, facts: facts, now: now) } guard let saved else { return candidate().map(Decision.save) ?? .keep } let savedEnd = expiry(saved) ?? 0 diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift index db9acd072c..56708dcc8b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift @@ -5,7 +5,7 @@ import DarkbloomClusterSecurity /// The control leader's step that keeps both Macs' setups on the same cluster approval: after the guided setup's Test /// stage passed, once at each start of its cluster service and after an update re-adopted the setups, and every /// minute while the pair is offered. The leader asks its coordinator, takes the entry whose digests are its own -/// facts, sends it to the other Mac over the cable (which checks it against its own files and saves it, or refuses), +/// facts (or a model approval for its setup's model, schedule and artifact, which a new build does not change), sends it to the other Mac over the cable (which checks it against its own files and saves it, or refuses), /// and saves it itself only after the other Mac did. Both Macs so carry the approval, or neither does. A coordinator /// that serves none (404, no matching entry, any failure) changes nothing. public enum ClusterApprovalSync { @@ -33,7 +33,7 @@ public enum ClusterApprovalSync { } /// What the step would do with this saved setup and this answer. `facts` describes this Mac's installed app for - /// the setup's model; it runs only when an entry must be chosen. + /// the setup's model; it runs only when a build-pinned entry must be checked, never for a model approval. static func decision(saved: ClusterConfigurationStore.Saved, fetched: ClusterApprovalFetch.Outcome, now: Double, facts: (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts) -> ClusterApprovalLifetime.Decision { let configuration = saved.configuration @@ -41,7 +41,7 @@ public enum ClusterApprovalSync { guard configuration.nativeMember?.approval == nil else { return .keep } return ClusterApprovalLifetime.decide(saved: configuration.nativeMember?.clusterApproval, fetched: fetched, model: configuration.publicModelID, schedule: configuration.selectedPrefillSchedule, - facts: { try? facts(configuration) }, now: now) + artifact: saved.capability.artifactSHA256, facts: { try? facts(configuration) }, now: now) } /// `ClusterApprovalCheck.Step.serveLocally`: the other Mac saves its setup without the approval first, then this diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift index 1138643a60..7d2f48f5de 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift @@ -100,6 +100,10 @@ public struct ClusterMemberPreparation: Sendable { /// registers the roster registration instead: `device` gives this Mac's /// device profile v2 for the approval's metallib, and the plan is derived from the setup's selected /// partition and rank order, so both members register the same plan. + /// Under a model approval, which pins no build, the metallib digest is the + /// one this Mac takes of its installed metallib here (with its resource + /// library's, which the start checks again), and the plan carries this + /// setup's own runtime block (`DistributedInstalledNativeStart.runtimeBlock`). public func nativeMemberInstallation(chip: String, device: ((_ metallibSHA256: String) throws -> ClusterRegisteredDeviceProfile)? = nil) throws -> NativePairMemberInstallation? { let plan = validation.plan @@ -109,6 +113,17 @@ public struct ClusterMemberPreparation: Sendable { guard Date().timeIntervalSince1970 * 1_000_000_000 < Double(policy.notAfter) else { throw ClusterConfigurationError.invalid("Saved pair approval has expired") } + // A model approval pins no files: hash this Mac's own once, here. + var installedDigests: (metallib: String, resourceLibrary: String)? + if policy.runtime == nil { + let deadline = DispatchTime.now().uptimeNanoseconds + 15_000_000_000 + func digest(_ path: String) throws -> String { + try DistributedInstalledFiles.digest(URL(fileURLWithPath: path), maximumBytes: 256 * 1024 * 1024, + deadline: deadline).sha256 + } + installedDigests = (try digest(attachment.metallibPath), try digest(attachment.resourceLibraryPath)) + } + let metallibSHA256 = installedDigests?.metallib ?? policy.runtime.map { NativePairMemberPolicy.hex($0.metallib) } ?? "" var roster: NativePairMemberRoster? if attachment.isRoster, let saved = attachment.roster, let pins = attachment.memberPins { guard let device else { throw ClusterConfigurationError.invalid("A roster registration needs this Mac's device profile") } @@ -131,7 +146,8 @@ public struct ClusterMemberPreparation: Sendable { artifactSHA256: plan.identity(epoch: UUID()).artifactSHA256, planSHA256: plan.partition.planSHA256, cut: plan.partition.stages[0].sourceLayerEnd, mode: configuration.selectedGenerationMode, tensorShares: configuration.tensorShares, - deviceProfile: try device(NativePairMemberInstallation.hex(policy.hashes[3])), edges: attachment.edges ?? []) + deviceProfile: try device(metallibSHA256), edges: attachment.edges ?? [], + runtime: installedDigests == nil ? nil : DistributedInstalledNativeStart.runtimeBlock(plan: plan)) } catch { throw ClusterConfigurationError.invalid("The saved roster registration is not valid for this Mac: \(error)") } @@ -143,7 +159,8 @@ public struct ClusterMemberPreparation: Sendable { nativeExecutable: URL(fileURLWithPath: plan.localPeer.workerExecutable), metallib: URL(fileURLWithPath: attachment.metallibPath), resourceLibrary: URL(fileURLWithPath: attachment.resourceLibraryPath), chip: chip, - meshOverLink: plan.configuration.linkControl != nil, roster: roster, batchLanes: plan.batchLanes()) else { + meshOverLink: plan.configuration.linkControl != nil, roster: roster, batchLanes: plan.batchLanes(), + installedDigests: installedDigests) else { throw ClusterConfigurationError.invalid(roster == nil ? "Saved pair approval does not cover this Mac's chip, artifact or native build" : "Saved cluster approval does not cover this Mac's numerics class, usable memory, artifact or native build") diff --git a/provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift b/provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift index a5ca604c56..8060bf725e 100644 --- a/provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift +++ b/provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift @@ -256,6 +256,35 @@ public struct ClusterPlan: Codable, Sendable, Equatable { /// The planner's speed estimate for one request alone on the cluster; /// omitted when it has none. Also part of the placement. public let prediction: Prediction? + /// The runtime every member of a plan for a model approval runs, from + /// each member's own saved setup; omitted in a plan for a build-pinned + /// approval, which pins the runtime itself. Part of the plan: every member + /// registers the same block, so all members agree on the runtime. + public let runtime: Runtime? + + /// A plan's runtime block (`runtime`, contract M3): the four runtime digests a + /// session's start carries, each 64 lowercase hex characters, not zero. + public struct Runtime: Codable, Sendable, Equatable { + public let nativeRuntimeSHA256: String + public let capabilitySHA256: String + public let resourcePolicySHA256: String + public let profileSHA256: String + enum CodingKeys: String, CodingKey { + case nativeRuntimeSHA256 = "native_runtime_sha256" + case capabilitySHA256 = "capability_sha256" + case resourcePolicySHA256 = "resource_policy_sha256" + case profileSHA256 = "profile_sha256" + } + public init(nativeRuntimeSHA256: String, capabilitySHA256: String, resourcePolicySHA256: String, profileSHA256: String) { + self.nativeRuntimeSHA256 = nativeRuntimeSHA256; self.capabilitySHA256 = capabilitySHA256 + self.resourcePolicySHA256 = resourcePolicySHA256; self.profileSHA256 = profileSHA256 + } + func validate() throws { + let zero = String(repeating: "0", count: 64) + guard [nativeRuntimeSHA256, capabilitySHA256, resourcePolicySHA256, profileSHA256] + .allSatisfy({ ClusterConfigurationSyntax.hash($0) && $0 != zero }) else { throw ClusterRosterError.invalidPlan } + } + } /// `protocol.ClusterPlanPrediction`. public struct Prediction: Codable, Sendable, Equatable { @@ -296,13 +325,13 @@ public struct ClusterPlan: Codable, Sendable, Equatable { case policySHA256 = "policy_sha256" case model case planSHA256 = "plan_sha256" - case members, cuts, mode, prediction + case members, cuts, mode, prediction, runtime } public init(policySHA256: String, model: String, planSHA256: String, members: [String], cuts: [UInt32], - mode: String? = nil, prediction: Prediction? = nil) { + mode: String? = nil, prediction: Prediction? = nil, runtime: Runtime? = nil) { self.policySHA256 = policySHA256; self.model = model; self.planSHA256 = planSHA256 - self.members = members; self.cuts = cuts; self.mode = mode; self.prediction = prediction + self.members = members; self.cuts = cuts; self.mode = mode; self.prediction = prediction; self.runtime = runtime } /// The plan's generation mode, the pipeline when omitted. @@ -312,7 +341,7 @@ public struct ClusterPlan: Codable, Sendable, Equatable { public func samePlacement(as other: ClusterPlan) -> Bool { policySHA256 == other.policySHA256 && model == other.model && planSHA256 == other.planSHA256 && members == other.members && cuts == other.cuts && effectiveMode == other.effectiveMode - && prediction == other.prediction + && prediction == other.prediction && runtime == other.runtime } func validate(roster: ClusterRoster) throws { @@ -326,6 +355,7 @@ public struct ClusterPlan: Codable, Sendable, Equatable { throw ClusterRosterError.invalidPlan } try prediction?.validate() + try runtime?.validate() } } diff --git a/provider-swift/Tests/ProviderCoreTests/Config/ClusterModelApprovalTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/ClusterModelApprovalTests.swift new file mode 100644 index 0000000000..0d235f2a6d --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Config/ClusterModelApprovalTests.swift @@ -0,0 +1,160 @@ +import CryptoKit +import Foundation +import Testing +@testable import ProviderCore + +/// A cluster approval that pins no build (a model approval): its two entry shapes, its canonical bytes under +/// `darkbloom/coordinator-cluster-model-approval/v1`, and the member's strict reader of those bytes. The golden +/// vectors are the ones the coordinator's encoder pins for the same inputs. +@Suite("Cluster model approval") +struct ClusterModelApprovalTests { + static let artifact = SHA256.hash(data: Data("artifact".utf8)).map { String(format: "%02x", $0) }.joined() + + /// The golden inputs: 14 fields, no runtime digest. + static func entry(classes: [String] = [], changes: [String: Any] = [:]) -> [String: Any] { + var value: [String: Any] = ["id": "devnet/fixture-model/s1", "model": "fixture-model", "generation": 1, + "artifact_sha256": artifact, "schedule": 1, "maximum_transport_frame": 1_048_616, "maximum_plaintext": 1_048_576, + "maximum_records": 1_048_576, "maximum_cumulative_plaintext": 4_294_967_296, "allowed_numerics_classes": classes, + "minimum_members": 2, "maximum_members": 2, "minimum_member_usable_bytes": 1, "not_after": "2026-11-13T10:44:04Z"] + changes.forEach { value[$0] = $1 } + return value + } + + /// The same entry pinned to one build: the seven runtime digests added. + static func pinned() -> [String: Any] { + var value = entry() + for (index, key) in ClusterRuntimeApproval.runtimeKeys.enumerated() { + value[key.rawValue] = String(repeating: String(format: "%02x", index + 1), count: 32) + } + return value + } + + static func approval(_ object: [String: Any]) throws -> ClusterRuntimeApproval { + try JSONDecoder().decode(ClusterRuntimeApproval.self, from: JSONSerialization.data(withJSONObject: object)) + } + + @Test func canonicalBytesAreTheGoldenVectors() throws { + let first = try Self.approval(Self.entry()).canonicalPolicy() + #expect(first.count == 205) + #expect(ClusterConfigurationCodec.sha256(first) == "58aee08d621431662b7fd667538e59ea8be1af98087e783a3add313cee17799b") + #expect(memberHex(first) == "6461726b626c6f6f6d2f636f6f7264696e61746f722d636c75737465722d6d6f64656c2d617070726f76616c2f763100000000176465766e65742f666978747572652d6d6f64656c2f73310000000d666978747572652d6d6f64656c0000000000000001c7c5c1d70c5dec4416ab6158afd0b223ef40c29b1dc1f97ed9428b94d4cadb1c01010100100028001000000000000000100000000000010000000018e794dacd6288000202000000000000000100000009502f90000000001bf08eb00000000014f46b040000000000") + let second = try Self.approval(Self.entry(classes: ["apple-m5-nax0", "apple-m5-nax1"])).canonicalPolicy() + #expect(second.count == 239) + #expect(ClusterConfigurationCodec.sha256(second) == "368372b60ed1615eb14b7f32951c486104dcedf6c7b88c0e1b0805d97e914bf8") + // The same terms pinned to a build keep the build-pinned domain and layout. + let build = try Self.approval(Self.pinned()).canonicalPolicy() + #expect(build.starts(with: NativePairMemberPolicy.clusterDomain) && build.count == first.count + 7 * 32 + 2) + } + + @Test func theMemberReaderReadsTheModelDomain() throws { + let policy = try NativePairMemberPolicy(try Self.approval(Self.entry(classes: ["apple-m5-nax0"])).canonicalPolicy()) + #expect(policy.model == "fixture-model" && policy.generation == 1 && policy.schedule == 1) + #expect(memberHex(policy.artifact) == Self.artifact) + #expect(policy.pinnedPlan == nil && policy.runtime == nil && policy.chips.isEmpty) + let terms = try #require(policy.cluster) + #expect(terms.minimumMembers == 2 && terms.maximumMembers == 2 && terms.minimumMemberUsableBytes == 1) + #expect(terms.leaseTermsNanoseconds == ClusterRuntimeApproval.leaseTermsNanoseconds) + #expect(terms.numericsClasses == ["apple-m5-nax0"]) + #expect(policy.maximumFrame == 1_048_616 && policy.maximumPlaintext == 1_048_576) + #expect(policy.maximumRecords == 1_048_576 && policy.maximumCumulative == 4_294_967_296) + #expect(policy.notAfter == ClusterPairApproval.unixNanoseconds(rfc3339: "2026-11-13T10:44:04Z")) + // A build-pinned entry still reads all of its digests by name. + let build = try NativePairMemberPolicy(try Self.approval(Self.pinned()).canonicalPolicy()) + #expect(build.pinnedPlan.map(memberHex) == String(repeating: "01", count: 32)) + #expect(build.runtime.map { memberHex($0.profile) } == String(repeating: "07", count: 32)) + } + + @Test func theReaderRefusesTrailingTruncatedSwappedAndZeroBytes() throws { + let bytes = try Self.approval(Self.entry()).canonicalPolicy() + let artifactOffset = NativePairMemberPolicy.modelDomain.count + 4 + 23 + 4 + 13 + 8 + #expect(bytes.subdata(in: artifactOffset..<(artifactOffset + 32)) == memberDigest("artifact")) + var zeroArtifact = bytes; zeroArtifact.replaceSubrange(artifactOffset..<(artifactOffset + 32), with: Data(count: 32)) + var modelUnderCluster = bytes + modelUnderCluster.replaceSubrange(0.. [String: Any] { + ["schema": ClusterNativeMemberAttachment.rosterSchemaName, "ownerSHA256": String(repeating: "1", count: 64), + "metallibPath": "/fixture/mlx.metallib", "resourceLibraryPath": "/fixture/resource.metallib", + "clusterApproval": approval, "roster": [String: Any](), "memberPins": [String]()] + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Config/ClusterPairApprovalTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/ClusterPairApprovalTests.swift index 3cedbf39fd..e3d54f62cc 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/ClusterPairApprovalTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/ClusterPairApprovalTests.swift @@ -49,8 +49,10 @@ struct ClusterPairApprovalTests { notAfter: "2027-01-02T03:04:05Z", schedule: 2, generation: 3)) let policy = try NativePairMemberPolicy(approval.canonicalPolicy()) #expect(policy.model == "fixture/pair-model" && policy.generation == 3 && policy.schedule == 2) - #expect(policy.hashes.map(memberHex) == ["plan", "artifact", "native", "metallib", "resources", - "capability", "resource-policy", "profile"].map(Self.digest)) + let runtime = try #require(policy.runtime) + #expect([try #require(policy.pinnedPlan), policy.artifact, runtime.nativeRuntime, runtime.metallib, + runtime.resourceLibrary, runtime.capability, runtime.resourcePolicy, runtime.profile].map(memberHex) + == ["plan", "artifact", "native", "metallib", "resources", "capability", "resource-policy", "profile"].map(Self.digest)) #expect(policy.maximumFrame == 131_112 && policy.maximumPlaintext == 131_072) #expect(policy.maximumRecords == 1024 && policy.maximumCumulative == 16_777_216) #expect(policy.chips == ["Apple M4 Max", "Apple M4 Pro"]) diff --git a/provider-swift/Tests/ProviderCoreTests/Coordinator/NativePairMember/ClusterRosterMemberTests.swift b/provider-swift/Tests/ProviderCoreTests/Coordinator/NativePairMember/ClusterRosterMemberTests.swift index 0eae96550a..8c796615e1 100644 --- a/provider-swift/Tests/ProviderCoreTests/Coordinator/NativePairMember/ClusterRosterMemberTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Coordinator/NativePairMember/ClusterRosterMemberTests.swift @@ -57,13 +57,147 @@ struct ClusterRosterMemberTests { return (roster, signers) } + /// The same model and terms as `approval()`, pinned to no build (a model approval). + static func modelApproval() -> ClusterRuntimeApproval { + let pinned = approval() + return ClusterRuntimeApproval(id: "devnet/qwen35-9b/s1", model: pinned.model, generation: pinned.generation, + placementPolicySHA256: nil, artifactSHA256: pinned.artifactSHA256, nativeRuntimeSHA256: nil, metallibSHA256: nil, + resourceLibrarySHA256: nil, capabilitySHA256: nil, resourcePolicySHA256: nil, profileSHA256: nil, + schedule: pinned.schedule, maximumTransportFrame: pinned.maximumTransportFrame, maximumPlaintext: pinned.maximumPlaintext, + maximumRecords: pinned.maximumRecords, maximumCumulativePlaintext: pinned.maximumCumulativePlaintext, + allowedNumericsClasses: classes, minimumMembers: 2, maximumMembers: 2, + minimumMemberUsableBytes: pinned.minimumMemberUsableBytes, notAfter: pinned.notAfter) + } + private func registration(_ roster: ClusterRoster, pins: [String], rank: Int, profile: ClusterRegisteredDeviceProfile, - mode: ClusterGenerationMode = .pipeline, tensorShares: [Int]? = nil) throws -> NativePairMemberRoster { + mode: ClusterGenerationMode = .pipeline, tensorShares: [Int]? = nil, + policyBytes: Data? = nil, runtime: ClusterPlan.Runtime? = nil) throws -> NativePairMemberRoster { try NativePairMemberRoster(clusterID: "pub-pair", rank: rank, roster: roster, rankPins: pins, - policyBytes: try Self.approval().canonicalPolicy(), model: "mlx-community/Qwen3.5-9B", + policyBytes: try policyBytes ?? Self.approval().canonicalPolicy(), model: "mlx-community/Qwen3.5-9B", artifactSHA256: String(repeating: "02", count: 32), planSHA256: String(repeating: "ab", count: 32), cut: 16, mode: mode, tensorShares: tensorShares, deviceProfile: profile, - edges: [ClusterEdge(peerPin: pins[1 - rank], transport: "rdma", measuredMbps: 80_000, measuredRTTMicros: 20)]) + edges: [ClusterEdge(peerPin: pins[1 - rank], transport: "rdma", measuredMbps: 80_000, measuredRTTMicros: 20)], + runtime: runtime) + } + + /// The runtime block a member's own setup gives (its worker pin, capability, resource policy and profile). + static func block(worker: String, capability: String = String(repeating: "06", count: 32)) -> ClusterPlan.Runtime { + .init(nativeRuntimeSHA256: worker, capabilitySHA256: capability, + resourcePolicySHA256: String(repeating: "07", count: 32), profileSHA256: String(repeating: "08", count: 32)) + } + + /// Under a model approval each member registers its plan with its own runtime block; under a build-pinned + /// approval the plan names none. The block is part of the plan both members must register byte for byte. + @Test func aModelApprovalsPlanCarriesTheMembersRuntimeBlock() throws { + let (roster, signers) = try members() + let pins = signers.map(\.pin) + let profile = try ClusterRegisteredDeviceProfile(chipName: "Apple M3 Ultra", numericsClass: Self.classes[0], gpuCores: 80, + memoryBytes: 256 << 30, usableWiredBytes: 200 << 30, osBuild: "25C56") + let policy = try Self.modelApproval().canonicalPolicy(), block = Self.block(worker: String(repeating: "03", count: 32)) + let r0 = try registration(roster, pins: pins, rank: 0, profile: profile, policyBytes: policy, runtime: block) + let r1 = try registration(roster, pins: pins, rank: 1, profile: profile, policyBytes: policy, runtime: block) + #expect(r0.plan.runtime == block && r0.plan.samePlacement(as: r1.plan)) + #expect(r0.plan.policySHA256 == ClusterConfigurationCodec.sha256(policy)) + let wire = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(r0.membership)) as? [String: Any]) + let plan = try #require((wire["plans"] as? [[String: Any]])?.first) + #expect((plan["runtime"] as? [String: String]) == ["native_runtime_sha256": block.nativeRuntimeSHA256, + "capability_sha256": block.capabilitySHA256, "resource_policy_sha256": block.resourcePolicySHA256, + "profile_sha256": block.profileSHA256]) + #expect(try JSONDecoder().decode(ClusterMembership.self, from: JSONEncoder().encode(r0.membership)) == r0.membership) + // Another member's runtime is another plan. + let other = try registration(roster, pins: pins, rank: 1, profile: profile, policyBytes: policy, + runtime: Self.block(worker: String(repeating: "09", count: 32))) + #expect(!r0.plan.samePlacement(as: other.plan)) + // A block whose digest is not 64 lowercase hex characters, or is zero, is refused. + for bad in [Self.block(worker: String(repeating: "0", count: 64)), Self.block(worker: "AB"), + Self.block(worker: String(repeating: "03", count: 32), capability: String(repeating: "A", count: 64))] { + #expect(throws: ClusterRosterError.invalidPlan) { + _ = try registration(roster, pins: pins, rank: 0, profile: profile, policyBytes: policy, runtime: bad) + } + } + // A build-pinned approval's plan carries no block, and its wire form names none. + let pinned = try registration(roster, pins: pins, rank: 0, profile: profile) + #expect(pinned.plan.runtime == nil) + let pinnedWire = try #require(try JSONSerialization.jsonObject(with: JSONEncoder().encode(pinned.membership)) as? [String: Any]) + #expect((pinnedWire["plans"] as? [[String: Any]])?.first?["runtime"] == nil) + } + + /// A member under a model approval: its installation takes the runtime from its own plan block and the digests it + /// took of its own files, a start must carry exactly that runtime, and its files must hash to it. + @Test func aMemberStartsUnderAModelApprovalOnlyWithItsOwnRuntime() throws { + let (roster, signers) = try members() + let pins = signers.map(\.pin) + let root = try NativePairMemberFixture.privateRoot() + defer { try? FileManager.default.removeItem(at: root) } + func file(_ name: String, _ text: String, mode: Int) throws -> URL { + let url = root.appendingPathComponent(name) + try Data(text.utf8).write(to: url, options: .withoutOverwriting) + try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: url.path) + return url + } + func sha256(_ url: URL) throws -> String { memberHex(Data(SHA256.hash(data: try Data(contentsOf: url)))) } + let owner = try file("owner", "model-approval-owner", mode: 0o700), worker = try file("worker", "model-approval-worker", mode: 0o700) + let metallib = try file("mlx.metallib", "model-approval-metallib", mode: 0o600) + let resource = try file("pagedattention.metal", "model-approval-resource", mode: 0o600) + let gate = root.appendingPathComponent(".darkbloom/cluster-device") + try FileManager.default.createDirectory(at: gate, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let profile = try ClusterRegisteredDeviceProfile(chipName: "Apple M3 Ultra", numericsClass: Self.classes[0], gpuCores: 80, + memoryBytes: 256 << 30, usableWiredBytes: 200 << 30, osBuild: "25C56") + let policy = try Self.modelApproval().canonicalPolicy(), block = Self.block(worker: try sha256(worker)) + let files = (metallib: try sha256(metallib), resourceLibrary: try sha256(resource)) + let identity = ClusterWorkerIdentity(membershipEpoch: UUID(), modelID: "fixture-model", + artifactSHA256: String(repeating: "02", count: 32), configurationSHA256: memberHex(memberDigest("fixture-config")), + peers: (0..<2).map { ClusterWorkerPeer(id: "peer-\($0)", buildSHA256: block.nativeRuntimeSHA256) }) + let workerProfile = ClusterWorkerProfile(id: "fixture-profile", vocabularySize: 1000, + maximumPromptTokens: 128, maximumOutputTokens: 128, maximumChunkTokens: 64, maximumContextTokens: 512) + func installation(_ policy: Data, _ runtime: ClusterPlan.Runtime?, + _ digests: (metallib: String, resourceLibrary: String)?) throws -> NativePairMemberInstallation { + try NativePairMemberInstallation(expectedCoordinatorPolicy: policy, rank: 0, clusterID: "pub-pair", + identity: identity, profile: workerProfile, installedOwner: owner, ownerSHA256: try sha256(owner), + nativeExecutable: worker, metallib: metallib, resourceLibrary: resource, chip: "Apple M3 Ultra", + leaseDirectory: gate, roster: try registration(roster, pins: pins, rank: 0, profile: profile, policyBytes: policy, + runtime: runtime), + installedDigests: digests) + } + let member = try installation(policy, block, files) + #expect(member.policy.runtime == nil && member.runtime.block == block) + #expect(memberHex(member.runtime.metallib) == files.metallib && memberHex(member.runtime.resourceLibrary) == files.resourceLibrary) + func start(_ change: (inout [Data]) -> Void = { _ in }) throws -> ClusterNativeAuthorizationStart { + // Worker, capability, resource policy and profile, as the coordinator copies them from the agreed plan. + var runtime = try [block.nativeRuntimeSHA256, block.capabilitySHA256, block.resourcePolicySHA256, + block.profileSHA256].map { try #require(NativePairMemberPolicy.digest(hex: $0)) } + change(&runtime) + let common = try ClusterNativeAuthorizationCommon(epoch: UUID(), membershipGeneration: 7, nativePolicyGeneration: 3, + membershipTranscriptSHA256: memberDigest("model-approval-membership"), + approvedNativeBindingSHA256: Data(SHA256.hash(data: policy)), planSHA256: try #require(member.roster).planDigest, + artifactSHA256: Data(repeating: 2, count: 32), nativeRuntimeSHA256: runtime[0], capabilitySHA256: runtime[1], + resourcePolicySHA256: runtime[2], profileSHA256: runtime[3], schedule: .serial, maximumTransportFrameBytes: 1_048_616, + limits: .init(maximumPlaintextBytes: 1_048_576, maximumRecordsPerDirection: 1_048_576, + maximumCumulativePlaintextBytesPerDirection: 4_294_967_296)) + return try .init(common: common, rank: 0, ownerIncarnation: UUID(), leaseID: UUID(), launchID: UUID()) + } + // Its own runtime: admitted, and its files hash to it. + let deadline = DispatchTime.now().uptimeNanoseconds + 15_000_000_000 + #expect(try member.prepare(start: try start(), deadline: deadline).count == 4) + // Any one runtime digest that is not its own is refused. + for index in 0..<4 { + let other = try start { $0[index] = memberDigest("another-runtime-\(index)") } + #expect(throws: NativePairMemberError.binding, "runtime digest \(index)") { try member.requireStart(other) } + } + // A file that differs from the digest it took is refused at prepare. + let changed = try installation(policy, block, (metallib: memberHex(memberDigest("another-metallib")), resourceLibrary: files.resourceLibrary)) + #expect(throws: ClusterConfigurationError.self) { _ = try changed.prepare(start: try start(), deadline: deadline) } + // A model approval needs the plan's block and the member's own file digests; a build-pinned one refuses a block. + #expect(throws: NativePairMemberError.binding) { _ = try installation(policy, nil, files) } + #expect(throws: NativePairMemberError.binding) { _ = try installation(policy, block, nil) } + #expect(throws: NativePairMemberError.binding) { + _ = try installation(policy, block, (metallib: "AB", resourceLibrary: files.resourceLibrary)) + } + // A block whose worker is not the setup's pin (the identity's build) is refused. + #expect(throws: NativePairMemberError.binding) { + _ = try installation(policy, Self.block(worker: String(repeating: "09", count: 32)), files) + } + #expect(throws: NativePairMemberError.binding) { _ = try installation(try Self.approval().canonicalPolicy(), block, files) } } @Test func bothMembersRegisterOneRosterAndOnePlan() throws { diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFetchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFetchTests.swift index 275547f811..8aa39b4327 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFetchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFetchTests.swift @@ -14,7 +14,7 @@ struct ClusterApprovalFetchTests { private func approvals() throws -> [ClusterRuntimeApproval] { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") - return [macs.approval(schedule: 1), macs.approval(schedule: 2)] + return [macs.approval(schedule: 1), macs.approval(schedule: 2), macs.modelApproval()] } @Test func aStrictListIsTakenAndTheRequestHasNoQuery() async throws { @@ -34,7 +34,8 @@ struct ClusterApprovalFetchTests { @Test func everyOtherAnswerIsNoApproval() async throws { let (mock, url) = try await coordinator() - let entry = try JSONSerialization.jsonObject(with: JSONEncoder().encode(try approvals()[0])) as! [String: Any] + let all = try approvals() + let entry = try JSONSerialization.jsonObject(with: JSONEncoder().encode(all[0])) as! [String: Any] func list(_ entries: [[String: Any]], schema: String = ClusterApprovalFetch.schemaName, extra: [String: Any] = [:]) throws -> Data { var object: [String: Any] = ["schema": schema, "cluster_approvals": entries] extra.forEach { object[$0] = $1 } @@ -44,6 +45,13 @@ struct ClusterApprovalFetchTests { var missing = entry; missing.removeValue(forKey: "resource_policy_sha256") var badDigest = entry; badDigest["metallib_sha256"] = "ABC" var badExpiry = entry; badExpiry["not_after"] = "in two weeks" + // A model approval (no runtime digests) with one runtime digest, or without one of its own fields; a + // build-pinned entry whose runtime digests are null. + let model = try JSONSerialization.jsonObject(with: JSONEncoder().encode(all[2])) as! [String: Any] + var partial = model; partial["native_runtime_sha256"] = entry["native_runtime_sha256"] + var modelMissing = model; modelMissing.removeValue(forKey: "allowed_numerics_classes") + var nulls = entry + for key in ClusterRuntimeApproval.runtimeKeys { nulls[key.rawValue] = NSNull() } let refused: [(String, Int, Data, String?)] = [ ("a server error", 500, Data("{}".utf8), nil), ("a redirect", 302, Data(), "https://elsewhere.invalid/v1/cluster/approvals"), @@ -54,6 +62,9 @@ struct ClusterApprovalFetchTests { ("a missing entry field", 200, try list([missing]), nil), ("a malformed digest", 200, try list([badDigest]), nil), ("a malformed not_after", 200, try list([badExpiry]), nil), + ("a model approval with one runtime digest", 200, try list([model, partial]), nil), + ("a model approval without its numerics classes", 200, try list([entry, modelMissing]), nil), + ("a build-pinned entry with null runtime digests", 200, try list([nulls]), nil), ("too many entries", 200, try list(Array(repeating: entry, count: ClusterApprovalFetch.maximumApprovals + 1)), nil), ("an answer over its bound", 200, Data(repeating: 32, count: ClusterApprovalFetch.maximumBytes + 1), nil), ] diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift index 0a13131a36..fa28745c52 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalFixture.swift @@ -30,27 +30,21 @@ final class ClusterApprovalMacs: @unchecked Sendable { static let chip = ClusterChipClass(chipName: "Apple M3 Ultra") let root: URL - let capability: ClusterRuntimeCapability - let capabilitySHA256: String + /// 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 let macs: [Mac] + private let records: [ClusterPairingRecord] var leader: Mac { macs[0] } var follower: Mac { macs[1] } /// `coordinatorURL`: the coordinator both provider configurations name. init(coordinatorURL: String) throws { - let h = Self.hash let base = try NativePairMemberFixture.privateRoot() root = base - let profile = ClusterWorkerProfile(id: "registered_qwen35_9b_greedy_generation_v1", vocabularySize: 248320, - maximumPromptTokens: 8192, maximumOutputTokens: 128, maximumChunkTokens: 512, maximumContextTokens: 8320) - capability = try ClusterRuntimeCapability(runtimeBinarySHA256: h("a"), 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")) - let capabilityData = try ClusterRuntimeCapabilityCodec.encode(capability) - capabilitySHA256 = ClusterConfigurationCodec.sha256(capabilityData) + let installed = try Self.capability(runtime: Self.hash("a")) + capability = installed + capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(installed)) let homes = try (0..<2).map { rank -> URL in let home = base.appendingPathComponent("mac-\(rank)", isDirectory: true) @@ -63,7 +57,7 @@ final class ClusterApprovalMacs: @unchecked Sendable { let stores = homes.map { ClusterPairingStore.default(home: $0) } let signers = [ClusterPairingProviderTests.SoftwareSigner(), ClusterPairingProviderTests.SoftwareSigner()] let (leaderRecord, followerRecord) = try ClusterPairingProviderTests.pair(signers[0], signers[1], stores: (stores[0], stores[1])) - let records = [leaderRecord, followerRecord] + records = [leaderRecord, followerRecord] let pins = signers.map { ClusterMemberPin.of(uncompressedKey: $0.x963) } func file(_ url: URL, _ text: String, executable: Bool) throws { @@ -92,11 +86,41 @@ final class ClusterApprovalMacs: @unchecked Sendable { let secret = mac.home.appendingPathComponent("link.secret") try Data(repeating: 7, count: 32).write(to: secret, options: .withoutOverwriting) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: secret.path) + } + try saveSetups() + } + + /// The capability the worker of the build whose worker digest is `runtime` describes for the fixture model. + static func capability(runtime: String) 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")) + } + + /// 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) + capabilitySHA256 = ClusterConfigurationCodec.sha256(try ClusterRuntimeCapabilityCodec.encode(capability)) + try saveSetups() + } + + /// Saves each Mac's setup for `capability`, without a cluster approval. + private func saveSetups() throws { + let h = Self.hash, capabilityData = try ClusterRuntimeCapabilityCodec.encode(capability) + for mac in macs { + let secret = mac.home.appendingPathComponent("link.secret") let record = records[mac.rank] func peer(_ other: Mac) -> [String: Any] { ["id": other.memberID, "rank": other.rank, "host": "192.0.2.\(other.rank + 1)", "port": 22, "user": "fixture", "ownerExecutable": other.owner.path, "workerExecutable": other.worker.path, "modelDirectory": other.model.path, - "runtimeBinarySHA256": h("a"), "jacclDevice": "rdma_en7"] + "runtimeBinarySHA256": capability.runtimeBinarySHA256, "jacclDevice": "rdma_en7"] } let configuration: [String: Any] = ["schema": ClusterConfiguration.schemaName, "clusterID": record.clusterID, "memberID": mac.memberID, "role": mac.rank == 0 ? "leader" : "follower", "publicModelID": Self.model, @@ -143,6 +167,19 @@ final class ClusterApprovalMacs: @unchecked Sendable { static let blockFields = ["native_runtime_sha256", "metallib_sha256", "resource_library_sha256", "placement_policy_sha256", "artifact_sha256", "capability_sha256", "profile_sha256", "resource_policy_sha256"] + /// A model approval (contract M1) for the fixture model's artifact (`artifact`, default the setups'), ending + /// `seconds` from now: no runtime digests, so a new build keeps it. + func modelApproval(endsIn seconds: Double = 14 * 86_400, schedule: UInt8 = 1, model: String = ClusterApprovalMacs.model, + id: String? = nil, artifact: String = ClusterApprovalMacs.hash("b")) -> ClusterRuntimeApproval { + let end = ISO8601DateFormatter().string(from: Date(timeIntervalSince1970: (Date().timeIntervalSince1970 + seconds).rounded(.down))) + return ClusterRuntimeApproval(id: id ?? "devnet/\(model)/s\(schedule)", model: model, generation: 1, + placementPolicySHA256: nil, artifactSHA256: artifact, nativeRuntimeSHA256: nil, metallibSHA256: nil, + resourceLibrarySHA256: nil, capabilitySHA256: nil, resourcePolicySHA256: nil, profileSHA256: nil, + schedule: schedule, maximumTransportFrame: 1_048_616, maximumPlaintext: 1_048_576, maximumRecords: 1_048_576, + maximumCumulativePlaintext: 4_294_967_296, allowedNumericsClasses: [], minimumMembers: 2, maximumMembers: 4, + minimumMemberUsableBytes: 1, notAfter: end) + } + /// The approval the coordinator derives from those facts (contract B), ending `seconds` from now. func approval(endsIn seconds: Double = 14 * 86_400, schedule: UInt8 = 1, model: String = ClusterApprovalMacs.model, id: String? = nil) -> ClusterRuntimeApproval { @@ -166,13 +203,19 @@ final class ClusterApprovalMacs: @unchecked Sendable { /// The cable to the follower: its cluster service's own `approval` handling against its own home, wrapped as the /// link exchange wraps a refusal. `facts` are the follower installation's facts. func cable(facts: ClusterRuntimeApprovalFacts, sent: ClusterApprovalRecorder? = nil) -> (ClusterServiceCommand) throws -> Void { + cable(describe: { _ in facts }, sent: sent) + } + + /// The same, with the follower's installation described by `describe` (which may record that it ran). + func cable(describe: @escaping (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts, + sent: ClusterApprovalRecorder? = nil) -> (ClusterServiceCommand) throws -> Void { let mac = follower return { command in sent?.append(command) do { _ = try ClusterApprovalSync.receive(command, paths: mac.paths, providerConfiguration: mac.provider, pairingStore: mac.pairing, scratch: mac.scratch, now: Date().timeIntervalSince1970, say: { _ in }, - chipClass: Self.chip, facts: { _ in facts }) + chipClass: Self.chip, facts: describe) } catch { throw ClusterSetupFailure("the other Mac refused: " + ClusterApprovalSync.refusal(error)) } @@ -183,9 +226,17 @@ final class ClusterApprovalMacs: @unchecked Sendable { func sync(_ fetched: ClusterApprovalFetch.Outcome, leaderFacts: ClusterRuntimeApprovalFacts, followerFacts: ClusterRuntimeApprovalFacts, sent: ClusterApprovalRecorder? = nil, now: Double = Date().timeIntervalSince1970) -> ClusterApprovalSync.Result { + sync(fetched, describe: { _ in leaderFacts }, followerDescribe: { _ in followerFacts }, sent: sent, now: now) + } + + /// The same, with each Mac's installation described by its own closure (which may record that it ran). + func sync(_ fetched: ClusterApprovalFetch.Outcome, describe: (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts, + followerDescribe: @escaping (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts, + sent: ClusterApprovalRecorder? = nil, + now: Double = Date().timeIntervalSince1970) -> ClusterApprovalSync.Result { ClusterApprovalSync.run(fetched: fetched, paths: leader.paths, providerConfiguration: leader.provider, pairingStore: leader.pairing, scratch: leader.scratch, now: now, - sendToPeer: cable(facts: followerFacts, sent: sent), chipClass: Self.chip, facts: { _ in leaderFacts }) + sendToPeer: cable(describe: followerDescribe, sent: sent), chipClass: Self.chip, facts: describe) } /// The probe a serving leader records for the pair after a load. diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift index a1048964e3..1b232a14e7 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift @@ -18,7 +18,8 @@ struct ClusterApprovalLifetimeTests { let all = [lookahead, other, serial, later, ended] func select(_ approvals: [ClusterRuntimeApproval], _ schedule: ClusterPrefillSchedule, facts: ClusterRuntimeApprovalFacts) -> ClusterRuntimeApproval? { - ClusterApprovalLifetime.select(approvals, model: ClusterApprovalMacs.model, schedule: schedule, facts: facts, now: now) + ClusterApprovalLifetime.select(approvals, model: ClusterApprovalMacs.model, schedule: schedule, + artifact: m.capability.artifactSHA256, facts: { facts }, now: now) } #expect(select(all, .serial, facts: facts) == later) #expect(select(all, .oneChunkLookahead, facts: facts) == lookahead) @@ -30,20 +31,53 @@ struct ClusterApprovalLifetimeTests { } } + /// A model approval names no build: it is taken for this setup's model, schedule and saved artifact without + /// describing the installed runtime (the facts closure never runs), and a build-pinned entry is still matched + /// on the facts, once, when it is listed beside it. + @Test func aModelApprovalIsChosenWithoutBuildFacts() throws { + let m = try macs(), artifact = m.capability.artifactSHA256 + var calls = 0 + func select(_ approvals: [ClusterRuntimeApproval], _ schedule: ClusterPrefillSchedule = .serial, + facts: ClusterRuntimeApprovalFacts? = nil) -> ClusterRuntimeApproval? { + ClusterApprovalLifetime.select(approvals, model: ClusterApprovalMacs.model, schedule: schedule, artifact: artifact, + facts: { calls += 1; return facts }, now: now) + } + let serial = m.modelApproval(), lookahead = m.modelApproval(schedule: 2) + #expect(select([lookahead, serial]) == serial) + #expect(select([lookahead, serial], .oneChunkLookahead) == lookahead) + #expect(calls == 0) + // Another artifact, another schedule, another model or an ended entry is not this setup's. + #expect(select([m.modelApproval(artifact: ClusterApprovalMacs.hash("9"))]) == nil) + #expect(select([lookahead]) == nil) + #expect(select([m.modelApproval(model: "other/model")]) == nil) + #expect(select([m.modelApproval(endsIn: -60)]) == nil) + #expect(calls == 0) + // Both shapes listed: the later end wins, and the facts are described once for both build-pinned entries. + let facts = try m.facts() + let pinnedLater = m.approval(endsIn: 20 * 86_400, id: "pinned-later"), pinned = m.approval(id: "pinned") + #expect(select([serial, pinned, pinnedLater], facts: facts) == pinnedLater) + #expect(calls == 1) + let modelLater = m.modelApproval(endsIn: 30 * 86_400, id: "model-later") + #expect(select([pinnedLater, modelLater], facts: facts) == modelLater) + // Facts that cannot be described choose no build-pinned entry, and leave a model approval chosen. + #expect(select([pinnedLater, serial]) == serial) + #expect(select([pinnedLater]) == nil) + } + @Test func aSavedApprovalIsKeptReplacedNearItsEndAndRemovedOnceEnded() throws { let m = try macs(), model = ClusterApprovalMacs.model let fresh = m.approval(), near = m.approval(endsIn: 3_600, id: "near"), ended = m.approval(endsIn: -60, id: "ended") let later = m.approval(endsIn: 13 * 86_400, id: "later") func decide(_ saved: ClusterRuntimeApproval?, _ fetched: ClusterApprovalFetch.Outcome) -> ClusterApprovalLifetime.Decision { ClusterApprovalLifetime.decide(saved: saved, fetched: fetched, model: model, schedule: .serial, - facts: { try? m.facts() }, now: now) + artifact: m.capability.artifactSHA256, facts: { try? m.facts() }, now: now) } #expect(decide(nil, .approvals([fresh])) == .save(fresh)) #expect(decide(nil, .notOffered) == .keep) #expect(decide(nil, .unavailable("no answer")) == .keep) // Facts that cannot be described choose no entry. #expect(ClusterApprovalLifetime.decide(saved: nil, fetched: .approvals([fresh]), model: model, schedule: .serial, - facts: { nil }, now: now) == .keep) + artifact: m.capability.artifactSHA256, facts: { nil }, now: now) == .keep) // More than a day left and still listed: nothing is written; no usable answer says nothing about it. #expect(decide(fresh, .approvals([fresh, later])) == .keep) #expect(decide(fresh, .unavailable("HTTP 500")) == .keep) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift index 1672d01928..65022d4b16 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift @@ -172,6 +172,80 @@ struct ClusterApprovalSyncTests { #expect(try macs.bytes(macs.leader) == before) } + /// A model approval names no build: both Macs save it from a mixed answer without describing their installed + /// runtime, and after an update re-adopts the setups for a new worker the next check finds the same entry again, + /// while the build-pinned entry of the old build no longer matches. + @Test func aModelApprovalIsSavedWithoutBuildFactsAndFoundAgainAfterAnUpdate() async throws { + let mock = MockCoordinator() + let url = try await mock.start().mockProviderWebSocketURL() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + let model = macs.modelApproval() + // The old build's own entry for the same model and schedule, ending later: it would win while it matched. + let pinnedOld = macs.approval(endsIn: 20 * 86_400, id: "devnet/old-build/fixture-qwen/s1") + mock.setClusterApprovals(body: try ClusterApprovalMacs.body([macs.approval(schedule: 2), model, macs.modelApproval(schedule: 2)])) + let fetched = await ClusterApprovalFetch.fetch(coordinatorURL: url) + guard case .approvals(let listed) = fetched else { Issue.record("a mixed answer was refused: \(fetched)"); return } + #expect(listed.map(\.isModelApproval) == [false, true, true]) + let described = ClusterApprovalRecorder() + let describe: (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts = { _ in + described.append(1); throw ClusterConfigurationError.invalid("a model approval needs no build facts") + } + let result = macs.sync(fetched, describe: describe, followerDescribe: describe) + #expect(result == .init(changed: true, line: ClusterApprovalLifetime.offeredLine(model), note: .some(nil))) + #expect(described.values.isEmpty) + for mac in macs.macs { + let saved = try #require(try attachment(macs, mac), "rank \(mac.rank) saved no approval") + #expect(saved.schema == ClusterNativeMemberAttachment.rosterSchemaName && saved.clusterApproval == model) + #expect(try saved.policyBytes == model.canonicalPolicy()) + // The saved setup holds the 14 fields and reads back to the same bytes. + let setup = try macs.saved(mac), file = try macs.bytes(mac)[1] + #expect(try ClusterConfigurationCodec.encode(setup.configuration, capability: setup.capability, + capabilitySHA256: setup.configuration.capabilitySHA256) == file) + let object = try #require(try JSONSerialization.jsonObject(with: file) as? [String: Any]) + let entry = try #require((object["nativeMember"] as? [String: Any])?["clusterApproval"] as? [String: Any]) + #expect(Set(entry.keys) == ClusterRuntimeApproval.modelFields) + } + + // The update: both setups re-adopted for the new build's worker, with no approval. + let newWorker = ClusterApprovalMacs.hash("9") + try macs.readopt(runtime: newWorker) + for mac in macs.macs { #expect(try attachment(macs, mac) == nil) } + var watch = ClusterApprovalCheck.Watch() + let step = ClusterApprovalCheck.step(saved: try macs.saved(macs.leader), fetched: .approvals([pinnedOld, model]), + setAside: nil, scope: .publicServing, memberQuickEnds: 0, peerApprovalID: .some(nil), watch: &watch, + clock: 0, grace: 600, now: Date().timeIntervalSince1970, facts: { _ in try macs.facts() }) + #expect(step == .save(model)) + let updated = try macs.facts() + #expect(macs.sync(.approvals([pinnedOld, model]), leaderFacts: updated, followerFacts: updated).changed) + for mac in macs.macs { + let saved = try macs.saved(mac) + #expect(saved.configuration.nativeMember?.clusterApproval == model) + #expect(saved.capability.runtimeBinarySHA256 == newWorker) + } + await mock.shutdown() + } + + @Test func aModelApprovalForAnotherArtifactIsSavedOnNeitherMac() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let before = try macs.macs.map(macs.bytes), saved = try macs.saved(macs.leader) + let other = macs.modelApproval(artifact: ClusterApprovalMacs.hash("9")) + let refusal = "the approval's artifact_sha256 differs from this Mac's setup" + let mine = #expect(throws: (any Error).self) { + _ = try ClusterApprovalAttachment.attachment(for: other, saved: saved, paths: macs.leader.paths, + pairingStore: macs.leader.pairing, edge: nil, now: Date().timeIntervalSince1970, chipClass: ClusterApprovalMacs.chip, + facts: { _ in throw ClusterConfigurationError.invalid("a model approval needs no build facts") }) + } + #expect(mine.map(ClusterApprovalSync.refusal) == refusal) + // The other Mac refuses it the same way when its leader sends it. + var command = ClusterServiceCommand(op: .approval) + command.approval = other + command.approvalEdge = ClusterEdge(peerPin: macs.leader.pin, transport: "rdma", measuredMbps: 1, measuredRTTMicros: 1) + let cable = macs.cable(facts: try macs.facts()) + let theirs = #expect(throws: (any Error).self) { try cable(command) } + #expect(theirs.map(ClusterApprovalSync.refusal)?.hasSuffix(refusal) == true) + #expect(try macs.macs.map(macs.bytes) == before) + } + @Test func aFollowerThatCannotBeReachedLeavesBothMacsWithoutTheApproval() throws { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") let before = try macs.macs.map(macs.bytes), facts = try macs.facts() From 8189581be44607fbe24ca059dfcbc3f5eabb3cbb Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 15:41:20 -0500 Subject: [PATCH 2/7] Say that a re-adopted setup finds the same model approval again Co-Authored-By: Claude Opus 5.5 --- .../Inference/Distributed/Onboarding/ClusterService.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index b2a5a3f5c8..9f4982bbd3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -1004,7 +1004,8 @@ public final class ClusterService: @unchecked Sendable { // The plan's own line and its reason for the mode (tensor parallel or a pipeline), so the log says why. say("set the cluster up again after the update: \(model) is starting on both Macs (" + choices[index].lines.joined(separator: " ") + ")") - // The re-adopted setups carry no cluster approval: the next check looks for the entry of the updated app. + // The re-adopted setups carry no cluster approval: the next check finds the same model approval again, or the + // build-pinned entry of the updated app. self.lock.withLock { self.approvalChecked = false; self.nextApprovalCheck = .distantPast } } } From 7a992109f7b8507205b49f8d862641554ee4e5f3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 16:01:05 -0500 Subject: [PATCH 3/7] Refactor pass: one digest parser and encoder, plainer selection Behavior-preserving cleanup of the model-approval change: - Both canonical encoders (pair and cluster approval) parse digests with NativePairMemberPolicy.digest(hex:), and the pair encoder uses the shared pair domain constant. - One hex encoder: NativePairMemberPolicy.hex replaces the forwarding NativePairMemberInstallation.hex; the roster uses ClusterConfigurationCodec.sha256. - NativePairMemberInstallation stores the execution plan digest its initializer checked instead of recomputing it with an unreachable fallback. - ClusterApprovalLifetime.select describes facts once, up front, only when an eligible build-pinned entry exists, without a double optional. - ClusterMemberPreparation chooses the metallib digest per approval shape. - Doc comments rewrapped; the pair how-to no longer says every approval matches eight digests or lasts 14 days. Co-Authored-By: Claude Opus 5.5 --- docs/provider/two-mac-cluster.md | 17 ++++++++++------- .../Config/ClusterPairApproval.swift | 7 +++---- .../Config/ClusterRuntimeApproval.swift | 5 ++--- .../Config/ClusterRuntimeApprovalFacts.swift | 2 +- .../NativePairMemberInstallation.swift | 19 +++++++++---------- .../Coordinator/NativePairMemberRoster.swift | 2 +- .../Coordinator/NativePairMemberSession.swift | 2 +- .../ClusterApprovalAttachment.swift | 17 +++++++++-------- .../ClusterApprovalFetch.swift | 6 +++--- .../ClusterApprovalLifetime.swift | 19 +++++++++---------- .../ClusterApproval/ClusterApprovalSync.swift | 7 ++++--- .../Membership/ClusterMemberPreparation.swift | 16 +++++++++++----- .../ClusterRuntimeApprovalFactsTests.swift | 2 +- 13 files changed, 64 insertions(+), 57 deletions(-) diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 464db643f5..57473bd6cf 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-29 +> Last updated: 2026-10-30 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 @@ -112,9 +112,9 @@ start fails and says why. To serve without any coordinator, use ## Registered with the coordinator as a cluster member (DevNet) When the coordinator's operator approval file holds a cluster approval for this -pair's installed app and 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 +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)). @@ -122,8 +122,11 @@ 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). After the Test stage passes, the leader reads the approvals the coordinator - serves (`GET /v1/cluster/approvals`) and takes the one whose model, prefill - schedule and eight digests match this pair's installed app and model. Each + serves (`GET /v1/cluster/approvals`) and takes the one whose model and + prefill schedule match this pair's setup. A build-pinned approval must also + match the installed app's digests. A model approval names no build and must + match only the model's artifact, so it stays valid after an update + ([model approvals](../reference/configuration.md#model-approvals)). Each Mac checks it against its own files, and both Macs save it, or neither does. Both Macs then start their parts again as cluster members. 2. Read the ready screen. Instead of the API line it says: @@ -135,7 +138,7 @@ 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` (14 days after the operator added it). The +An approval ends at its `not_after`, which the operator sets. 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 diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterPairApproval.swift b/provider-swift/Sources/ProviderCore/Config/ClusterPairApproval.swift index c405db83af..d19c9c9078 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterPairApproval.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterPairApproval.swift @@ -52,7 +52,7 @@ public struct ClusterPairApproval: Codable, Sendable, Equatable { guard let expiry = Self.unixNanoseconds(rfc3339: notAfter) else { throw ClusterConfigurationError.invalid("Pair approval not_after must be an RFC 3339 instant") } - var bytes = Data("darkbloom/coordinator-native-runtime-approval/v1\0".utf8) + var bytes = NativePairMemberPolicy.pairDomain func integer(_ value: T) { withUnsafeBytes(of: value.bigEndian) { bytes.append(contentsOf: $0) } } @@ -60,11 +60,10 @@ public struct ClusterPairApproval: Codable, Sendable, Equatable { text(id); text(model); integer(generation) for digest in [planSHA256, artifactSHA256, nativeRuntimeSHA256, metallibSHA256, resourceLibrarySHA256, capabilitySHA256, resourcePolicySHA256, profileSHA256] { - guard ClusterConfigurationSyntax.hash(digest) else { + guard let value = NativePairMemberPolicy.digest(hex: digest) else { throw ClusterConfigurationError.invalid("Pair approval digests must be 64 lowercase hex characters") } - let digits = Array(digest.utf8).map { $0 < 58 ? $0 - 48 : $0 - 87 } - for index in stride(from: 0, to: 64, by: 2) { bytes.append(digits[index] << 4 | digits[index + 1]) } + bytes.append(value) } bytes.append(contentsOf: [1, 1, schedule]) integer(maximumTransportFrame); integer(maximumPlaintext) diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift index 488246110c..319d5e6dc7 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift @@ -108,11 +108,10 @@ public struct ClusterRuntimeApproval: Codable, Sendable, Equatable { func text(_ value: String) { integer(UInt32(value.utf8.count)); bytes.append(contentsOf: value.utf8) } text(id); text(model); integer(generation) for digest in digests { - guard ClusterConfigurationSyntax.hash(digest) else { + guard let value = NativePairMemberPolicy.digest(hex: digest) else { throw ClusterConfigurationError.invalid("Cluster approval digests must be 64 lowercase hex characters") } - let digits = Array(digest.utf8).map { $0 < 58 ? $0 - 48 : $0 - 87 } - for index in stride(from: 0, to: 64, by: 2) { bytes.append(digits[index] << 4 | digits[index + 1]) } + bytes.append(value) } bytes.append(contentsOf: [1, 1, schedule]) integer(maximumTransportFrame); integer(maximumPlaintext) diff --git a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift index 596da822ef..10f04d9230 100644 --- a/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift +++ b/provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApprovalFacts.swift @@ -128,7 +128,7 @@ public struct ClusterRuntimeApprovalFacts: Equatable, Sendable { } return Model(model: artifact.modelID, artifactSHA256: capability.artifactSHA256, capabilitySHA256: ClusterConfigurationCodec.sha256(bytes), profileSHA256: capability.profileFingerprint, - resourcePolicySHA256: NativePairMemberInstallation.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability))) + resourcePolicySHA256: NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability))) } // MARK: - Canonical form diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift index 9ee5ed0827..aad49d2e4e 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberInstallation.swift @@ -38,6 +38,8 @@ public struct NativePairMemberInstallation: Sendable { /// the approval's own, or under a model approval this member's own (its /// plan's runtime block and the digests it took of its installed files). let runtime: NativePairMemberPolicy.Runtime + /// The plan the owner runs: the registered plan, or a pair approval's fixed plan. + let executionPlanSHA256: String /// `meshOverLink`: the saved setup reaches the follower over the link /// control channel, the only way a committed start can serve in this @@ -91,15 +93,15 @@ public struct NativePairMemberInstallation: Sendable { covered = roster != nil && device?.chipName == chip && terms.admits(numericsClass: device?.numericsClass ?? "") && (device?.usableWiredBytes ?? 0) >= terms.minimumMemberUsableBytes - && roster?.plan.policySHA256 == Self.hex(Data(SHA256.hash(data: expectedCoordinatorPolicy))) + && roster?.plan.policySHA256 == ClusterConfigurationCodec.sha256(expectedCoordinatorPolicy) && roster?.plan.model == policy.model - && roster?.membership.artifact(for: policy.model) == Self.hex(policy.artifact) + && roster?.membership.artifact(for: policy.model) == NativePairMemberPolicy.hex(policy.artifact) } else { covered = roster == nil && policy.chips.contains(chip) } guard (0...1).contains(rank), identity.peers.count == 2, ClusterConfigurationSyntax.hash(ownerSHA256), covered, - identity.artifactSHA256 == Self.hex(policy.artifact), - identity.peers[rank].buildSHA256 == Self.hex(runtime.nativeRuntime), - let executionPlanSHA256 = roster?.plan.planSHA256 ?? policy.pinnedPlan.map(Self.hex) else { + identity.artifactSHA256 == NativePairMemberPolicy.hex(policy.artifact), + identity.peers[rank].buildSHA256 == NativePairMemberPolicy.hex(runtime.nativeRuntime), + let executionPlanSHA256 = roster?.plan.planSHA256 ?? policy.pinnedPlan.map(NativePairMemberPolicy.hex) else { throw NativePairMemberError.binding } _ = try ClusterOwnerBinding(clusterID: clusterID, ownerIncarnation: UUID(), leaseID: UUID(), @@ -109,7 +111,7 @@ public struct NativePairMemberInstallation: Sendable { localOwner = try .init(installedDarkbloom: installedOwner, batchLanes: batchLanes); self.ownerSHA256 = ownerSHA256 artifacts = [nativeExecutable, metallib, resourceLibrary]; self.chip = chip; self.leaseDirectory = leaseDirectory self.ownerServesCommittedStart = ownerServesCommittedStart; self.bootstrap = bootstrap - self.roster = roster; self.runtime = runtime + self.roster = roster; self.runtime = runtime; self.executionPlanSHA256 = executionPlanSHA256 } /// The claim this member registers. Its `policySHA256` is the digest of /// exactly the policy bytes a prepare frame must carry. @@ -141,7 +143,7 @@ public struct NativePairMemberInstallation: Sendable { var files = [try DistributedInstalledFiles.verify(localOwner.installedDarkbloom, expectedSHA256: ownerSHA256, maximumBytes: 256 * 1024 * 1024, executable: true, deadline: deadline)] for (i, digest) in [runtime.nativeRuntime, runtime.metallib, runtime.resourceLibrary].enumerated() { - files.append(try DistributedInstalledFiles.verify(artifacts[i], expectedSHA256: Self.hex(digest), + files.append(try DistributedInstalledFiles.verify(artifacts[i], expectedSHA256: NativePairMemberPolicy.hex(digest), maximumBytes: 256 * 1024 * 1024, executable: i == 0, deadline: deadline)) } for file in files { try file.requireUnchanged() } @@ -167,7 +169,4 @@ public struct NativePairMemberInstallation: Sendable { ClusterWorkerIdentity(membershipEpoch: start.common.epoch, modelID: identity.modelID, artifactSHA256: identity.artifactSHA256, configurationSHA256: identity.configurationSHA256, peers: identity.peers) } - /// The registered plan, or a pair approval's fixed plan (the initializer refuses neither). - var executionPlanSHA256: String { roster?.plan.planSHA256 ?? policy.pinnedPlan.map(Self.hex) ?? "" } - static func hex(_ bytes: Data) -> String { NativePairMemberPolicy.hex(bytes) } } diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift index 3f7512f5fd..ce9b5ca74e 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberRoster.swift @@ -40,7 +40,7 @@ public struct NativePairMemberRoster: Sendable, Equatable { throw ClusterRosterError.invalidMembership } guard tensorShares == nil else { throw ClusterRosterError.invalidPlan } - let policy = Data(SHA256.hash(data: policyBytes)).map { String(format: "%02x", $0) }.joined() + let policy = ClusterConfigurationCodec.sha256(policyBytes) plan = ClusterPlan(policySHA256: policy, model: model, planSHA256: planSHA256, members: rankPins, cuts: mode.layerCutCount(ranks: rankPins.count) == 0 ? [] : [UInt32(cut)], mode: mode == .pipeline ? nil : mode.rawValue, runtime: runtime) diff --git a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift index f0e6aaa6a0..d7b7529973 100644 --- a/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift +++ b/provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberSession.swift @@ -82,7 +82,7 @@ final class NativePairMemberSession: @unchecked Sendable { let (policy, start) = try NativePairMemberPolicy.preparation(Data(base64Encoded: message.payload)!) try installation.requireStart(start) guard policy.bytes == installation.policy.bytes, start.rank == installation.rank, - NativePairMemberInstallation.hex(Self.uuidBytes(start.common.epoch)) == message.epoch, + NativePairMemberPolicy.hex(Self.uuidBytes(start.common.epoch)) == message.epoch, start.common.membershipGeneration == message.generation, let prepare = message.prepareBeforeUnixNano, let expires = message.expiresAtUnixNano, wallUnixNanoseconds > 0, prepare > wallUnixNanoseconds, expires > prepare, UInt64(expires) < policy.notAfter else { throw NativePairMemberError.binding } 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 88efe3c940..ae8e63ce6d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift @@ -15,14 +15,15 @@ enum ClusterApprovalAttachment { /// when the facts describe no entry for the approval's model. A model approval is never compared with facts. static func mismatches(_ approval: ClusterRuntimeApproval, facts: ClusterRuntimeApprovalFacts) -> [String] { guard let entry = facts.models.first(where: { $0.model == approval.model }) else { return ["model"] } - let pairs: [(String, String?, String)] = [("native_runtime_sha256", approval.nativeRuntimeSHA256, facts.nativeRuntimeSHA256), - ("metallib_sha256", approval.metallibSHA256, facts.metallibSHA256), - ("resource_library_sha256", approval.resourceLibrarySHA256, facts.resourceLibrarySHA256), - ("placement_policy_sha256", approval.placementPolicySHA256, facts.placementPolicySHA256), - ("artifact_sha256", approval.artifactSHA256, entry.artifactSHA256), - ("capability_sha256", approval.capabilitySHA256, entry.capabilitySHA256), - ("profile_sha256", approval.profileSHA256, entry.profileSHA256), - ("resource_policy_sha256", approval.resourcePolicySHA256, entry.resourcePolicySHA256)] + let pairs: [(String, String?, String)] = [ + ("native_runtime_sha256", approval.nativeRuntimeSHA256, facts.nativeRuntimeSHA256), + ("metallib_sha256", approval.metallibSHA256, facts.metallibSHA256), + ("resource_library_sha256", approval.resourceLibrarySHA256, facts.resourceLibrarySHA256), + ("placement_policy_sha256", approval.placementPolicySHA256, facts.placementPolicySHA256), + ("artifact_sha256", approval.artifactSHA256, entry.artifactSHA256), + ("capability_sha256", approval.capabilitySHA256, entry.capabilitySHA256), + ("profile_sha256", approval.profileSHA256, entry.profileSHA256), + ("resource_policy_sha256", approval.resourcePolicySHA256, entry.resourcePolicySHA256)] return pairs.filter { $0.1 != $0.2 }.map(\.0) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift index dd13e3a81e..70ee91294a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift @@ -3,9 +3,9 @@ import Foundation /// The cluster approvals the provider's coordinator serves (`GET /v1/cluster/approvals`): every unexpired entry of /// the coordinator operator's approval file, public build facts, so the request carries no credential. The answer /// approves nothing by itself: the leader takes only an entry whose digests are this Mac's own cluster runtime facts -/// (or a model approval for its saved setup's model, schedule and artifact), and each Mac checks it against its own installed files before it saves it (`ClusterApprovalAttachment`). A -/// coordinator without pair control answers 404, and every failure means "no approval": nothing here can stop a Mac -/// from serving. +/// (or a model approval for its saved setup's model, schedule and artifact), and each Mac checks it against its own +/// installed files before it saves it (`ClusterApprovalAttachment`). A coordinator without pair control answers 404, +/// and every failure means "no approval": nothing here can stop a Mac from serving. public enum ClusterApprovalFetch { public static let path = "/v1/cluster/approvals" public static let schemaName = "darkbloom_cluster_catalog_v2" diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift index 1df66d958c..05333a6c1d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift @@ -1,9 +1,9 @@ import Foundation import DarkbloomClusterProtocol -/// Which cluster approval a pair's setup keeps, and for how long. Every approval expires (its `not_after`, 14 days -/// after the operator computed it); one within a day of its end is replaced when the coordinator has a later one. An expired approval is removed, never -/// kept: the Macs then serve as a pair without one does, on the leader's local API. +/// Which cluster approval a pair's setup keeps, and for how long. Every approval expires (its `not_after`, which the +/// operator sets); one within a day of its end is replaced when the coordinator has a later one. An expired approval +/// is removed, never kept: the Macs then serve as a pair without one does, on the leader's local API. public enum ClusterApprovalLifetime { /// A saved approval this close to its `not_after` is replaced when the coordinator offers a later one. public static let renewWithinSeconds: Double = 86_400 @@ -40,14 +40,13 @@ public enum ClusterApprovalLifetime { /// not be computed, so no build-pinned entry is this setup's). static func select(_ approvals: [ClusterRuntimeApproval], model: String, schedule: ClusterPrefillSchedule, artifact: String, facts: () -> ClusterRuntimeApprovalFacts?, now: Double) -> ClusterRuntimeApproval? { - var computed: ClusterRuntimeApprovalFacts?? - return approvals.filter { approval in - guard approval.model == model, approval.schedule == Self.schedule(schedule), current(approval, now: now) else { - return false - } + let eligible = approvals.filter { + $0.model == model && $0.schedule == Self.schedule(schedule) && current($0, now: now) + } + let installed: ClusterRuntimeApprovalFacts? = eligible.allSatisfy(\.isModelApproval) ? nil : facts() + return eligible.filter { approval in if approval.isModelApproval { return approval.artifactSHA256 == artifact } - if computed == nil { computed = .some(facts()) } - guard let installed = computed ?? nil else { return false } + guard let installed else { return false } return ClusterApprovalAttachment.mismatches(approval, facts: installed).isEmpty }.max { (expiry($0) ?? 0) < (expiry($1) ?? 0) } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift index 56708dcc8b..a712977aff 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift @@ -5,9 +5,10 @@ import DarkbloomClusterSecurity /// The control leader's step that keeps both Macs' setups on the same cluster approval: after the guided setup's Test /// stage passed, once at each start of its cluster service and after an update re-adopted the setups, and every /// minute while the pair is offered. The leader asks its coordinator, takes the entry whose digests are its own -/// facts (or a model approval for its setup's model, schedule and artifact, which a new build does not change), sends it to the other Mac over the cable (which checks it against its own files and saves it, or refuses), -/// and saves it itself only after the other Mac did. Both Macs so carry the approval, or neither does. A coordinator -/// that serves none (404, no matching entry, any failure) changes nothing. +/// facts (or a model approval for its setup's model, schedule and artifact, which a new build does not change), sends +/// it to the other Mac over the cable (which checks it against its own files and saves it, or refuses), and saves it +/// itself only after the other Mac did. Both Macs so carry the approval, or neither does. A coordinator that serves +/// none (404, no matching entry, any failure) changes nothing. public enum ClusterApprovalSync { /// How the other Mac's refusal starts, so the leader's line names the Mac that refused. public static let peerRefusalPrefix = "the other Mac refused the cluster approval: " diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift index 7d2f48f5de..addfdfbb62 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterMemberPreparation.swift @@ -113,17 +113,23 @@ public struct ClusterMemberPreparation: Sendable { guard Date().timeIntervalSince1970 * 1_000_000_000 < Double(policy.notAfter) else { throw ClusterConfigurationError.invalid("Saved pair approval has expired") } - // A model approval pins no files: hash this Mac's own once, here. - var installedDigests: (metallib: String, resourceLibrary: String)? - if policy.runtime == nil { + // The metallib digest the device profile names: the approval's, or under a model approval, which pins no + // files, the digest this Mac takes of its own metallib here, once, with its resource library's. + let installedDigests: (metallib: String, resourceLibrary: String)? + let metallibSHA256: String + if let pinned = policy.runtime { + installedDigests = nil + metallibSHA256 = NativePairMemberPolicy.hex(pinned.metallib) + } else { let deadline = DispatchTime.now().uptimeNanoseconds + 15_000_000_000 func digest(_ path: String) throws -> String { try DistributedInstalledFiles.digest(URL(fileURLWithPath: path), maximumBytes: 256 * 1024 * 1024, deadline: deadline).sha256 } - installedDigests = (try digest(attachment.metallibPath), try digest(attachment.resourceLibraryPath)) + let own = (metallib: try digest(attachment.metallibPath), resourceLibrary: try digest(attachment.resourceLibraryPath)) + installedDigests = own + metallibSHA256 = own.metallib } - let metallibSHA256 = installedDigests?.metallib ?? policy.runtime.map { NativePairMemberPolicy.hex($0.metallib) } ?? "" var roster: NativePairMemberRoster? if attachment.isRoster, let saved = attachment.roster, let pins = attachment.memberPins { guard let device else { throw ClusterConfigurationError.invalid("A roster registration needs this Mac's device profile") } diff --git a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift index 73df5efa3e..cc47255b81 100644 --- a/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Config/ClusterRuntimeApprovalFactsTests.swift @@ -45,7 +45,7 @@ struct ClusterRuntimeApprovalFactsTests { let fields = ["darkbloom/installed-resource-policy/v1", capability.arithmeticPolicyID, capability.arithmeticPolicySHA256, capability.stateSemantics, capability.schedulingPolicy] #expect(entry.resourcePolicySHA256 == ClusterConfigurationCodec.sha256(Data(fields.joined(separator: "\u{1F}").utf8))) - #expect(entry.resourcePolicySHA256 == NativePairMemberInstallation.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability))) + #expect(entry.resourcePolicySHA256 == NativePairMemberPolicy.hex(DistributedInstalledNativeStart.resourcePolicySHA256(capability))) // The worker ran its metadata command with the hash just computed. let configuration = try f.real(model.appendingPathComponent("config.json")) From 36034adbd29ad1f5c1e4c33a3e7bb4464ddf5752 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 16:05:04 -0500 Subject: [PATCH 4/7] fix (review): set a failing model approval aside for its build only ClusterApprovalCheck.step dropped a failing set-aside approval by id alone, and the set-aside clears only on expiry or another save. A model approval keeps its id for its whole life, so after three quick ends on one build no later build took it again. The set-aside now records the setup's worker digest (ApprovalSetAside.runtimeBinarySHA256) and filters the id only while the setup runs that worker. A record from an older build has no digest and keeps today's behavior (filtered by id). Row: ClusterApprovalWatchTests.aModelApprovalSetAsideAsFailingIsTakenAgainByTheNextBuild. Co-Authored-By: Claude Opus 5.5 --- changelog.d/cluster-model-approvals.md | 1 + docs/reference/configuration.md | 2 +- .../Console/ClusterSetupWizardStore.swift | 8 +++++- .../ClusterApprovalCheck.swift | 6 ++-- .../Onboarding/ClusterService.swift | 7 +++-- .../ClusterApprovalWatchTests.swift | 28 +++++++++++++++++++ 6 files changed, 46 insertions(+), 6 deletions(-) diff --git a/changelog.d/cluster-model-approvals.md b/changelog.d/cluster-model-approvals.md index 4f16ca9eeb..8f02cae17f 100644 --- a/changelog.d/cluster-model-approvals.md +++ b/changelog.d/cluster-model-approvals.md @@ -3,3 +3,4 @@ - 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/docs/reference/configuration.md b/docs/reference/configuration.md index 5d82922a82..8c144ef5d6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1032,7 +1032,7 @@ 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 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 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 and the reason in its setup record (`approvalSetAside`). When an answer lists a matching entry, the pair is registered again through the Save step; after repeated failures, only a later entry | `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 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` | | 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` | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift index 76cb3695e5..161f42053d 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Console/ClusterSetupWizardStore.swift @@ -101,7 +101,13 @@ public struct ClusterSetupRecord: Codable, Sendable, Equatable { public struct ApprovalSetAside: Codable, Sendable, Equatable { public var approval: ClusterRuntimeApproval public var reason: ClusterApprovalFallback - public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback) { self.approval = approval; self.reason = reason } + /// 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. + public var runtimeBinarySHA256: String? + public init(approval: ClusterRuntimeApproval, reason: ClusterApprovalFallback, runtimeBinarySHA256: String? = nil) { + self.approval = approval; self.reason = reason; self.runtimeBinarySHA256 = runtimeBinarySHA256 + } } public init(pair: Pair? = nil) { self.pair = pair } 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 6ad32a8bf7..c6ee9cc525 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift @@ -121,9 +121,11 @@ 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. + // parts kept failing with is not taken again by the same build (by any build for a record without one). var answer = fetched - if let setAside, setAside.reason == .failing, case .approvals(let approvals) = fetched { + if let setAside, setAside.reason == .failing, + setAside.runtimeBinarySHA256.map({ $0 == saved.capability.runtimeBinarySHA256 }) ?? true, + case .approvals(let approvals) = fetched { answer = .approvals(approvals.filter { $0.id != setAside.approval.id }) } if case .save(let approval) = ClusterApprovalSync.decision(saved: saved, fetched: answer, now: now, facts: facts) { diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index 9f4982bbd3..f589880104 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -1043,6 +1043,8 @@ public final class ClusterService: @unchecked Sendable { let step: ClusterApprovalCheck.Step let watch: ClusterApprovalCheck.Watch let serving: Bool + /// The saved setup's worker digest, recorded with an approval set aside. + let worker: String } func decide(_ answer: () -> ClusterApprovalFetch.Outcome?) -> Decided? { let record = try? self.store.readRecord() @@ -1072,7 +1074,8 @@ public final class ClusterService: @unchecked Sendable { let step = ClusterApprovalCheck.step(saved: saved, fetched: fetched, setAside: setAside, scope: scope, memberQuickEnds: quickEnds, peerApprovalID: peerApprovalID, watch: &watch, clock: ClusterService.monotonicSeconds(), grace: ClusterService.soloGraceSeconds, now: now) - return Decided(step: step, watch: watch, serving: record?.leadership?.serving == true) + return Decided(step: step, watch: watch, serving: record?.leadership?.serving == true, + worker: saved.capability.runtimeBinarySHA256) } var fetched: ClusterApprovalFetch.Outcome? func answer() -> ClusterApprovalFetch.Outcome? { @@ -1122,7 +1125,7 @@ public final class ClusterService: @unchecked Sendable { 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) + stored.approvalSetAside = .init(approval: approval, reason: reason, runtimeBinarySHA256: decided.worker) } if case .save = step, result.changed { stored.approvalSetAside = nil } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift index 67eaf97136..12befc1dd2 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift @@ -172,6 +172,34 @@ struct ClusterApprovalWatchTests { #expect(ClusterApprovalCheck.memberQuickEnds(after: 2, ranSeconds: 31, lastError: unreachable) == 0) } + /// 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`. + @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() + #expect(macs.sync(.approvals([model]), leaderFacts: facts, followerFacts: facts).changed) + let limit = ClusterControlSoloAdmission.maximumQuickEnds + #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) + // 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. + 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 older = try JSONDecoder().decode(ClusterSetupRecord.ApprovalSetAside.self, + from: JSONSerialization.data(withJSONObject: object)) + #expect(older == ClusterSetupRecord.ApprovalSetAside(approval: model, reason: .failing)) + + // 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) + } + @Test func aClusterThatServesLocallyOnlyNeverAsksTheCoordinatorAndChangesNothing() throws { let local = ClusterServingScope.localOnly(bind: "127.0.0.1") for first in [true, false] { From 73216a8d7181b8b2d01c82507aec08fb8d8fdb7c Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 16:05:04 -0500 Subject: [PATCH 5/7] fix (review): an entry replaced under the same id replaces the saved one ClusterApprovalLifetime.decide kept a saved approval while an entry with its id was listed, even when the operator had replaced that entry in place (a new not_after, other terms). The coordinator then approves other policy bytes, so the saved setup could not form a session. A saved approval now counts as listed only when the listed entry equals it; otherwise the decision is the withdrawn path's: a matching entry is saved, else the approval is withdrawn. Row: ClusterApprovalLifetimeTests.aSavedApprovalIsKeptReplacedNearItsEndAndRemovedOnceEnded (same id, new not_after -> .save(listed); same id, other model -> .withdrawn). Co-Authored-By: Claude Opus 5.5 --- docs/reference/configuration.md | 4 ++-- .../ClusterApproval/ClusterApprovalLifetime.swift | 10 ++++++---- .../ClusterApproval/ClusterApprovalLifetimeTests.swift | 6 ++++++ 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 8c144ef5d6..412ffef6b3 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1031,8 +1031,8 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | 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`) | | 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 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 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` | +| 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` | | 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` | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift index 05333a6c1d..d4f80c4526 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift @@ -55,12 +55,12 @@ public enum ClusterApprovalLifetime { /// Nothing to write: the saved setup stays byte for byte as it is. case keep /// Save this approval on both Macs: none was saved; the saved one is near its end and this one is later; or the - /// coordinator no longer lists the saved one and serves this matching one. + /// coordinator no longer lists the saved one as saved and serves this matching one. case save(ClusterRuntimeApproval) /// The saved approval expired and the coordinator has no later one: both Macs save the setup without it. case remove - /// The coordinator answered (404, or a list without the saved approval) and serves no other matching entry: the - /// saved approval is withdrawn although it has not ended. + /// The coordinator answered (404, or a list without the saved approval as saved) and serves no other matching + /// entry: the saved approval is withdrawn although it has not ended. case withdrawn } @@ -84,7 +84,9 @@ public enum ClusterApprovalLifetime { guard let saved else { return candidate().map(Decision.save) ?? .keep } let savedEnd = expiry(saved) ?? 0 if savedEnd <= now { return candidate().map(Decision.save) ?? .remove } - if let listed, !listed.contains(where: { $0.id == saved.id }) { return candidate().map(Decision.save) ?? .withdrawn } + // An entry the operator replaced under the same `id` (a new `not_after`, other terms) is not the saved one: the + // coordinator no longer approves the saved bytes. + if let listed, !listed.contains(saved) { return candidate().map(Decision.save) ?? .withdrawn } if savedEnd - now > renewWithinSeconds { return .keep } if let candidate = candidate(), candidate != saved, (expiry(candidate) ?? 0) > savedEnd { return .save(candidate) } return .keep diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift index 1b232a14e7..8227690b04 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalLifetimeTests.swift @@ -86,6 +86,12 @@ struct ClusterApprovalLifetimeTests { #expect(decide(fresh, .approvals([later])) == .save(later)) #expect(decide(fresh, .approvals([])) == .withdrawn) #expect(decide(fresh, .notOffered) == .withdrawn) + // Replaced in place under the same `id` (a new `not_after`): the coordinator no longer approves the saved + // bytes, so the listed entry is saved; a replacement this setup does not match withdraws it. + let replaced = m.approval(endsIn: 10 * 86_400) + #expect(replaced.id == fresh.id && replaced != fresh) + #expect(decide(fresh, .approvals([replaced])) == .save(replaced)) + #expect(decide(fresh, .approvals([m.approval(model: "other/model", id: fresh.id)])) == .withdrawn) // Within a day of its end: a later one replaces it; still listed without one, it stays until it ends. #expect(decide(near, .approvals([near, later])) == .save(later)) #expect(decide(near, .approvals([near])) == .keep) From f652905953600ee008c8e5509bf27f5a4de9095a Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 16:05:04 -0500 Subject: [PATCH 6/7] fix (review): test the owner's start admission under a model approval DistributedInstalledOwner.memberAuthorizer under a saved model approval admits a start that carries the setup's own runtime block and refuses one whose worker or resource policy digest differs. Co-Authored-By: Claude Opus 5.5 --- .../ClusterApprovalSyncTests.swift | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift index 65022d4b16..fc6390bbcf 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalSyncTests.swift @@ -2,6 +2,7 @@ import CryptoKit import Foundation import Testing import DarkbloomClusterProtocol +import DarkbloomClusterSecurity @testable import ProviderCore /// The leader's step that saves a fetched cluster approval on both Macs (`ClusterApprovalSync`), with each Mac's real @@ -225,6 +226,43 @@ struct ClusterApprovalSyncTests { await mock.shutdown() } + /// The owner's own admission of a committed start (`DistributedInstalledOwner.memberAuthorizer`) under a saved + /// model approval: the start must carry this Mac's own setup's runtime block, the one its member registers. + @Test func theOwnerAdmitsAStartUnderAModelApprovalOnlyWithItsSetupsRuntime() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let model = macs.modelApproval(), facts = try macs.facts() + #expect(macs.sync(.approvals([model]), leaderFacts: facts, followerFacts: facts).changed) + let saved = try macs.saved(macs.leader), member = try #require(saved.configuration.nativeMember) + let plan = try DistributedInstalledPlan(saved: saved, paths: macs.leader.paths) + let admit = try DistributedInstalledOwner.memberAuthorizer(plan: plan, attachment: member) + let own = DistributedInstalledNativeStart.runtimeBlock(plan: plan) + #expect(own.nativeRuntimeSHA256 == saved.capability.runtimeBinarySHA256) + func start(_ runtime: ClusterPlan.Runtime) throws -> ClusterNativeAuthorizationStart { + func bytes(_ hex: String) throws -> Data { try #require(NativePairMemberPolicy.digest(hex: hex)) } + let common = try ClusterNativeAuthorizationCommon(epoch: UUID(), membershipGeneration: 7, nativePolicyGeneration: model.generation, + membershipTranscriptSHA256: memberDigest("model-approval-membership"), + approvedNativeBindingSHA256: Data(SHA256.hash(data: try member.policyBytes)), + planSHA256: try bytes(plan.partition.planSHA256), artifactSHA256: try bytes(model.artifactSHA256), + nativeRuntimeSHA256: try bytes(runtime.nativeRuntimeSHA256), capabilitySHA256: try bytes(runtime.capabilitySHA256), + resourcePolicySHA256: try bytes(runtime.resourcePolicySHA256), profileSHA256: try bytes(runtime.profileSHA256), + schedule: .serial, maximumTransportFrameBytes: Int(model.maximumTransportFrame), + limits: .init(maximumPlaintextBytes: Int(model.maximumPlaintext), maximumRecordsPerDirection: model.maximumRecords, + maximumCumulativePlaintextBytesPerDirection: model.maximumCumulativePlaintext)) + return try .init(common: common, rank: plan.configuration.localRank, ownerIncarnation: UUID(), leaseID: UUID(), + launchID: UUID()) + } + try admit(try start(own)) + let other = ClusterApprovalMacs.hash("9") + for runtime in [ + ClusterPlan.Runtime(nativeRuntimeSHA256: other, capabilitySHA256: own.capabilitySHA256, + resourcePolicySHA256: own.resourcePolicySHA256, profileSHA256: own.profileSHA256), + ClusterPlan.Runtime(nativeRuntimeSHA256: own.nativeRuntimeSHA256, capabilitySHA256: own.capabilitySHA256, + resourcePolicySHA256: other, profileSHA256: own.profileSHA256), + ] { + #expect(throws: ClusterConfigurationError.self) { try admit(try start(runtime)) } + } + } + @Test func aModelApprovalForAnotherArtifactIsSavedOnNeitherMac() throws { let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") let before = try macs.macs.map(macs.bytes), saved = try macs.saved(macs.leader) From 56f8a255472d4fc8962fca5537e702bbf3074ea3 Mon Sep 17 00:00:00 2001 From: David Tai Date: Fri, 30 Oct 2026 16:05:04 -0500 Subject: [PATCH 7/7] fix (review): say that listed numerics classes pin the metallib Co-Authored-By: Claude Opus 5.5 --- docs/reference/configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 412ffef6b3..adce5c06b2 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1119,7 +1119,7 @@ in its development deployment (DevNet); see the coordinator's documentation in | Shape | Exactly 14 fields: `id`, `model`, `generation`, `artifact_sha256`, `schedule`, `maximum_transport_frame`, `maximum_plaintext`, `maximum_records`, `maximum_cumulative_plaintext`, `allowed_numerics_classes`, `minimum_members`, `maximum_members`, `minimum_member_usable_bytes`, `not_after`. The build-pinned shape adds `placement_policy_sha256`, `native_runtime_sha256`, `metallib_sha256`, `resource_library_sha256`, `capability_sha256`, `resource_policy_sha256` and `profile_sha256`. An entry with some but not all of these seven, or with a null one, is refused | `provider-swift/Sources/ProviderCore/Config/ClusterRuntimeApproval.swift` (`ClusterRuntimeApproval`, `isEntry`, `init(from:)`) | | Canonical bytes | Domain `darkbloom/coordinator-cluster-model-approval/v1` and a zero byte, then the cluster approval's layout without the placement digest and the six runtime digests: `id`, `model`, `generation`, `artifact_sha256`, bytes `1, 1, schedule`, frame, plaintext, records, cumulative, `not_after` (nanoseconds), member bounds, usable bytes, grant lease terms, numerics classes. Their SHA-256 is the `policy_sha256` the member registers. Two golden vectors are pinned in `ClusterModelApprovalTests` and in the coordinator's tests | `ClusterRuntimeApproval.canonicalPolicy`; `provider-swift/Sources/ProviderCore/Coordinator/NativePairMemberPolicy.swift` (`modelDomain`) | | Plan runtime block | The member's plan for a model approval carries `runtime`: `native_runtime_sha256` (the saved setup's `capability.runtimeBinarySHA256`), `capability_sha256` (the setup's `capabilitySHA256`), `resource_policy_sha256` (`DistributedInstalledNativeStart.resourcePolicySHA256` of the capability) and `profile_sha256` (`capability.profileFingerprint`). A plan for a build-pinned entry has none. The block is part of the plan, so both members must register the same one | `DistributedInstalledNativeStart.runtimeBlock`; `provider-swift/Sources/ProviderCore/Protocol/ClusterRosterRegistration.swift` (`ClusterPlan.runtime`) | -| Metallib and resource library | Hashed once when the member builds its registration. The metallib digest also gives the device profile's numerics class | `ClusterMemberPreparation.nativeMemberInstallation` | +| Metallib and resource library | Hashed once when the member builds its registration. The metallib digest also gives the device profile's numerics class. A model approval that lists numerics classes is in effect pinned to one metallib, because each class contains the first 8 hex characters of the metallib digest (`ClusterMemberDeviceProfile.numericsClass`); an empty list admits any class | `ClusterMemberPreparation.nativeMemberInstallation` | | Start | The start's worker, capability, resource-policy and profile digests must equal the member's own block; the artifact, schedule and limits must equal the entry's. At prepare, the worker hashes to the setup's pin and the metallib and resource library to the digests taken at registration. The owner admits the start against the same block from its own setup | `NativePairMemberPolicy.require`, `NativePairMemberInstallation` (`requireStart`, `verifyInstalledFiles`), `DistributedInstalledOwner.memberAuthorizer` | ### Guided link setup