diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eec41c3c91..4db41586b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -614,6 +614,9 @@ jobs: - name: Run cluster model provisioning checks if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} run: bash provider-swift/Tests/ClusterModelProvisioningChecks/run.sh provisioning + - name: Run cluster onboarding checks + if: ${{ !cancelled() && steps.toolchain.outcome == 'success' }} + run: bash provider-swift/Tests/ClusterOnboardingChecks/run.sh provider-test-gate: name: Provider Tests diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 20f7b55b75..953a4bb669 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -234,6 +234,12 @@ ready screen shows the registered line (`ClusterOnboardingReady.offered`, `OnboardingLive.offeredReadiness`). How the approval is fetched, matched, checked on each Mac and saved: [coordinator-paired member](../reference/configuration.md#coordinator-paired-member). +The control leader checks the approval again under the command lock +(`ClusterService.checkApproval`) and checks a save against its own files +before any part stops (`ClusterApprovalSync.apply`). It compares the other +Mac's approval only when that Mac reports one +(`ClusterApprovalCheck.peerApprovalID`). It counts the quick ends of a part +only from that part's own rank-log lines (`ClusterService.lastError(in:from:)`). `OnboardingLive` uses fresh peer display facts only while their authenticated member identity matches the current pairing. These labels do not rewrite saved serving intent or change model eligibility and placement. See the diff --git a/docs/developer/test.md b/docs/developer/test.md index eb543245b2..92fa1c0a97 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1643,7 +1643,11 @@ root for model-free pseudo-terminal checks of setup stages, menu selection, failed test responses, terminal restoration and plain output. Set `ONBOARDING_TRANSCRIPTS` to a private output directory to retain screen text. The harness compiles only the onboarding flow, terminal and scripted operations; -it does not configure a network port, start a service or load a model. +it does not configure a network port, start a service or load a model. CI runs +it in the `Cluster Metadata Checks` job (step `Run cluster onboarding checks`). +Its rows include the end of the setup after the cluster registers with the +coordinator: the screen waits for both parts to serve again before it says +Done (`leaderWaitsForThePartsAfterTheRegistration`). `ClusterOnboardingPeerLabelTests` checks the live adapter with injected pairing facts: fresh authenticated peer labels replace saved display names, changed diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 63b7c28866..23e9999784 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1027,7 +1027,8 @@ saves it on both Macs. The cluster service then runs each Mac's part as | 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 | | 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`). 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 when the other Mac refuses its approval, it saves its own setup without it too | `ClusterApprovalCheck.macsDiffer`, `ClusterApprovalSync.converge` | +| 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` | A coordinator that answers 404, serves no matching entry or serves only ended entries leaves both saved setups byte for byte as they were: nothing is sent diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift index 6da87babab..65b86ff2f8 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Installed/ClusterServiceWire.swift @@ -68,8 +68,9 @@ public struct ClusterServiceStatus: Codable, Sendable, Equatable { /// control leader makes the pair serve locally when either Mac's count reaches the solo server's limit. Nil from an /// older build. public var memberQuickEnds: Int? = nil - /// The ID of the cluster approval this Mac's saved setup carries (none: absent). The control leader compares it - /// with its own on each check and gives this Mac its own, or none, when they differ (`ClusterApprovalCheck`). + /// The ID of the cluster approval this Mac's saved setup carries, "" for none. Absent (nil) from a build that does + /// not report it, which the control leader never reads as "none" (`ClusterApprovalCheck.peerApprovalID`). The + /// leader compares it with its own on each check and gives this Mac its own, or none, when they differ. public var approvalID: String? = nil public struct Control: Codable, Sendable, Equatable { public var leaderID: String 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 012609cbd9..6ad32a8bf7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalCheck.swift @@ -43,7 +43,14 @@ enum ClusterApprovalCheck { return first || macsDiffer || (serving && (offered || setAside)) } - /// Whether the other Mac's saved cluster approval (`peerApprovalID`, from its status; nil: it did not answer) is not + /// The other Mac's saved cluster approval as its status reports it: `.some(id)`, `.some(nil)` for none, and nil when + /// it did not answer or its build does not report the field (an older follower), which is never compared. + static func peerApprovalID(_ status: ClusterServiceStatus?) -> String?? { + guard let reported = status?.approvalID else { return nil } + return .some(reported.isEmpty ? nil : reported) + } + + /// Whether the other Mac's saved cluster approval (`peerApprovalID`, from its status; nil: unknown) is not /// this Mac's. A pair approval saved by hand on this Mac is the operator's and never compared. static func macsDiffer(_ saved: ClusterConfigurationStore.Saved, peerApprovalID: String??) -> Bool { guard saved.configuration.nativeMember?.approval == nil, let peer = peerApprovalID else { return false } 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 67c3bbd304..db9acd072c 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift @@ -81,6 +81,44 @@ public enum ClusterApprovalSync { return Result(changed: true, line: line, note: .some(line)) } + /// The control leader's change for `step` (`ClusterService.checkApproval`, under the command lock). A save is first + /// checked against this Mac's own files and pairing, so no part stops for an approval this Mac refuses. Then `stop` + /// stops both parts (nil when they stopped, else the line why not, and nothing changes), the change runs on both + /// Macs, and `serve` starts the parts again. + static func apply(_ step: ClusterApprovalCheck.Step, grace: Double, paths: ClusterUserPaths, providerConfiguration: URL, + pairingStore: ClusterPairingStore, scratch: URL, now: Double, stop: () -> String?, serve: () -> Void, + sendToPeer: (ClusterServiceCommand) throws -> Void, chipClass: ClusterChipClass? = ClusterChipClass.local(), + facts: (ClusterConfiguration) throws -> ClusterRuntimeApprovalFacts = ClusterApprovalAttachment.installedFacts) + -> Result { + if case .keep = step { return .unchanged } + if case .save(let approval) = step, + let saved = try? ClusterApprovalAttachment.savedSetup(paths: paths, providerConfiguration: providerConfiguration) { + do { + _ = try ClusterApprovalAttachment.attachment(for: approval, saved: saved, paths: paths, pairingStore: pairingStore, + edge: nil, now: now, chipClass: chipClass, facts: facts) + } catch { + let line = "Not offered for pairing: this Mac's check refused it: \(refusal(error))" + return Result(changed: false, line: line, note: .some(line)) + } + } + if let failure = stop() { return Result(changed: false, line: failure, note: nil) } + defer { serve() } + switch step { + case .keep: + return .unchanged + case .save(let approval): + return run(fetched: .approvals([approval]), paths: paths, providerConfiguration: providerConfiguration, + pairingStore: pairingStore, scratch: scratch, now: now, sendToPeer: sendToPeer, chipClass: chipClass, facts: facts) + case .serveLocally(let approval, let reason): + return serveLocally(approval, line: reason.line(approval, grace: grace), paths: paths, + providerConfiguration: providerConfiguration, pairingStore: pairingStore, scratch: scratch, + sendToPeer: sendToPeer) + case .converge(let target): + return converge(target, paths: paths, providerConfiguration: providerConfiguration, pairingStore: pairingStore, + scratch: scratch, sendToPeer: sendToPeer) + } + } + /// `ClusterApprovalCheck.Step.converge`: the other Mac's saved cluster approval differs from this Mac's (a lost /// reply, a failed give-back), so it is given this Mac's (`target`), which it checks against its own files, or /// none. When it refuses this Mac's, this Mac saves its setup without it too: both Macs carry the approval, or @@ -111,9 +149,19 @@ public enum ClusterApprovalSync { catch { line += " (this Mac could not save its setup yet: \(refusal(error)))" } return Result(changed: true, line: line, note: .some(line)) } - let line = target.map { "The other Mac's cluster approval differed from this Mac's: both Macs now carry approval \($0.id)" } - ?? "The other Mac's cluster approval differed from this Mac's: neither Mac carries one now" - return Result(changed: true, line: line, note: nil) + guard let target else { + // None: this Mac also saves its setup without a cluster approval it still holds but does not offer (it + // ended, or the cluster serves locally only), so both Macs hold none and the next check finds no difference. + var line = "The other Mac's cluster approval differed from this Mac's: neither Mac carries one now" + if saved.configuration.nativeMember?.clusterApproval != nil { + do { _ = try ClusterApprovalAttachment.save(nil, saved: saved, paths: paths, providerConfiguration: providerConfiguration, + scratch: scratch) } + catch { line += " (this Mac could not save its setup yet: \(refusal(error)))" } + } + return Result(changed: true, line: line, note: nil) + } + return Result(changed: true, line: "The other Mac's cluster approval differed from this Mac's: both Macs now carry approval \(target.id)", + note: nil) } /// One run of the step. `sendToPeer` delivers an `approval` command over the cable and throws the other Mac's diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index c49f7a0386..80a4ea3922 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -110,6 +110,8 @@ public final class ClusterService: @unchecked Sendable { // and whether the running part is one. private var memberQuickEnds = 0 private var childIsMember = false + // Where the running part began writing its log (`lastError(in:from:)`). + private var childLogOffset: UInt64 = 0 // Derived control (ClusterServiceControl.swift). var control: ClusterControlNode? var controlResponder: ClusterSetupLinkExchange.Responder? @@ -924,7 +926,7 @@ public final class ClusterService: @unchecked Sendable { value.updating = updatingLine value.localOnly = record?.leadership.map { $0.scope.isLocalOnly } value.memberQuickEnds = memberQuickEnds - value.approvalID = configuration?.nativeMember?.clusterApproval?.id + value.approvalID = configuration?.nativeMember?.clusterApproval?.id ?? "" return value } } @@ -1030,68 +1032,88 @@ public final class ClusterService: @unchecked Sendable { self.nextApprovalCheck = Date().addingTimeInterval(ClusterOnboardingUpdate.checkEverySeconds) } } - let record = try? self.store.readRecord() - let scope = record?.leadership?.scope ?? .publicServing - var setAside = record?.approvalSetAside - guard let saved = try? ClusterApprovalAttachment.savedSetup(paths: paths, providerConfiguration: configuration) else { - return checked() - } - let offered = saved.configuration.nativeMember.map { - ClusterApprovalLifetime.offers($0, scope: scope, now: Date().timeIntervalSince1970) - } ?? false let live = self.controlLive - // The other Mac's saved cluster approval and its coordinator-paired parts' quick ends, from its status (nil - // when it does not answer): both Macs carry the same approval, or neither does. - let peer = try? JSONDecoder().decode(ClusterServiceStatus.self, from: live.command(.init(op: .status), seconds: 10)) - let peerApprovalID: String?? = peer.map { $0.approvalID } - let macsDiffer = ClusterApprovalCheck.macsDiffer(saved, peerApprovalID: peerApprovalID) - let asks = ClusterApprovalCheck.asks(first: first, serving: record?.leadership?.serving == true, scope: scope, - offered: offered, setAside: setAside != nil, macsDiffer: macsDiffer) - guard asks || macsDiffer else { return checked() } - // A local-only cluster settles a difference between the Macs without asking the coordinator. - let fetched = asks ? ClusterApprovalFetch.fetchBlocking(providerConfiguration: configuration) - ?? .unavailable("no coordinator is configured") : .unavailable("not asked") - let now = Date().timeIntervalSince1970 - if let ended = setAside, !ClusterApprovalLifetime.current(ended.approval, now: now) { - try? self.store.updateRecord { $0.approvalSetAside = nil } - setAside = nil + let watchBefore = self.lock.withLock { self.approvalWatch } + /// The step for the setup, record and other Mac as they are now, for one answer of the coordinator. + struct Decided { + let step: ClusterApprovalCheck.Step + let watch: ClusterApprovalCheck.Watch + let serving: Bool } - // Both Macs' coordinator-paired parts that ended in a row right after starting. - let quickEnds = max(self.lock.withLock { self.memberQuickEnds }, peer?.memberQuickEnds ?? 0) - var watch = self.lock.withLock { self.approvalWatch } - 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) - self.lock.withLock { self.approvalWatch = watch } - guard step != .keep else { return checked() } - // A person's command and this never run at once; a busy lock is tried again at the next tick. - guard let held = ClusterControlCommandLock.acquire(seconds: 5) else { return } - defer { held.release() } - checked() - let serving = (try? self.store.readRecord())?.leadership?.serving == true - if serving { - if case .failure(let failure) = live.localStop() { - return say("could not stop the parts to change the cluster approval: " + failure.lines.joined(separator: " ")) + func decide(_ answer: () -> ClusterApprovalFetch.Outcome?) -> Decided? { + let record = try? self.store.readRecord() + let scope = record?.leadership?.scope ?? .publicServing + var setAside = record?.approvalSetAside + guard let saved = try? ClusterApprovalAttachment.savedSetup(paths: paths, providerConfiguration: configuration) else { + return nil } - guard live.drained(seconds: 300) else { - try? self.store.updateRecord { $0.leadership?.serving = true } - return say("a part did not stop within 5 minutes: the cluster approval stays as it is") + let now = Date().timeIntervalSince1970 + let offered = saved.configuration.nativeMember.map { ClusterApprovalLifetime.offers($0, scope: scope, now: now) } ?? false + // The other Mac's saved cluster approval and its coordinator-paired parts' quick ends, from its status + // (unknown when it does not answer or does not report them): both Macs carry the same approval, or neither. + let peer = try? JSONDecoder().decode(ClusterServiceStatus.self, from: live.command(.init(op: .status), seconds: 10)) + let peerApprovalID = ClusterApprovalCheck.peerApprovalID(peer) + let macsDiffer = ClusterApprovalCheck.macsDiffer(saved, peerApprovalID: peerApprovalID) + let asks = ClusterApprovalCheck.asks(first: first, serving: record?.leadership?.serving == true, scope: scope, + offered: offered, setAside: setAside != nil, macsDiffer: macsDiffer) + guard asks || macsDiffer else { return nil } + // A local-only cluster settles a difference between the Macs without asking the coordinator. + guard let fetched = asks ? answer() : .unavailable("not asked") else { return nil } + if let ended = setAside, !ClusterApprovalLifetime.current(ended.approval, now: now) { + try? self.store.updateRecord { $0.approvalSetAside = nil } + setAside = nil } + let quickEnds = max(self.lock.withLock { self.memberQuickEnds }, peer?.memberQuickEnds ?? 0) + var watch = watchBefore + 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) } - let send: (ClusterServiceCommand) throws -> Void = { request in _ = try live.command(request, seconds: 180) } - let result: ClusterApprovalSync.Result - switch step { - case .keep: return - case .save(let approval): - result = ClusterApprovalSync.run(fetched: .approvals([approval]), paths: paths, providerConfiguration: configuration, - pairingStore: pairingStore, scratch: scratch, now: Date().timeIntervalSince1970, sendToPeer: send) - case .serveLocally(let approval, let reason): - result = ClusterApprovalSync.serveLocally(approval, line: reason.line(approval, grace: ClusterService.soloGraceSeconds), - paths: paths, providerConfiguration: configuration, pairingStore: pairingStore, scratch: scratch, sendToPeer: send) - case .converge(let target): - result = ClusterApprovalSync.converge(target, paths: paths, providerConfiguration: configuration, - pairingStore: pairingStore, scratch: scratch, sendToPeer: send) + var fetched: ClusterApprovalFetch.Outcome? + func answer() -> ClusterApprovalFetch.Outcome? { + if fetched == nil { + fetched = ClusterApprovalFetch.fetchBlocking(providerConfiguration: configuration) ?? .unavailable("no coordinator is configured") + } + return fetched } + guard let initial = decide(answer) else { return checked() } + self.lock.withLock { self.approvalWatch = initial.watch } + guard initial.step != .keep else { return checked() } + // A person's command and this never run at once. A busy lock is tried again at the next check, a minute on, + // not at every tick. + guard let held = ClusterControlCommandLock.acquire(seconds: 5) else { + say("another cluster command is running: the cluster approval is checked again in a minute") + return checked() + } + defer { held.release() } + checked() + // Decided again under the lock, with the same answer: a person's command may have changed the setup, the + // scope or the other Mac while this check waited. + guard let decided = decide(answer) else { return } + self.lock.withLock { self.approvalWatch = decided.watch } + let step = decided.step, serving = decided.serving + guard step != .keep else { return } + let send: (ClusterServiceCommand) throws -> Void = { request in _ = try live.command(request, seconds: 180) } + let result = ClusterApprovalSync.apply(step, grace: ClusterService.soloGraceSeconds, paths: paths, + providerConfiguration: configuration, pairingStore: pairingStore, scratch: scratch, now: Date().timeIntervalSince1970, + stop: { + guard serving else { return nil } + if case .failure(let failure) = live.localStop() { + return "could not stop the parts to change the cluster approval: " + failure.lines.joined(separator: " ") + } + guard live.drained(seconds: 300) else { + try? self.store.updateRecord { $0.leadership?.serving = true } + return "a part did not stop within 5 minutes: the cluster approval stays as it is" + } + return nil + }, + serve: { + guard serving, case .failure(let failure) = live.localServe() else { return } + try? self.store.updateRecord { $0.leadership?.serving = true } + say("could not start the parts again after the cluster approval changed: " + failure.lines.joined(separator: " ")) + }, + sendToPeer: send) try? self.store.updateRecord { stored in if let note = result.note { stored.approvalNote = note } // The approval set aside is kept while the pair serves locally and dropped once one is saved again. @@ -1101,10 +1123,6 @@ public final class ClusterService: @unchecked Sendable { if case .save = step, result.changed { stored.approvalSetAside = nil } } if let line = result.line { say(line) } - if serving, case .failure(let failure) = live.localServe() { - try? self.store.updateRecord { $0.leadership?.serving = true } - say("could not start the parts again after the cluster approval changed: " + failure.lines.joined(separator: " ")) - } } } @@ -1113,11 +1131,14 @@ public final class ClusterService: @unchecked Sendable { (try? paths().rankLog).flatMap { lastError(in: $0) } } - private static func lastError(in log: URL) -> String? { + /// The same in `log`, reading only from `offset` on (where the part that ended began writing), so an error an + /// earlier part wrote is never taken for this part's. A log shorter than `offset` was replaced: it is read whole. + static func lastError(in log: URL, from offset: UInt64 = 0) -> String? { guard let handle = FileHandle(forReadingAtPath: log.path) else { return nil } defer { try? handle.close() } let size = (try? handle.seekToEnd()) ?? 0 - try? handle.seek(toOffset: size > 16_384 ? size - 16_384 : 0) + let window: UInt64 = size > 16_384 ? size - 16_384 : 0 + try? handle.seek(toOffset: offset <= size ? max(offset, window) : window) let tail = String(decoding: handle.readDataToEndOfFile(), as: UTF8.self) guard let line = tail.split(whereSeparator: \.isNewline).last(where: { $0.hasPrefix("Error:") }) else { return nil } return ClusterConsoleText.plain(ClusterConsoleText.bounded(String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces), maximum: 240)) @@ -1267,7 +1288,7 @@ public final class ClusterService: @unchecked Sendable { // A coordinator-paired part that keeps ending right after its start makes the leader serve locally // (`ClusterApprovalCheck.step`); an end because the coordinator was out of reach is not counted. if lock.withLock({ childIsMember }) { - let lastError = Self.lastError(in: serviceFiles.rankLog) + let lastError = Self.lastError(in: serviceFiles.rankLog, from: lock.withLock { childLogOffset }) lock.withLock { memberQuickEnds = ClusterApprovalCheck.memberQuickEnds(after: memberQuickEnds, ranSeconds: ran, lastError: lastError) } } // F14: a solo server that keeps ending right after its start is not started again for this plan and model @@ -1394,7 +1415,8 @@ public final class ClusterService: @unchecked Sendable { process.standardInput = FileHandle.nullDevice let log = serviceFiles.rankLog if !FileManager.default.fileExists(atPath: log.path) { FileManager.default.createFile(atPath: log.path, contents: nil, attributes: [.posixPermissions: 0o600]) } - if let handle = try? FileHandle(forWritingTo: log) { handle.seekToEndOfFile(); process.standardOutput = handle; process.standardError = handle } + var logOffset: UInt64 = 0 + if let handle = try? FileHandle(forWritingTo: log) { logOffset = handle.seekToEndOfFile(); process.standardOutput = handle; process.standardError = handle } beforePartStart?() do { try process.run() } catch { say("\(what) could not start: \(error)") @@ -1404,7 +1426,7 @@ public final class ClusterService: @unchecked Sendable { let startedAt = ClusterProcessTable.startTime(of: process.processIdentifier) lock.withLock { child = process; childSetup = key; childPort = port; childStarted = Date(); childStartedAt = startedAt; starts += 1 - childIsMember = memberRoute + childIsMember = memberRoute; childLogOffset = logOffset if !memberRoute { memberQuickEnds = 0 } } say("started \(what) (pid \(process.processIdentifier))") diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index 3a125b6a09..08bca38f4d 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -156,7 +156,7 @@ import Darwin expect(run.text.contains("\u{1B}[\(ClusterOnboardingBrand.height)A") == animated, "colour: the mark blooms only when animating") expect(!run.text.contains("\u{1B}[2J") && !run.text.contains("\u{1B}[H"), "colour: no screen clearing") expect(recorder.all == ["checkLink", "pair", "answer y", "ensureService", "reachMembers", "planModels", "recheckFit 0", "adopt 0", - "serve", "waitReady", "testRequest"], "colour: operations in order: \(recorder.all)") + "serve", "waitReady", "testRequest", "register"], "colour: operations in order: \(recorder.all)") } // The mark and the meter themselves. expect(ClusterOnboardingBrand.rows() == ["\u{2588}\u{2588}\u{2588}\u{2588} \u{2580}\u{2580}\u{2588}\u{2588} \u{2588}\u{2588}", @@ -202,7 +202,7 @@ import Darwin let stages = ["1 / 5 Connect the Macs", "2 / 5 Pair securely", "3 / 5 Choose a model", "4 / 5 Start the model", "5 / 5 Test a response"] let rows = stages.compactMap { stage in screen.firstIndex { $0.contains(stage) } } expect(rows.count == stages.count && rows == rows.sorted(), "\(label): stages in order") - expect(recorder.all.last == "testRequest", "\(label): the setup ran to its test: \(recorder.all)") + expect(Array(recorder.all.suffix(2)) == ["testRequest", "register"], "\(label): the setup ran to its test: \(recorder.all)") } } @@ -228,7 +228,7 @@ import Darwin "45 columns: no mark and no bloom climb") expect(screen.contains { $0.contains("1 / 5 Connect the Macs") && $0.contains("\u{25CF}\u{25CB}\u{25CB}\u{25CB}\u{25CB}") }, "45 columns: headings keep the meter") - expect(recorder.all.last == "testRequest", "45 columns: the setup ran to its test: \(recorder.all)") + expect(Array(recorder.all.suffix(2)) == ["testRequest", "register"], "45 columns: the setup ran to its test: \(recorder.all)") // A live line wider than a 44-column window, drawn directly. var primary: Int32 = -1, secondary: Int32 = -1 var window = winsize(ws_row: 24, ws_col: 44, ws_xpixel: 0, ws_ypixel: 0) @@ -836,8 +836,8 @@ import Darwin run.type("2\r") expect(run.waitFor("Starting Qwen3.8-27B-4bit-mtp on both Macs in 3 s"), "member model change: second model") expect(run.finish() == 0, "member model change: served") - expect(recorder.all == ["ensureService", "status", "reachMembers", "planModels", "recheckFit 1", "adopt 1", "serve", "waitReady", "testRequest"], - "member model change: every step through the operations (forwarded live): \(recorder.all)") + expect(recorder.all == ["ensureService", "status", "reachMembers", "planModels", "recheckFit 1", "adopt 1", "serve", "waitReady", "testRequest", + "register"], "member model change: every step through the operations (forwarded live): \(recorder.all)") expect(run.text.contains("Done. Run `darkbloom cluster` on any of these Macs"), "member model change: any Mac") // The leader saves the setup and sends it here: said from this Mac's side. expect(run.text.contains("Saving the setup on the other Mac, which sends it to this Mac over the cable…\n") @@ -955,8 +955,8 @@ import Darwin expect(run.waitFor("every file matched its manifest digest."), "copy: verified") expect(run.waitFor("Starting Qwen3.5-9B on both Macs in 3 s; press n to stop here."), "copy: then the timed start") expect(run.finish() == 0, "copy: served") - expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest"], - "copy: copied before the setup is synced: \(recorder.all)") + expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest", + "register"], "copy: copied before the setup is synced: \(recorder.all)") expect(run.keys == 2, "copy: enter (model), enter (copy); got \(run.keys)") expect(!run.text.lowercased().contains("ssh") && !run.text.contains("--model-dir"), "copy: no SSH, no model folder to type") transcript("leader-copies-missing-model", run.text, keys: run.keys) @@ -989,8 +989,8 @@ import Darwin expect(run.waitFor(" rank 1 (decodes): Apple M5 Ultra, 256 GB (this Mac), layers 32-63"), "download: the plan shown") expect(run.waitFor("Starting Qwen3.8-27B-4bit-mtp on both Macs in 3 s"), "download: timed start") expect(run.finish() == 0, "download: served") - expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "planModels", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest"], - "download: downloaded, planned again, then adopted: \(recorder.all)") + expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "planModels", "recheckFit 0", "adopt 0", "serve", "waitReady", + "testRequest", "register"], "download: downloaded, planned again, then adopted: \(recorder.all)") transcript("leader-downloads-model", run.text, keys: run.keys) } @@ -1047,8 +1047,8 @@ import Darwin expect(run.waitFor("Starting Qwen3.5-9B on both Macs in 3 s; press n to stop here."), "short copy: copied without a key, then the timed start") expect(run.finish() == 0, "short copy: served") expect(!run.text.contains("Press enter to copy it over the Thunderbolt cable"), "short copy: not asked") - expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest"], - "short copy: copied before the setup is synced: \(recorder.all)") + expect(recorder.all == ["ensureService", "reachMembers", "planModels", "provision 0 copy", "recheckFit 0", "adopt 0", "serve", "waitReady", "testRequest", + "register"], "short copy: copied before the setup is synced: \(recorder.all)") expect(run.keys == 1, "short copy: enter (model) only; got \(run.keys)") transcript("leader-short-copy-not-asked", run.text, keys: run.keys) } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift index 131750d8ec..67eaf97136 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalWatchTests.swift @@ -253,4 +253,93 @@ struct ClusterApprovalWatchTests { #expect(refused.changed && refused.line?.contains("neither Mac carries cluster approval") == true, "\(refused.line ?? "")") for mac in macs.macs { #expect(try macs.saved(mac).configuration.nativeMember == nil, "rank \(mac.rank)") } } + + @Test func aPartsQuickEndsAreCountedFromItsOwnLogLinesOnly() throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("rank-log-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: folder) } + let log = folder.appendingPathComponent("rank.log") + // An earlier part ended because the coordinator was out of reach; then the next part starts writing here. + try Data(("Error: " + ClusterMemberControlError.coordinatorUnreachable.rawValue + "\n").utf8).write(to: log) + let offset = UInt64(try Data(contentsOf: log).count) + // The next part ends quickly without an error line of its own: its end is not the coordinator's and counts. + #expect(ClusterService.lastError(in: log, from: offset) == nil) + #expect(ClusterApprovalCheck.memberQuickEnds(after: 1, ranSeconds: 5, + lastError: ClusterService.lastError(in: log, from: offset)) == 2) + // Its own error line is the one read. + let handle = try FileHandle(forWritingTo: log) + try handle.seekToEnd() + try handle.write(contentsOf: Data("Error: Saved cluster approval does not cover this Mac's chip\n".utf8)) + try handle.close() + #expect(ClusterService.lastError(in: log, from: offset) == "Saved cluster approval does not cover this Mac's chip") + // The whole log still names the earlier part's line before it. + #expect(ClusterService.lastError(in: log)?.hasPrefix("Saved cluster approval") == true) + #expect(ClusterService.lastError(in: log, from: offset + 4_096)?.hasPrefix("Saved cluster approval") == true, + "a log shorter than the offset was replaced and is read whole") + } + + @Test func aFollowerThatDoesNotReportItsApprovalIsNeverTakenForOneWithout() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let approval = macs.approval(), facts = try macs.facts() + #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed) + let leaderSaved = try macs.saved(macs.leader) + func status(_ approvalID: String?) throws -> ClusterServiceStatus { + var object: [String: Any] = ["serving": true, "sessionLeader": false, "child": ["running": true, "starts": 1]] + if let approvalID { object["approvalID"] = approvalID } + return try JSONDecoder().decode(ClusterServiceStatus.self, from: JSONSerialization.data(withJSONObject: object)) + } + // An older follower build sends no field: unknown, never "no approval", so nothing converges. + let older = ClusterApprovalCheck.peerApprovalID(try status(nil)) + #expect(older == nil) + #expect(!ClusterApprovalCheck.macsDiffer(leaderSaved, peerApprovalID: older)) + #expect(try step(macs, .approvals([approval]), peer: older, Watched(), clock: 0) == .keep) + // A follower that reports none ("") differs from the leader's approval; one that reports the same ID does not. + let none = ClusterApprovalCheck.peerApprovalID(try status("")) + #expect(none == .some(nil) && ClusterApprovalCheck.macsDiffer(leaderSaved, peerApprovalID: none)) + let same = ClusterApprovalCheck.peerApprovalID(try status(approval.id)) + #expect(same == .some(approval.id) && !ClusterApprovalCheck.macsDiffer(leaderSaved, peerApprovalID: same)) + // No answer at all is unknown too. + #expect(ClusterApprovalCheck.peerApprovalID(nil) == nil) + } + + @Test func convergingOnNoneAlsoClearsTheLeadersApprovalThatIsNotOffered() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let facts = try macs.facts(), approval = macs.approval() + #expect(macs.sync(.approvals([approval]), leaderFacts: facts, followerFacts: facts).changed) + // The other Mac lost its copy; the leader serves locally only now, so its own approval is not offered. + try macs.cable(facts: facts)(ClusterServiceCommand(op: .approval)) + let local = ClusterServingScope.localOnly(bind: "127.0.0.1"), lost = try peerID(macs) + #expect(try step(macs, .unavailable("not asked"), peer: lost, scope: local, Watched(), clock: 0) == .converge(nil)) + let result = converge(macs, nil, followerFacts: facts) + #expect(result.changed && result.line?.hasSuffix("neither Mac carries one now") == true, "\(result.line ?? "")") + // Both Macs hold none, so the next check finds no difference and does not repeat. + for mac in macs.macs { #expect(try macs.saved(mac).configuration.nativeMember == nil, "rank \(mac.rank)") } + let leaderSaved = try macs.saved(macs.leader), settled = try peerID(macs) + #expect(!ClusterApprovalCheck.macsDiffer(leaderSaved, peerApprovalID: settled)) + } + + @Test func noPartStopsForAnApprovalTheLeadersOwnCheckRefuses() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let approval = macs.approval(), facts = try macs.facts(), before = try macs.macs.map(macs.bytes) + var stops = 0, serves = 0 + func apply(stop: () -> String?, leaderFacts: ClusterRuntimeApprovalFacts) -> ClusterApprovalSync.Result { + ClusterApprovalSync.apply(.save(approval), grace: grace, paths: macs.leader.paths, providerConfiguration: macs.leader.provider, + pairingStore: macs.leader.pairing, scratch: macs.leader.scratch, now: Date().timeIntervalSince1970, + stop: stop, serve: { serves += 1 }, sendToPeer: macs.cable(facts: facts), chipClass: ClusterApprovalMacs.chip, + facts: { _ in leaderFacts }) + } + // The leader's own check refuses the entry: no part stops, nothing is sent, nothing starts again. + let refused = apply(stop: { stops += 1; return nil }, leaderFacts: try macs.facts(differing: "metallib_sha256")) + #expect(!refused.changed && stops == 0 && serves == 0) + #expect(refused.line?.contains("this Mac's check refused it") == true, "\(refused.line ?? "")") + #expect(try macs.macs.map(macs.bytes) == before) + // The parts do not stop: nothing changes and nothing starts. + let unstopped = apply(stop: { "a part did not stop within 5 minutes" }, leaderFacts: facts) + #expect(!unstopped.changed && unstopped.line == "a part did not stop within 5 minutes" && serves == 0) + #expect(try macs.macs.map(macs.bytes) == before) + // Accepted: both parts stop once, both Macs save it, both parts start once. + let saved = apply(stop: { stops += 1; return nil }, leaderFacts: facts) + #expect(saved.changed && stops == 1 && serves == 1) + for mac in macs.macs { #expect(try macs.saved(mac).configuration.nativeMember?.clusterApproval == approval, "rank \(mac.rank)") } + } }